INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to create an account for contacts in Android? I'm creating an app that manages the phonebook of the device. In the phone, there are contact accounts like **com.google** or **com.htc.android.pcsc**. When the user adds a new contact, the contact will be assigned to an account. How do I **create such an account**? I'm quite unfamiliar with how the contacts account work. I would like to have a few pointers on where I should be looking this information for, if possible. Thanks everyone!
If anyone were to create this custom accounts. You will have to create one of this using the accountManagers. That means somehow you have to write your own syncadapters and stuff like that in order to let Android recognise you as one of the accounts. However there's a bug that restrict editing of contacts that are from this custom accounts. Therefore, i'm not going to implement this feature in my app.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "android, android contacts" }
Существует ли инструментарий для создания анимации в material design? В описании концепции `material design` есть обзорное видео `motion`: MaterialMotionHero Spec 0505 Наверняка Google написали инструментарий, как обычно. Будь я на их месте, я бы вообще создал отдельную программу, по примеру `JavaFX Scene Builder` для `JavaFX`. Но может быть, такой инструментарий существует? Приложение или стандартные библиотеки, написанные специально для `material design`?
Инструментов нет - остается писать самим, либо использовать готовое: GitHub, AndroidArsenal Если надумаете писать сами, можете посмотреть исходники вот этой библиотеки: Material-Animations \- скрины анимаций ниже, информация на русском языке: Animation и Transition, Анимация преобразований, Векторная анимация в приложениях android, Building Apps with Graphics & Animation, Установка пользовательских анимаций в Material Design ![введите сюда описание изображения]( ![введите сюда описание изображения]( ![введите сюда описание изображения]( ДОБАВЛЕНО: Также, пользовательскую анимацию можно установить при помощи библиотек: `Animation`, `ObjectAnimator`, `ViewAnimationUtils`, `Transition`.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, material design" }
Can the limiting process be used to differentiate $f(x)=x$? If so, then why is $dy/dx=0$? Slope=$∆x/∆x=1$ $\lim_{∆x\to0} ∆x/∆x=0$ Therefore $dx/dx$ should be $0$. Is this right, if not pls correct.
The following statement you made in the question is not correct: Slope=$∆x/∆x$ The slope is of the curve is (change in y over the change in x): $$∆y/∆x$$ Can the limiting process be used to differentiate f(x)=x ? Yes of course. Using the chart below, you want to find the limit as x approaches zero for the expression: $$\frac{x+∆x-x}{∆x}$$ $$ f'(x)=\lim\limits_{\Delta x \to 0}\frac{x+∆x-x}{∆x}=1=dy/dx$$ Therefore $dx/dx$ should be 0. Not so because the the derivative is actually $dy/dx=1$ from the above. This tells us that the rate of change for this function is constant and is always = $1$ for all $x$ values in its domain. All of these things are well described in many good Calculus books. ![enter image description here]( Ref: Image Source
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus" }
Making Bootable USB From DVD using Command line Is there any way to create a boot-able USB from a windows DVD via command line? It is accepted using third party application which accepts command line arguments. I searched internet but did not found any way.
You can do this using the program diskpart which is included in windows. You need the following steps: SELECT DISK <DRIVE NUMBER> CLEAN CREATE PARTITION PRIMARY SELECT PARTITION 1 ACTIVE FORMAT FS=NTFS QUICK ASSIGN EXIT save them in a txt file. Find out the drive number using "LIST DISK" You can then call diskpart with the /s parameter and give the saved textfile as a script. Afterwards you can copy the content of the dvd over. Now as to really do this programmatically: The main difficulty would be selecting the correct drive number in case it may vary. The main problem however is that this is a pretty dangerous operation. If you select the wrong disk (as stated those drives are selected by number not even by their drive letter) instead of your usb drive you might format a partition of your harddrive. I would personally not really fully automate the task but rather do it by hand.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "batch file, command line, windows 7, usb, boot" }
swift for windows platform and linux platform development As I known Cocotron GNUStep are the objectivec sdk for windows and linux. Just wonder if apple's new language Swift can work with Cocotron GNUStep on windows and linux. Your comment welcome
No. Currently Apple distributes Swift as part of Xcode6 betas, which only work on OS X. There are hints that Swift will be open sourced when it is finished, at which point it is up to the community to port it to different platforms. No doubt that will happen.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "swift" }
JavaFX 2 : TableView : remove header + show grid when empty I have 2 questions about the TableView in Javafx2: 1) Is it possible to hide the headers in your table? 2) When the table is empty it just shows a white pane saying "No content in table.". Is it possible to change this to display the default grid, even when the table is empty? If possible, Id like a solution with CSS (javacode is also fine). Thank you in advance.
Answer to the first question is here. Note that you may hide the headers only after the table is rendered. Answering your second question you may use following approach: table.setPlaceholder(new Label("Placeholder")); Instead of label you may add any `Node`.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "css, javafx 2, tableview, columnheader" }
Retrieve Session variables into ASP.NET MVC 4 (razor, view) I wrote many websites with PHP. Now, I have to create website with ASP MVC 4 (c#) and I am stuck with Sessions. I.E. the user should go to login page, enter his/her login and password. If they are correct, in controller, I set the session with UserId, like this: Session["UserId"] = 10 This UserId value is used for showing PartialViews (login form or (after login) some application menus). How can I get this UserId inside Razor view ? After this in View: if (Session.UserId == 10) { @Html.Partial("LoggedMenu") } i've got exception with StackOverflow. :/
you're doing it wrong... `Session[<item name>]` returns a string, you should compare with a string as well, or cast it, so, either `(int)Session["UserId"] == 10` or `Session["UserId"] = "10"`. you also are invoking a property that does not exist `Session.UserId` will not exist as `Session` is like an NameValueCollection, you call it by request it's item name. at the end, you should write @if (Session["UserId"] == "10") { Html.Partial("LoggedMenu"); } You say your are learning, so I would like to point out 2 quick things: * You should take advantage of the ASP.NET MVC Course that is available for free in the home page < (right side when you read "Essential Videos") * Create an MVC3 project and see how they do it as it comes ready out of the box with Membership
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 8, "tags": "asp.net mvc, asp.net mvc 4, session variables" }
Postfix: Is it possible to rebuild mail queue to fix incorrectly generated addresses? I am new to postfix and I was playing with the config file, with $mydomains and other variables. During this time I had some mails in the queue, and they now have incorrect to addresses showing in postfix queue like [email protected] When I look inside the mail body fortunately the To address is correct. Is it possible to rebuild the mail qiueue now that I corrected the postfix config?
I solved it by adding a fake "com.com" virtual domain, and created an email catch all rule for the original address, and then I requeued the mails. Arrgh
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "postfix" }
blackberry arabic text In my application, i need to show some english and arabic text in a `net.rim.device.api.ui.component.EditField`. The text comes from server encoded with UTF-8. @ iPhone it is works fine but on BB we see small black filled rectangles instead of Arabic text. I do not want to enforce users to download some font to see the text. I need embedded solution. I am developing for BB OS 4.5.
It is definitely a font issue. In OS 5+ you can ship your app with a custom font that supports Arabic and install it at run time. Instructions and sample code for how to do this can be found in this development guide topic. Unfortunately, there is any support for custom fonts pre-5.0 (see, e.g., this thread).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "blackberry, arabic" }
Can I make an LED turn OFF when current ON, and ON when current OFF? Im an electronics noob so this may be a stupid question....but here's some context to my problem. I am rebuilding a motorcycle and have swapped out the dash. There is a wire coming off the bike to illuminate a 'Neutral' light. Im pretty certain I have the right wire however whenever the bike is in neutral, the light extinguishes. Whenever the bike is in gear, the light illuminates. This is backwards. I need the light to come on when the bike is in neutral. Being a motorcycle, the system is 12V (i think?). I have rigged up all the other lights (backlights, indicators, high-beam) and all works well. So, first question... Does it make sense the circuit be rigged up this way? I have swapped a more modern digital dashboard for an analogue one if this is a factor. Second question... Can i inverse this to make the light do the opposite?
If it’s like most motorcycles, the neutral switch has a single pin that connects to engine case ground (closes) when the selector is in neutral. It’s open otherwise. You can check this with an ohmmeter. Some motorcycles might use a 2-pin connector if the engine is in an anti-vibration mount (e.g., a newer Harley), but nevertheless would connect to ground via the harness when closed. Normally the neutral lamp has one side connected to the switch and the other to the +12 from ignition. So current flows from 12V, though the lamp, then through the closed neutral switch to ground. If your dash has the lamp connected to the ignition switch then that’s almost you need to do (don’t forget to add a load resistor to the LED or you will fry it.)
stackexchange-electronics
{ "answer_score": 2, "question_score": 1, "tags": "transistors, led, light" }
Multiple if blocks or a single if with AND condition If I need to check multiple conditions, which is the preferred way with respect to performance if( CND1 && CND2 && CND3 && CND4) { } else { } or if(CND1) { if(CND2) { if(CND3) { if(CND4) { } else { } } else { } } else { } } }
They will be identical in terms of performance, but the first form is much more readable IMO. The only situation in which I'd split the conditions up would be if there were sets of logical conditions: if (x && y) // x and y are related { if (a && b) // a and b are related { } } Although an alternative there which reads nicely (but does evaluate more conditions, admittedly) is: bool shouldPayBackDebt = x && y; bool haveEnoughFunds = a && b; if (shouldPayBackDebt && haveEnoughFunds) { // ... }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "c#, coding style" }
How to remove elements from the $_POST array? I want to insert a record into a MySQL database table from a formulaire. The problem is that there is a `field` that is not in the table's columns in the `$_POST` variable but it's displayed as a `textfield` in the `formulaire`. I insert the fields values by this way : $newRecord->insert($_POST); // we created a generic function insert($array) to insert records So how to remove an element of the $_POST ?
simply go: unset($_POST['field']);
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 3, "tags": "php, html, post, xhtml" }
Hilbert polynomial of an abelian scheme This is coming out of Mumford's GIT, section 7.2, page 131. $A/S$ an abelian scheme of dimension $g$ with polarization $\bar{\omega}$ of degree $d^2$. Then $\pi_*(L^\Delta(\bar{\omega})^3)$ is locally free on $S$ of rank $6^gd$ which defines the closed immersion $\varphi_3 : A \rightarrow \mathbb{P}(\pi_{*}(L^\Delta(\bar{\omega})^3))$. Equip this with a linear rigidification $\phi : \mathbb{P}(\pi_{*}(L^\Delta(\bar{\omega})^3)) \rightarrow \mathbb{P_m} \times S$ so that we get an embedding $I : A \rightarrow \mathbb{P_m} \times S$. Mumford then states the Hilbert Polynomial of $I(A)$ is easily computed to be $P(X) = 6^gdX^g$. Exactly how does one go about finding this Hilbert polynomial?
Let us look at a single geometric fiber $X$. Let $L^\Delta(\bar\omega)|_X = \mathcal{O}_X(D)$. The Riemann-Roch theorem for abelian varieties (Mumford "Abelian Varieties", Chap. 3 Section 16) states that $$ \chi(\mathcal{O}_X(D)) = D^g/g!$$ and moreover that $\chi(\mathcal{O}_X(D))^2 = \deg \phi$, where $\phi$ is the polarization map defined by $\mathcal{O}_X(D)$. So the Hilbert polynomial $\chi(\mathcal{O}_X(3nD)) = 3^gn^gD^g/g! = 3^g n^g \chi(\mathcal{O}_X(D)) = 3^g n^g d$. I got almost the right answer (where did $2^g$ go?), so maybe I misunderstood the question, but I hope this is still helpful. EDIT. Is the superscript $\Delta$ the symmetrization of the line bundle in question? Then it would explain why the $2^g$ above is missing...
stackexchange-mathoverflow_net_7z
{ "answer_score": 2, "question_score": 1, "tags": "ag.algebraic geometry, geometric invariant theory" }
Is it possible to define a wx.Panel as a class in Python? I want to define several plugins. They all inherit from the superclass Plugin. Each plugin consists on a wx.Panel that have a more specific method called "draw". How can I define a class as a Panel and afterwards call that class in my frame? I've tried like this: class Panel(wx.Panel): def __init__(self, parent): wx.Panel(self, parent) but it gives me this error: in __init__ _windows_.Panel_swiginit(self,_windows_.new_Panel(*args, **kwargs)) TypeError: in method 'new_Panel', expected argument 1 of type 'wxWindow *' Thanks in advance!
class MyPanel(wx.Panel): def __init__(self, *args): wx.Panel.__init__(self, *args) def draw(self): # Your code here
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "python, class, wxpython, panel, frame" }
Python return two separate objects in one 'return' Is it possible to return two separate object in one 'return' statement? I have tried below but I get 'tuple' object. recipient, user = authenticate(mobile=mobile, email=email) Function: def authenticate(self, mobile=None, email=None): user = Recipient.objects.recipient_friend_match(mobile, email) return user[0], user
return tuple is right,you can get them like this def fun(): a = 4 b = [1,2,3,4] return a,b # equals to return (a,b) a,b=fun() just print a and b to see the results
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, django" }
How To Get The Line Count Of A RichTextBox Is there a simple way to simulate `TextBox.LineCount` for a `RichTextBox`? I've been looking at other posts and solutions but they're extremely outdated. Other Posts: Richtextbox lines count How many Lines in RichTextBox
Get the text from the control and split it to an array with `Environment.NewLine` separator then you can check the length of the array to get the line count. private void button_Click(object sender, RoutedEventArgs e) { TextRange MyText = new TextRange( richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd ); string[] splittedLines = MyText.Text.Split(new[] { Environment.NewLine } , StringSplitOptions.None); // or StringSplitOptions.RemoveEmptyEntries MessageBox.Show(splittedLines.Length.ToString()); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, wpf, richtextbox" }
Why am I getting objects printed twice? When I am in irb or in rails and I create some iteration with `each`, I am getting the whole struct printed again in my terminal or inside the browser. Example: a = [1,2,3,4] a.each do |number| puts n end The result in irb terminal or inside the browser: 1 2 3 4 => [1,2,3,4] Why does this `=> [1,2,3,4]` appear inside the browser? I can't create a single list in my page because the whole structure appears.
Every expression in Ruby returns a value; in `irb`, the value returned by the expression you've just executed is displayed after `=>`. The return value of `Enumerable::each` is the object that called `each` \- in this case, the array `[1,2,3,4]`
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ruby, irb" }
Limit typescript interface to another interface Given a typescript interface: interface alpha { name?: string; age?: string; sign?: string; } I would like to create another interface that is confined to have a limited set of properties from another interface interface beta { age?: string; } Is this possible? If someone was to have: interface beta { foo?: string; } I'd like it to be invalid.
Great answer here: How to remove fields from a TypeScript interface via extension So you make a "helper type" called e.g. `Omit` to omit certain properties from your interface: type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> Likewise, you can also modify the properties of your existing interface, which can be useful many times: type Readonly<T> = { readonly [P in keyof T]: T[P]; } type Partial<T> = { [P in keyof T]?: T[P]; } Also, sometimes it's easier to turn it around. Extend alpha from beta. interface alpha extends beta { name?: string; sign?: string; } interface beta { age?: string; } const x: alpha = { name: "foo" // valid } const y: beta = { name: "where" // invalid }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "typescript" }
link to gpgme library in Visual Studio I found this old post: Using the gpgme library from .NET? but it can't help me to link my C++ project (Visual Studio) to libgpgme-11.dll. I am using Windows 10 platform, and have done the followings to try to set it up: Properties->Linker->Input: **libgpgme-11.dll** Properties->Linker->Additional Library Directories: **Gpg4win\lib** and **Gpg4win\bin_64** Properties->C/C++ General->Additional Include Directories: **Gpg4win\include** When I compiled the project, I got an Link error LNK1107 invalid or corrupt file: can not read at 0x368. It seems to me that the libgpgme-11.dll is not the correct one to link against. Yet, I don't find any gpgme lib files under the root Gpg4win folder. Any recommendation ? Eric
There are three things to do in setting gpgme in Visual Studio: 1. Add "Gpg4win\include" to the "Additional Include Directories" property 2. Add "Gpg4win\bin and Gpg4win\lib" to the "Additional Library Directories" property 3. Add " **libgpgme.imp** " to the "Additional Dependencies" property The Additional Library Directories and Additional Dependencies properties are under Linker's **General** and **Input** tabs. The Additional Include Directories property is under C/C++ **General** tab. Hope this saves someone else's time.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "visual studio, gpgme" }
Getting AttributeError: module 'matplotlib._image' has no attribute 'frombyte' in python3 I'm trying to execute a simple snippet of code which is given below: import matplotlib.pyplot as plt image = caffe.io.load_image(root + 'images/cat.jpg') transformed_image = transformer.preprocess('data', image) plt.imshow(image) When the code reaches `plt.imshow`, I'm faced with the following error : AttributeError: module 'matplotlib._image' has no attribute 'frombyte' <matplotlib.figure.Figure at 0x1bd2ac8ac18> What is wrong here?
Upgraded to the latest version of matplotlib and the issue is solved.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python 3.x, matplotlib" }
How do I interpret 'detected downgrade...' NuGet error messages? I'm getting the followin error message i Visual Studio, from NuGet: ![enter image description here]( What I'm logically thinking is that first first package requires a version of Microsoft.AspNetCore.Hosting greater than or equal to 2.2.0, and the one below a version greater than or equal to 2.1.1. So I already have version 2.2.0, yet it wants me to downgrade to 2.1.1 eventhough it satisfies the requirements (from my understanding). Does the >= symbol mean something different?
You interpreted it correctly - you can only resolve one package version and it seems like `2.2.0` would be the sensible version to pick as it satisfies both projects. NuGet however uses a nearest wins resolution rule, so in your case picks `2.1.1`. As it goes further down the transitive dependency chain it finds the other project, which requires `>=2.2.0`, but it's already resolved version `2.1.1`. So if it continued, this project that requested `>=2.2.0` would be getting `2.1.1` instead, so would be getting 'downgraded'.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, visual studio, nuget" }
How can I define a global property in rhino? I'm embedding Rhino in Java and I want to create a global property with a getter and setter. This non-global property definition works: var testObj = {}; Object.defineProperty(testObj, 'testPropName', { set: function(value) { print('setter called w/' + value); } }); If I try it w/ the global "this" object it throws an error: Object.defineProperty(this, 'testPropName', { set: function(value) { print('setter called w/' + value); } }); Error: TypeError: Expected argument of type object, but instead had type object (#1) in at line number 1 Creating it from the Java-side would be fine too, but I've had no luck with that either.
A solution from the Java side... public class MyCustomBindings extends SimpleBindings { @Override public Object put(String name, Object value) { Object result = super.put(name, value); // "setter" logic return result; } @Override public Object get(Object key) { // "getter" logic return super.get(key); } and elsewhere... ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByName("JavaScript"); MyCustomBindings bindings = new MyCustomBindings(); engine.getContext().setBindings(bindings, ScriptContext.ENGINE_SCOPE);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "javascript, java, rhino" }
LINQ to SQL Table Names I want get my tables name with LINQ For Example I Have DB with 5 Table and i want show my tables name in a listBox Then whith a Query I Add a Table then try again, now we have ListBox With 6 Items.
Your Linq to SQL DataContext already has the table names: `context.Mapping.GetTables()`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql, linq" }
zsh: When running source I get zshrc:116: unmatched So today I wanted to add some extra alias to zsh. * I did the usual nano ~/.zshrc and added my alias ex: alias desktop="cd desktop" (I've doubled checked that all variables for typos) `Ctrl`+`O` to save and `Ctrl`+`X` to exit. * After getting out I run: source ~/.zshrc And get the following error: /Users/fridavbg/.zshrc:116: unmatched " * When running I get: echo $SHELL /bin/zsh Any kind soul out there that could help me out or give me some resource that might help me figure out how to fix this? It feels like this is something simple, but I'm a little scared to mess my path up completely.
Your error message is not `unmatched`, it is `unmatched "`, as in there is an unmatched quote character, `"`. The part `/Users/fridavbg/.zshrc:116` exlains that this error was detected in file `/Users/fridavbg/.zshrc` on line `116`. So you should look at that file around the indicated line for unmatched quotes. Note that sometimes the indicated line is not the line where there error is. If you don't find an error on the indicated line, it may be before that line, or sometimes after that line. Example: command1 "missing quote at the end command2 "" Here the quote started on the first line continues to the first quote character on the second line, and the quote starting with the second quote character is not terminated.
stackexchange-unix
{ "answer_score": 2, "question_score": 0, "tags": "zsh, alias, oh my zsh" }
Why is the scrollLeft function only working on the first click? I want the `scrollLeft` function to scroll a div each time when I click a forward button Code: $("#nextbutton").click( function() { $("#thumbholder").scrollLeft(300); }); Thumbholder holds the images and its `overflow:hidden`, I want to show the hidden items by scrolling to the left. #thumbholder { height:30%; width:90%; overflow: hidden; white-space:nowrap; margin:2% auto; } Can anyone tell me how to repeat the scrollLeft function for each click on "#nextbutton", instead of just the first time I click it?
The problem is that `scrollLeft` takes an absolute scrollbar position, not a relative one. See the docs for `scrollLeft`. Try using `.scrollLeft()` to get the existing position, subtract 300 from it, and apply it back using the `.scrollButton(value)` function you're already using: < $("#leftButton").click( function() { var thumbHolder = $("#thumbholder"); thumbHolder.scrollLeft(thumbHolder.scrollLeft() - 300); } );
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "jquery" }
The complexity of expansion ratio (Cheeger constant) of a graph Let $G=(V(G), E(G))$ be a graph on $n$ vertices and let $S$ be a subset of $V(G)$. The boundary of $S$, denoted by $\partial S$, is the set of edges $(i, j)$ such that $i \in S$ and $j \in V(G) \setminus S$. The expansion ratio of $G$, denoted by $h(G)$, is \begin{equation} h(G)= \min_{S\subset V, 0<|S|\leq \frac{n}{2}}\frac{|\partial S|}{|S|}. \end{equation} Is calculating $h(G)$ NP-hard?
This paper says it is NP-hard and gives three references.
stackexchange-mathoverflow_net_7z
{ "answer_score": 2, "question_score": 2, "tags": "graph theory, algorithms, computational complexity, spectral graph theory, random graphs" }
How to fill a flash drive with 1s instead of zeros I recently ran the F3Tools on a large USB thumb drive that I purchased. It has a 240 GB FAT32 filesystem (not exFAT or NTFS, actual FAT32) on it, and it's supposed to be 256 GB, so I got slightly suspicious. Turns out it's legit, but now I have a flash drive with random data written to all of its sectors, which is bad for write amplification and speed issues down the road. Since flash drives erase to 0xFF rather than 0x00, is there a way to overwrite a device or file with 1s rather than zeros? If I use zeros, there'll be the same write amplification issue. I am using Linux (Ubuntu 18.04), so system tools would be best, but I'll also accept anything that's in the apt-get package store.
Run this in a terminal: cat /dev/zero |tr '\0' '\377' |dd of=/dev/sdx Notes: * Replace `sdx` with your device name, **after being absolutely certain it's the right one**. (I like to use `gparted` to review at all my devices, sizes, etc.) * The `tr` command changes 0x00 (all zeros) to 0xFF (all ones). * When this finishes, it will give an error that the drive is full. This is expected. * You are probably aware - flash drives have a limited number of write cycles.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "linux, ubuntu, usb flash drive, flash, overwrite" }
php regex/preg_match for beginner I am not good at expressions I would like to match the string below of a string. * .js preg_match('( I know this code is not right. * Represents any file with .js extension. Could anyone guide me with the expression. Sorry if any duplication.
You have to use delimiters such as '#', '@' or '/' in the pattern : $url = ' $preg_match = preg_match('#( $url, $matches); if($preg_match === 1) { var_dump($matches); // displays : // array // 0 => string ' (length=38) // 1 => string ' (length=20) // 2 => string 'javascript/test' (length=15) // 3 => string '.js' (length=3) } else { // doesn't match }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, regex, preg match" }
laravel 500 internal server error I'm trying to deploy my Laravel 4 app on 1and1 shared hosting, but I keep getting a 500 internal server error. I have checked the following: * Using PHP 5.4 * Mcrypt PHP extension installed * chmod 777 /app/storage/ * Domain is pointing to /laravel/public/ I'm out of ideas now? One thing I've noticed is if I go to /index.php/, I get a "Fatal error: require(): Failed opening required" error. Could this mean some of my paths are wrong somewhere? I doubt it, because the app is working fine locally. Any help would be amazing. Thanks
Try running `composer install` after cloning the repo. The vendor directory is in the Laravel `.gitignore` file by default. Edit: just re-read your follow-up comment and realized I shouldn't attempt to answer questions after midnight.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "laravel, laravel 4" }
C# Concurrency and Agents Is there anything in C# similar to the new Microsoft C++11 Concurrency library that allows to build asynchronous agents (for example as it is done here) ?
You might be looking for the new (beta) `async` keyword. <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 9, "tags": "c#, parallel processing" }
How do I stop my cables from getting tangled inside my box? I've a box of different cables, but they're always get tangled. **Any ideas how to store bunch of cables without getting tangled?**
If you have some empty tubes, you can store each cable inside the tube by keeping them separated. In example you can use inner cardboard tube from kitchen roll, wrapping paper or toilet paper. !Sick of having a box full of tangled cords Image credits: instructables See more at: * TP Roll Organizer Box instructable at instructables
stackexchange-lifehacks
{ "answer_score": 8, "question_score": 9, "tags": "storage, cables" }
Uncaught syntax error unexpected token I can't figure out what I'm doing wrong here: (The error is on line 4, I'm sure there are plenty more): var RPSPlayer = { myHistory = new array(); rivalRock = 0; rivalScissors = 0; rivalPaper = 0; itemChosen; victorySum; this.choose=function(item) { myHistory.push(item); }; ... {more code here}
You're right, there are plenty more. A quick correction: var RPSPlayer = { myHistory: [], rivalRock: 0, rivalScissors: 0, rivalPaper: 0, choose: function(item) { this.myHistory.push(item); } };
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript" }
Trying to get JSON data from python application to google sheets I have a python program which outputs JSON files. I want to get the JSON files into google sheets. I looked for a way to upload JSON files directly to google sheets, and couldn't find a way. This prompted me to look for a way to store my JSON files online, so google sheets could use an API to call the JSON data. I have tried using Google Cloud Platform, but I could not find a way to call the JSON data from Google Cloud Platform to google sheets. I looked into a few other web based services that offer storage and api services at low-no cost, but I could not find any. I am fairly proficient Python, but that's the extent of my programming knowledge. At this point, I am at a loss as far as a method of getting my JSON data into a google spreadsheet. Any and all advice/suggestions are welcome and appreciated, and I am glad to answer any questions.
I would use this < to convert if from JSON to xls. Then you can open it up directly in google sheets.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, json, google sheets, google cloud platform, google sheets api" }
Pushing apks from compiled AOSP to device I synced code from AOSP onto my computer, modified the source for the `Phone.apk` file. I ran make (for Maguro), and got a Phone.apk file back in the /out folder. I'm using an AOSP rom on my phone (but not the one that I compiled myself), but when I move the created `Phone.apk` file into `/system/app` I lose signal, and when I launch `Settings > Mobile Networks` I get a FC. Logcat says I'm missing `MobileNetworkSettings.java` (which I know that I'm not). What do I need to do in order to use the apk files that I built from the source?
The problem, I guess, is the following. Phone application uses sharedUserId: `android:sharedUserId="android.uid.phone"`. So as the AOSP image and your Phone.apk are signed with different certificates your Phone application is not allowed to receive this shared UID (because applications can share the same UID if they are signed with the same certificate) and receives a new UID. Thus, Phone application cannot work with radio interface (loose signal) and cannot be configured. Try to create your AOSP image using your keys and flash it on the device. Then sign your Phone application with the same certificate. I guess this should help. Good luck!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, android source" }
Array search using arrayjobx I'm using the `arrayjobx` to store data in arrays, and I want to search through those arrays. For example, I might have a list of names and places and I want to search through those names to find the index of a given name in that array. \newarray\Names \newarray\Places \readarray{\Names}{Alice,Bob,Charles,Steve,George} \readarray{\Places}{Alberta,Bangkok,China,Saarland,Georgia} I want something like `\findindex` so that I can call the place associated to the person, e.g. \Places(\findindex{\Names}{Bob}) should output `Bangkok`. How might I do this?
You probably want a property list, rather than two independent arrays. \documentclass{article} \usepackage{xparse} \ExplSyntaxOn \NewDocumentCommand{\addperson}{mm} { \prop_gput:Nnn \g_luftbahn_person_place_plist { #1 } { #2 } } \DeclareExpandableDocumentCommand{\Place}{m} { \prop_item:Nn \g_luftbahn_person_place_plist { #1 } } \prop_new:N \g_luftbahn_person_place_plist \ExplSyntaxOff \addperson{Alice}{Alberta} \addperson{Bob}{Bangkok} \addperson{Charles}{China} \addperson{Steve}{Saarland} \addperson{George}{Georgia} \begin{document} Bob lives in \Place{Bob}. \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 3, "question_score": 1, "tags": "arrays" }
How do I detect the url of where the user is coming from in Javascript/Angularjs? I want to detect the origin url of an user entering my website (such to perform certain operations later). Can this be achieved using angular?
Are you looking for referrer? var x = document.referrer;
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "javascript, angularjs, url, location, browser detection" }
Existence of a quadratic form I'm trying to prove whether the below statement false: For a real $3 \times 4$ matrix $A$, the function $q(\vec{x}) = \lVert \vec{Ax}\rVert^2$ cannot define a positive semidefinite quadratic form on $\mathbb{R}^4$ because $A$ is not square and hence it is non-invertible. My approach would be to use the determinant test to show that there exists a matrix such that $A$ is positive semidefinite. Is this the correct approach?
Note that $A: \Bbb R^4 \to \Bbb R^3; \tag 1$ as such, $\ker(A) \ne \\{0\\}; \tag 2$ thus there exists a vector $\vec x \in \Bbb R^4$ with $A \vec x = 0; \tag 3$ then $q(\vec x) = \Vert A \vec x \Vert^2 = \Vert 0 \Vert^2 = 0, \tag 4$ so $q(\vec x)$ cannot be positive definite; however, if $A \ne 0$ there is some $\vec y \in \Bbb R^n$ with $A\vec y \ne 0, \tag 4$ and for any such $\vec y$, $q(\vec y) = \Vert A \vec y \Vert^2 > 0\. \tag 5$ We see that $q(\vec x) \ge 0$ for all $\vec x \in \Bbb R^4$; thus $q(\vec x)$ is positive semidefinite. The above argument does not invoke determinants.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "linear algebra, quadratic forms" }
How to add background image to a Windows form gridview? I wonder if there is any way to put an background image to the gridview in windows form ... I am using c#
using the OnPaint event you could do something like this private void dataGridView1_Paint(object sender, PaintEventArgs e) { DataGridView dgv = (DataGridView) sender; int i = dgv.Rows.GetRowsHeight(DataGridViewElementStates.Visible); e.Graphics.DrawImage(Properties.Resources.BackGround, new Rectangle(0, i, dgv.Width, (dgv.Height - i))); } **EDIT** This works to detect the Rows, but it doesn't seem to detect the UserAddRow option on the bottom, if that is a need. I am at a loss.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, winforms, gridview" }
FindRoot with lists as input I have to calculate different Internal Rates of Returns by using the `FindRoot` function. cashflowlist={-10,3,12} FindRoot[TimeValue[Cashflow@cashflowlist, r, 0] == 0, {r, .05}] However, this needs to work for many more potential cashflows. E.g. cashflowlistlong={{-10,3,12},{-9,4,12},{-8,2,11}} When inserting the `cashflowlistong` in the function defined above, it does not work at all. FindRoot[TimeValue[Cashflow/@cashflowlistlong, r, 0] == 0, {r, .05}] My goal is to get a list which contains only the three return rates.
Make the whole solving step a function and map it over `cashflowlistlong`: sol = FindRoot[TimeValue[Cashflow[#], r, 0] == 0, {r, .05}] & /@ cashflowlistlong > {{r -> 0.255667}, {r -> 0.398112}, {r -> 0.304248}} You obtain the list of numerical solutions simply by `ReplaceAll`: r /. sol > {0.255667, 0.398112, 0.304248} **Edit** Actually, for list with three elements, your equations boil down to quadratic equations in one variable, so also `Solve` can compute the solutions symbolically: Solve[TimeValue[Cashflow@Array[a, 3], r, 0] == 0, r] > { > > {r -> (-2*a[1] - a[2] - Sqrt[a[2]^2 - 4*a[1]*a[3]])/(2*a[1])}, > > {r -> (-2*a[1] - a[2] + Sqrt[a[2]^2 - 4*a[1]*a[3]])/(2*a[1])} > > }
stackexchange-mathematica
{ "answer_score": 2, "question_score": 3, "tags": "list manipulation, equation solving, finance" }
Local Notifications received, even after app is uninstalled? Has anybody had the experience of Local Notifications being delivered from an app that has been uninstalled? I hesitate to ask since I can't reliably reproduce the issue, but we're receiving multiple reports of that occurring. We're having an emergency debug session here, and since we barely know where to start looking for answers on this, wanted to see if anybody else has had this happen to them, as either a developer or as a consumer. Could this potentially be an iOS 4.0 bug?
Looks like there's a thread on it here: < Likely an iOS bug.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, ios4" }
How to check if text editor view in Visual Studio is modified (unsaved)? In order to trigger autocompletion I need to know which text view among opened ones does contain modified text (i.e. not yet saved to disk). How can I check that having IVsTextView and ITextView instances?
I've found the following solution: IVsTextLines buffer; if (vsTextView.GetBuffer(out buffer) != VSConstants.S_OK) { return false; } uint flags; buffer.GetStateFlags(out flags); bool isDirty = (flags & (uint)BUFFERSTATEFLAGS.BSF_MODIFIED) != 0;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, visual studio, mef" }
Trigger insert deleted row Hello I have some difficulties with simple trigger in MSSQL 2008. I want to insert deleted row to another table. Here is my trigger code: use databasex; GO CREATE TRIGGER DeleteEmployee ON Employees FOR DELETE AS BEGIN INSERT INTO DeletedEmployees (Name, Surname, Function) VALUES (deleted.Name, deleted.Surname, deleted.Function) END Employees table: Name Surname Function ... DeletedEmployees table: Name Surname Function ... I need somehow to specify that deleted columns are from deleted table, but how ? I dont want to write subquery for every column. How it being done ? ps: is there any good tutorial on using triggers ? i believe i will need write more triggers in the future.
`DELETED` is a virtual table you select from (you may have deleted more than one row, so a single value is not enough) Also, `FUNCTION` is a reserved word and needs to be escaped CREATE TRIGGER DeleteEmployee ON Employees FOR DELETE AS BEGIN INSERT INTO DeletedEmployees (Name, Surname, [Function]) SELECT Name, Surname, [Function] FROM deleted END An SQLfiddle to test with.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql server 2008" }
Targets for conditional comments in html? I know you can target browsers with conditional comments, as explained here in MSDN. But I just saw one that looked like this `<!--[if gte mso 9]>` What does this check for and what (other than browsers) can you check for with conditional comments? **EDIT** Is there any documentation on the conditional comments. What options and what version numbers you can use? mso = Microsoft Outlook 9 = 2007
This German version of Wikipedia lists the various targets (IE, Microsoft Office, and VML). < (You will need to Google translate) Also, this post suggests that MS Publisher can also be targeted <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "html, conditional comments" }
Is there a standard GUI toggle switch in Java? Is there a standard implementation or library that provides a GUI toggle switch in Swing? I know Swing provides a toggle _button_ , but the UX leaves a bit to be desired. I'm looking for this: !enter image description here Also, is there a canonical term for this type of control? The Apple HIG refer to it as a UISwitch. I also tried searching for "toggle switch", but I didn't have much luck. (Plenty of JavaScript results, but nothing native.)
You might mimic it by using two icons to represent on & off, then set those to a `JToggleButton`. As an aside, users want to see logical and consistent GUIs that represent the 'path of least surprise', it's developers that think users want a 'beautiful, clever' GUI (and that they can design one). Why on earth would they want such a control over a standard toggle-button?
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 13, "tags": "java, swing, icons, uiswitch, jtogglebutton" }
Does Three.js sphere geometry have a size limit? I am making a Three.js sphere geometry with a radius of 4000, put a JPEG image on it and position the camera within its center and it works fine. When I made the sphere with a radius of 9000 so the texture should look further away, it appeared as if there was a black "hole" in the sphere in the very direction the camera was looking. Also the texture on the sphere looks nearer and not further away. When I move the camera towards this "hole" it becomes smaller. new THREE.SphereGeometry(9000, 32, 32);
The camera has a .near and .far setting. If .far is lower than your sphere radius, it will clip like you are describing. Try setting camera.far = 20000
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "three.js" }
php simple rand() look up taking long / crashing browser? I'm running this code: $n1 = rand(1,20); $n2 = rand(1,20); echo '<p>Looking for ' . $z1; echo '<p>looking....<br><br>'; for ($i = 1; $n1 != $n2; $i ++) { $n2 = rand(1,10); } echo '<p>I tried ' . $i . ' times.</p>'; First loads of the page are usually super fast. Then suddenly: Fatal error: Maximum execution time of 120 seconds exceeded It's either working super fast or crashing. Can someone help me understand why this is? Thank You
You have committed a "logic" mistake. If `$n1 = rand(1,20);` sets `$n1` to any number from `11` to `20`, then the condition in your loop will never be satisfied and result in an "infinite loop". In other words, roughly half of your code executions will result in infinite loops and half will not. `$n2 = rand(1,10);` needs to be `$n2 = rand(1,20);` so that all possible `$n1` values can be matched. Might I recommend: $n = rand(1, 20); echo "<p>Looking for $n</p>"; $i = 0; do { ++$i; } while($n != rand(1, 20)); echo "<p>Tries: $i </p>"; Ultimately, whenever a random generator is used to determine a loop's break condition, it can be sensible to set an arbitrary "maximum iterations" value. Once that is reached, let your script exit the loop.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "php, random, browser, fatal error" }
Custom WordPress Theme isn't picking up the style.css file I have just followed a tutorial about creating custom WordPress theme, each and everything went just fine from static to dynamic conversion but when I activate that theme and I come up with a plain HTML document with blue hyperlinks which mean the site is not picking up the css file of style.css Am I doing something wrong? Please help me.
Check your source HTML and see that the path to your CSS is correct. You can use bloginfo() to find the correct path by using: <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/style.css"> If your style.css resides in the root folder of your template.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "wordpress" }
Python3: Separating a text output into separate variables I am working on a little project that requires detecting the properties of the computer it is running on. I am using the `os` module and the commmand `plat = os.uname` which gives me something like this: `posix.uname_result(sysname='Linux', nodename='abh57fbg', release='5.4.0-1009-gcp', version='#9-Ubuntu SMP Fri Apr 10 19:12:03 UTC 2020', machine="x86_64")` What I am looking to do is parse this out and establish each of these results as their own variable that the rest of my code can act on. I did look through the official docs and do some searching, but I couldn't seem to find what I was looking for.
Once you have your `posix.uname_result` object you can access each value by it's property name. For example: `print(plat.sysname)` Should output: `Linux`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "python, python 3.x, parsing" }
Show on hover using CSS and HTML only How to show a child `div` when hovering anchor tag? I want to show a `div` with class `botm` when cursor hovers anchor tag. This is the exact scheme I am using so kindly keep tags in the same order: HTML: <a> Hover me!</a> <div class="faraz"> sdjfg <div class="dikha">Stuff shown on hover</div> <div class="botm"></div> </div> CSS: div { display: none; } a:hover ~ .faraz > .botm { display: block; background-color: RED; height: 250px; width: 960px; } .botm { background-color: #0CC; height: 50px; width: 100%; position: fixed; top: 90px; }
The parent of your targeted div is hidden therefore it cannot be shown. Show the parent as well and every thing will work. a:hover ~ .faraz{ display:block; } <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "html, css" }
SQL Server Management Studio replacing single quotes with double quotes when modifying stored procedure Whenever I attempt to "modify" or use the "script to" function with a stored procedure within SQL Server Management Studio, every single quote in the SP is replaced with a double quote. Whenever any of my colleagues uses modify or script to, they receive the output in single quotes. The double quotes break the query. It appears to be a setting within SSMS, but I cannot find any such setting. Any advice would be appreciated.
I believe you are getting dynamic SQL from the scripting options because you have this option selected: > Tools > Options > SQL Server Object Explorer > Scripting > Check for object existence When this setting is enabled, the script is generated like this: IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = ...) BEGIN EXEC dbo.sp_executesql @statement = N'ALTER PROCEDURE...' END Disable this option, and it should be correct when you use `right-click > Modify` or `right-click > Script stored procedure as > ALTER to >`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sql server, ssms" }
How can round to 2 decimals in laravel? I have this. Its made in laravel public function render() { $percentageNotAnswered = ($noanswer * 100) / $mytickets; And also this: <span class="text-2xl font-semibold text-gray-700"> {{ $noanswer ?? "" }} </span> <span class="text-sm text-gray-500"> {{ $percentageNotAnswered ?? '' }}% </span> <div class="text-gray-500">Tickets with no Answer</div> </div> And it show the result like 33.333333333333% How can I round to just 2 decimals? Thanks
Simple php function: round(($noanswer * 100) / $mytickets, 2); <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "laravel, rounding" }
Will functions I return from closures be available in the outer scope? I'm building a small library after a while away from javascript, and am probably over-thinking this. I have my library wrapped in a closure, and while I know I can return what I want with something like `window.namespace.function`, I'm wondering if I can more elegantly do something like this: (function($){ var config = {...} var namespace = { doStuff: function() { // . . . }, } return namespace })(jQuery) After this script has loaded, will a user be able to call my library with something like `namespace.doStuff()`? Also, if a user simply copied and pasted my library within a closure of their own, would my namespace then be available within their closure, but not as a global?
It would only be available in the outer scope if you assign it to something. As it is you are returning it, but not assigning it to anything so it is then not available. You could assign it like this: var ns = (function($){ var config = {...} var namespace = { doStuff: function() { // . . . }, } return namespace; })(jQuery); Then, you could call the `doStuff()` function from the outer scope like this: ns.doStuff();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, closures" }
Improving the readability of PL/SQL for identifying the LOOPs and Individual blocks I am relatively new to PL/SQL (Oracle). I am able to complete my assignment successfully. Having followed Modular programming, I divided my program into small PL/SQL blocks. Also I have nested `BEGIN-END` in my code. (To handle exceptions) When my code base started to grow, I could see many nested blocks inside, and I am unable to identify the corresponding `END` for every `BEGIN` block .(When the blocks are bigger). The same case with the nested `FOR LOOP`s too. I agree there's no curly brackets in PL/SQL. I improved the indentation of my code to the best of my ability, and to some extent the code is readable now. But still, if anyone else wanted to read my code, I have a feeling that my code may not be easy to traverse. Do you guys provide some suggestions to solve my issue?
<<outer_loop>> LOOP <<<block1>> BEGIN i := i + 1; j := 0; <<inner_loop>> LOOP -- Your Statements EXIT inner_loop WHEN (j > 5); EXIT outer_loop WHEN ((i * j) > 15); END LOOP inner_loop; END block1; END LOOP outer_loop; Try using `LABELS` (embedded between angled brackets). This should help you! Your can look for the label names, for where the block/loop starts or ends! Actually, this kind of Label can be used for `GOTO` too But dont over use it, as it also confuses you :) Good Luck!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "oracle, plsql" }
Two cards are drawn from 52−card deck (the first is not replaced) Two cards are drawn from 52−card deck (the first is not replaced) (a) given the first card a queen, what is the probability that the second is also a queen? (b) Repeat part (a) for the first card a queen and the second card is 7 (c) What is the probability that both cards will be a queen?
a) So after we choose the first queen, we are left with $51$ cards with three queens in them, So then the probability that we get a queen should be:$\frac{3}{51}$ b)Here after we choose the first queen, we are left with $51$ cards with four $7$ in them, hence the probability that we get a $7$ is :$\frac{4}{51} $ c)Here we are picking 2 cards from a deck of $52$ cards, so there are $52*51$ possible outcomes. There are $\binom{4}{2}=\frac{4*3}{2}$ ways to get choose $2$ queens from $4$ queens and the order of choice matters, so we should get $4*3$ ways to choose ordered pair of queens, hence the probability that we get two queens is: $\frac{4}{52}\frac{3}{51}$
stackexchange-math
{ "answer_score": 1, "question_score": -2, "tags": "probability" }
Retrieve Website Fully Qualified URL Securely in PHP? Have seen lots of individual threads on how to generate a fully qualified website URL, e.g. The majority of the threads are a few years old and have mentions of security risks with using the code. Is there a more up to date and secure way of retrieving the qualified URL in PHP? UPDATE: I wish to keep a global string, auto-generated, of the top level website address to use in the pages on the website.
$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; refer : Get the full URL in PHP
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "php, security, url" }
Retrieve innerHTML of a diffrent page using $.get So I tried getting the innerHtml of an Element of a diffrent page (SOP friendly). For example: $.get("/archiveIDs.htm", function(data){ alert($(data).find('a#1163').html()); }); I tried getting the innerHtml of an `<a>`-Tag with ID 1163. Thats doenst work... I dont know what to do now. If u have any ideas please reply to this post. Thanks in advance, Freddy!
Please try this. $.get("/archiveIDs.htm", function(data){ var html=$('<div />').html(data).find('a#1163').html(); alert(html); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html, cross domain" }
Checking for internet in the background I would like to be able to run a background process that is always open to check for when the user gets internet. This is so that when the user comes back online, data I have saved to their phone locally will then automatically push its self to my online database. I don't know if this is possible without having the app open. Realm isn't an option due to GDPR Thank you.
Use this `BroadcastReceiver` structure: public class InternetReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { //Do Something } } In the `<application>` tag, add: <receiver android:name=".InternetReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "java, android, database" }
UIImage to CCSprite cocos2d v 2.0 Moved to version 2.0 of `Cocos2D` but I'm trying to find a workaround solution to convert `UIImage` to `CCSprite`, previous one like: CCTexture2D *texture = [[[CCTexture2D alloc] initWithImage:tempImage] autorelease]; self.spriteImage = [CCSprite spriteWithTexture:texture]; Note: **tempImage is a`UIImage` object**
Try this: self.spriteImage = [[CCSprite alloc] initWithCGImage:tempImage.CGImage key:@"unique image name"]; Alternatively there's also a `initWithCGImage` method in CCTexture2D if you prefer to use that.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "objective c, cocos2d iphone, uiimage, cctexturecache" }
detect attribute of variable - jquery I am working on a script and not sure why this isn't working function moveIn($selector) { if( $( $selector[left] ) != null ){ $direction = 'left'; }else{ $direction = 'right'; } This is does work: if( $( '#hello[left]' ) != null ){ This is essentially what I am trying to get spit out. It seems the brackets are causing the problem. How else would this be written? Tips for future coding? Thanks Entire function: function moveIn($selector) { if( $( $selector + '[left]' ) != null ){ $direction = 'left'; }else{ $direction = 'right'; } var animation = {}; animation[$direction] = 0; $($selector).animate(animation, 1500); }
Assuming you're passing `"#hello"` as the selector, you are then trying to get the `left` property of a string, which doesn't exist. `"#hello[left]"`, on the other hand, searches for an element with the ID `hello` and a `left` _attribute_. They are not the same. Try `$selector+"[left]"`
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "jquery" }
Django 'next' not working? Not sure what's wrong here. I'm using the built-in comment form. The form tag is like this: <form action="{% comment_form_target %}?next={% url post post.id %}" method="post"> The resulting HTML looks like this: <form action="/comments/post/?next=/6/" method="post"> Where `/6/` is my Post's post_detail address. However I still end up at this URL: with a > Thank you for your comment. message What is going on here? Thanks!
`next` should be a POST param , not a GET param . try add following line into your form <input type="hidden" name="next" value="{% url post post.id %}" /> and leave the action of the form as `"{% comment_form_target %}"`
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "django, next, django comments" }
PHP CLI does not allow run two script at same time PHP (5.6.11-1 on Debian Strech/sid) does not allows me to run two instaces of cli. I've tried to execute following script two times. First script runs normally. Second one is locked until first one is killed. #!/usr/bin/env php <?php $i = 0; while (++$i) { var_dump($i); sleep(1); } Do you know what may be reason of that strange behaviour? Edit: Issue does not occur on other machines. (?) Edit: Is there something in configuration files of php, that could do that?
Issue was caused by something wrong in configuration (still does not know what was it be). aptitude purge php5 php5-cli aptitude install php5 php5-cli Configuration purging helped.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
unix: how to cat from 2 inputs? in UNIX scripting programming, cat is a command that could combine 2 files together: cat file1 file2 > file3 this generate the 3rd by combining the first two. also, cat could be used with pipe: cat file1 | tail -4 this will list the last 4 lines of file 1. question: how could I combine the last 4 lines of file 1 and 2, to generate file 3? i'm a bit lost here: how to give 2 streams inputs to cat?
Bash has a process substitution feature: cat <(tail -4 file1) <(tail -4 file2) I often use this feature to diff slightly altered versions of two files.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 6, "tags": "unix, cat" }
How to recreate previous activity? I have a main activity (let's call it A) and a second activity (let's call it B) which's used to change the language of the app. The point is, when I click the button to change the language I also call `recreate();` and B changes it language. Until here it's ok. The problem comes when I go back to the main activity (A) and it hasn't updated the language because it hasn't been recreated, so, is there any way to recreate A from B in order to update A? I use this code to translate the app (eng version example): public void btnIngles_onClick(View v) { Locale locale = new Locale("en"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; this.getApplicationContext().getResources().updateConfiguration(config, null); recreate(); }
1) `Activity B` changes some global settings, accessible via `SharedPreferences` for example 2) In `Activity A` do: @Override protected void onResume() { super.onResume(); if(didLanguageChange) recreate(); } Problem solved. `Activity A` _will_ call `onResume()` since it has switched into a paused state when `Activity B` came into the foreground.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 7, "tags": "android, recreate" }
Outputting a 1/4 inch TRS male plug from a PCB I am designing a small PCB that I need to plug into a 1/4" TRS receptacle. The overall setup can either be something like a small dongle (i.e. attaching a male TRS directly to the PCB somehow,) or I can use an approximately 1-2 foot long cable. I don’t want a cable much longer than that because the low-power electronics on my PCB will need to drive it. My main challenge is finding a TRS cable where the termination on the end that I would connect to my PCB is something convenient. I have seen 1/4" male TRS to mini USB male. That's a possibility, but I'm wondering if there is a more elegant or more standard approach. The signal is just a digital HI/LOW, so no analog to worry about.
Just get a plug (without cable) and wire it up to whatever connector you want for your PCB, or just directly solder wires to the PCB if you don't need the plug to be detachable. Distributors like Mouser have lots of options (click for relevant results).
stackexchange-electronics
{ "answer_score": 2, "question_score": 1, "tags": "pcb design, trs" }
Store PHP errors in a log file I would like to store any errors and warings generated by php in a log file but **still** display them in the normal way (echo) as well. Thanks
You can define your own function and describe what to do with errors. < < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php" }
extracting some features from a dataframe column for KNN algorithm My question is about selecting and extracting some features from a dataframe column. Does that effect in the effectiveness of ML algorithms. For example i'm doing analysis on "Chicago crime Dataset". It has a "Date Of Occurrence" column and it has data in this form: "2018-11-23 05:10:00". What i want to do is, i want to add some extra columns out of this for "year", "month", "weekday", "hour". **Will that effect in efficiency of KNN Classifier algorithm.** This is the link to dataset if you want to check which dataset I'm Talking about. "<
Adding new features always benefits the model learning. It is always recommended to add individual new date features for date columns. `day` `month` `day_of_week` `year` `is_it_weekend` `hour` `minute` `AM_PM` `season`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, machine learning, deep learning, knn" }
Limit characters or letters in category product name on opencart 2.0 In opencart 2.0 how to set the limit characters or letters on product name on category page ? Any one please answer this Thanks
If, You want to restrict Product name in one line instead or two or more line. So, You can use below css & easily product name convert in one line (exp.- my product name....) .product-thumb h4{ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "css, opencart2.x" }
Is it ok to use npm 3.x with nodejs 4.x? See title. I searched all across the internets and could not find a firm answer. The reason I want to use npm3 is because I am working in a Windows environment and I am hitting the dreaded too long path name. Migrating off Windows is not a viable option at this time. Also, I can not upgrade to node 5.x because I use the karma test runner, which is not yet supported on node 5.x So, I want to use node 4.x with npm 3.x. I have successfully updated my machine, using the slick npm-windows-upgrade package, to use npm 3 with node 4. After the upgrade, I did see a couple issues with karma not realizing jasmine/phantomjs was available. The workaround was simply to install both those packages locally.
Yes. The npm 3.x is compatible with node 4.x. In fact, any node >= 0.8 is okay. This has been documented in < **You need node v0.8 or higher to run this program.** And more, I suggest you to use the nvm < It very easy to switch in various node environments with nvm. Your jasmine/phantomjs is references by peerDependencies, npm 2.x will install it if missing, and an error will be reported if found version conflict by multiple package. As you known ,the npm 3.x flatten the package dependencies, peerDependencies will print a line of warn message only(will not be instal), you should manually include peerDependencies in your package.json file, this means it is you that decide which version should be installed.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 8, "tags": "node.js, windows, npm, karma runner" }
What is the Backwards Compatibility of SNMP? I am working on a network monitoring application and need to know what versions of SNMP are backwards compatible with the other versions. I am writing the program in Java and using SNMP4J to query OIDs on particular devices. Within SNMP4J, you must specify the version of the SNMP device when setting up the target. Currently, there is SNMP versions 1, 2c, and 3. If I have a device that is SNMP version 1, will SNMP version 2c or 3 be backwards compatible with that version? If device is version 2, will 1 or 3 be backwards compatible? ... and so on Anyway, all the help is greatly appreciated, Steve
SNMPv1 uses community strings, which became context-IDs in SNMPv2c. Essentially it's the same thing but a slightly different way of looking at things. SNMPv3 has security and all kinds of additions that make the protocol anything but simple. If you try and make SNMPv2c requests on a SNMPv1 device you will run into problems if the SNMPv2c manager is using get-bulk requests (where it requests more than 1 subsequent object at a time, useful for pulling in columnar objects quickly). SNMPv1 has no support for bulk operations. So, a SNMPv1 manager may be able to retrieve objects from SNMPv2c agents. But a SNMPv2c manager may have trouble getting objects from a SNMPv1 device. Mixing SNMPv3 with anything else is asking for trouble.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, networking, monitoring, snmp, backwards compatibility" }
Change the separator in Zsh %_ When setting PROMPT2, I can add %_ to show `for if` or `for then` when I'm in these constructs. Is there any way to change the space to be something else, e.g. show `for/if` or `for:if` or even `for -> if` instead of the default?
With the `promptsubst` option enabled, you could do: $ PS2='${${(%):-%_}// / -> }> ' $ for i for> if for -> if> `${(%)...}` enables prompt expansion on the expansion of `...`. `${:-text}` allows to have a `${...}` expand arbitrary text. And we apply the `${x//pat/reply}` substitution on it. That assumes the expansion of `%_` doesn't itself include `%` characters.
stackexchange-unix
{ "answer_score": 4, "question_score": 3, "tags": "zsh, prompt" }
Postgresql: select distinct - combinations of columns I have this query in PostgreSQL: select p1.id, p2.id, p1.title, p2.title from publication "p1", publication "p2" where p1.title = p2.title and p1.id <> p2.id The problem is that it returns more data than I need: id id title title 3456 5678 Ulysses Ulysses 5678 3456 Ulysses Ulysses 234, 345 Das Kapital Das Kapital 345 234 Das Kapital Das Kapital I only need rows 1 and 3, or rows 2 and 4.
select p1.id, p2.id , p1.title, p2.title from publication p1 , publication p2 where p1.title = p2.title and p1.id < p2.id -- tie breaker ; Or with the much hipper JOIN-syntax: SELECT p1.id, p2.id , p1.title, p2.title FROM publication p1 JOIN publication p2 ON p1.title = p2.title AND p1.id < p2.id -- tie breaker ;
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "postgresql, select, distinct values" }
Finding out the type of value passed is select statement or csv without using SQL predefined keyword Please provide help in this created procedure which when executes returns result as the value passed to parameter it is csv or it is `select`. Here I used `select` in `like` statement to find out what value is passed. there is any way in which without using any sql keyword I can identified whether passed parameter value is csv or it is `select` Create procedure TypeOfvalue (@abc varchar(max)) as begin IF (@abc like '%select%') begin Print 'It is select' End Else Begin Print 'It is CSV' End First: Declare @abc varchar(max) set @abc='1' execute TypeOfvalue @abc Output: "It is CSV" Second: Declare @abc varchar(max) set @abc='select * from tbl1' execute TypeOfvalue @abc Output: "It is a Select"
You can use the `PARSEONLY` in combination with `NOEXEC` options for this. See this code example: CREATE PROCEDURE #TypeOfvalue (@code nvarchar(max)) AS BEGIN DECLARE @result int BEGIN TRY EXEC(N'SET PARSEONLY ON;SET NOEXEC ON;'+@code+N';SET NOEXEC OFF;SET PARSEONLY OFF;') PRINT(N'Statement') SET @result = 1 END TRY BEGIN CATCH PRINT(N'CSV') SET @result = 2 END CATCH RETURN @result END GO DECLARE @returnCode int EXECUTE @returnCode = #TypeOfvalue @code = N'abc;' SELECT @returnCode as returned -- 2 (CSV) EXECUTE @returnCode = #TypeOfvalue @code = N'SELECT * FROM sys.all_objects' SELECT @returnCode as returned DROP PROCEDURE #TypeOfvalue -- 1 (SELECT)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "sql, sql server, select, stored procedures" }
Using ant build for my web project I have my personal website and it is almost static with only a few instances of dynamic server-side code. Is it a good idea to build my project using Ant script? If yes, how to do it on an windows environment? While reading Html5BolilerPlate related build script,I thought to migrate on H5BP and use their script. Is that advisable?
Any kind of automated way helps you to increase productivity. Ant is one tool that could and you should try. I suspect what you need is some project automation / continuous integration. Tools like Jenkins/Judson can help there.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ant, web, html5boilerplate" }
print redirected to file SOMETIMES results in incomplete printout in python I want to save list to a file so I cycle through it and write it to file. Everything's fine. But SOMETIMES(!?!?) the list is not written entirely, it stops rendering in the middle of the item. No error is raised, it silently continues executing rest of the code. I've tried several ways to write it out, several versions of python (2.4, 2.5, 2.7) and it's all the same. It sometimes work, sometimes not. When it's printed out to the terminal window, not to the file, it's working properly without glitches. Am I missing something? this is it ... from bpnn import * ... # save input weights for later use: writewtsi = open("c:/files/wtsi.txt", "w") for i in range(net.ni): print>>writewtsi, net.wi[i] bpnn is neural network module from here: <
Close the file when done with all the writes to ensure any write-caching is flushed to the drive with: writewtsi.close()
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, file" }
Skinning Halo scroll bar in Flex I have the Spark scroll bar in my application skinned the way I want where I use `s|VScrollBar` and then set `skinClass: ClassReference(my skin class)` in my CSS file. For my Halo scroll bar I have the skins set for each element of the scroll bar (arrows, thumb, track, etc.) but I want to have one central class like with the Spark scroll bar. Is there any way to do this?
Yes, but not in the same way as you can in Spark. Spark was made for easy skinning which is the great thing about Flex 4, but Flex 3 did things very differently. What you can do is extend the Flex 3 scrollbar into a custom class that sets all those elements in it. Then within that project, just reference that custom class. Sadly, that's all that can be done.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "css, apache flex, scrollbar, flex spark, halo" }
Local-only message queue? I'm using Celery with RabbitMQ. For my use case, I'll definitely have instances where I'll have messages which should be executed on any given node, but for one specific queue, I'll need things _only_ executed on the originating server. This is because it works with a local-only file: @celery.task def calculate_hash(filename): target = Models.objects.get(filename=filename) hasher = hashlib.md5() with open(filename, "rb") as f: chunk = f.read(64 * 1024) while len(chunk) > 0: hasher.update(chunk) chunk = f.read(64 * 1024) target.hash = hasher.hexdigest() target.save() Obviously, the above task is only relevant where `filename` actually exists, and it's not likely that it'll exist on multiple nodes at the same time. Is there a way to specify that the given tasks only be executed locally?
Basically, if I'm correctly understanding your question, you should have one specific worker reading from one specific queue. First of all, you can configure queues to work with on a `celeryd` level, e.g. by starting it with `--queues` option: celeryd --queues=celery,queue1.mydomain.com Then, to send a task to a specific queue, you can use apply_async by setting `queue` argument. Also see: How to make celery retry using the same worker? Hope that helps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "rabbitmq, celery" }
Are static classes supported by Swift? I would like to know if you can create static classes in swift similar to those in C# i.e. a class that cannot be instantiated which can only have static functions and static properties. Are these types of classes possible in swift? If not, what is the most efficient way to recreate such a design pattern given the tools available within Swift?
No, Swift has no concept of a static class. But if you have no assignable property anyway, what difference will initialization make? I can think of 2 options: * Mark the class as `final` so it cannot be inherited: `final class MyClass { .... }` * Use a `struct`, which has no inheritance: `struct MyUtilities { ... }`
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "swift, static classes" }
Why meteor database(mongo db) contents is not uploaded in the github repo? I uploaded a meteor project on github repository. Once I finished uploading, I downloaded the zip file to check if it is functioning properly. The project runs, however, there is not even a single collection in mongodb. (Note my meteor version is 1.8) Can someone please help me get why the database collections are not stored/uploaded in the github repo and how can they be stored on github repo?
That is the designed behaviour of classic 3 tier web apps architecture. Your app code is separated from your app data. Technically, the MongoDB data of your Meteor project in dev mode (i.e. when you start it with `meteor run`) is in your Meteor project `.meteor/local` folder, which is correctly excluded from version control by `.gitignore`. Note that in production (i.e. when you use your app after doing `meteor build`) you will have to provide a `MONGO_URL` environment variable to specify where your MongoDB can be reached, since your local dev data will not be shipped with the built app. Now you can backup your data (e.g. mongodump) and use the dump to fill up your new MongoDB. You can also do it automatically, typically in your Meteor server startup, if you find empty collections.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mongodb, git, github, meteor" }
Get all milliseconds from LocalTime Java I need to know how to get LocalTime to milliseconds LocalTime lunchTime = LocalTime.parse("01:00:00", DateTimeFormatter.ISO_TIME); If i am going to execute `lunchTime.getMinute()` i only get 0 and `lunchTime.getHour()` i only get 1 as an hour. How to get value in milliseconds?
You can use `System.currentTimeMillis()`, refer < Also, please refer < to followup on **parsing date** in your choice of format. Also, if you trying to get local time in your timezone from an application running in different timezone please follow comment <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, milliseconds, localtime" }
RegEx: Replace lines that start with "msgctxt" with content that is in between quotation marks of those strings I have several big files with several entries like these: msgctxt "#. client error message" msgctxt "#. 0 = ID" #: Some more text msgid "" "Could not activate\n" "Connection lost?" msgstr "" "Some other text" "Even more other text" Now, ideally, I would like all of the lines that start with "msgctxt" to be replaced with the content that is in between the quotation marks of those strings: #. client error message #. 0 = ID #: Some more text msgid "" "Could not activate\n" "Connection lost?" msgstr "" "Some other text" "Even more other text" Some entries don't have any "msgctxt", others have only one or several. Is there a way to do this with Regular Expressions in Notepad++?
My guess is that a simple expression such as, msgctxt\s+"(.+)" being replaced by $1 would simply suffice. ### Demo
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "regex, notepad++, po" }
How do I build a react-native app using Xcode build I created a completely new react-native project using: react-native init demo After the successful creating I can run it using the react-native cli. cd demo && react-native run-ios When I try to open the ios library in Xcode and click on the build button I get the following error: > Library not found for -lDoubleConversion Is there a way to build the project using XCode? What could be the reason for my error? All my packages are updated to the latest versions. (Xcode, react-native, node).
If the **React native** version is `0.59` or later, there may be some problems. just open the `MyAppName.xcworkspace` instead of `MyAppName.xcodeproj`, and then, building.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "xcode, react native, react native ios" }
Alternative definition of sigma algebra generated by random variable Let $(\Omega, \mathcal F)$ be a measurable space (especially a probability space), and let $Y : \Omega \to \mathbb R$ be measurable. Then we define the sigma algebra generated by $Y$ to be $$ \sigma(Y) = \\{Y^{-1}(B) \mid B \in \mathcal B(\mathbb R)\\}, $$ where $\mathcal B(\mathbb R)$ are the borel sets of $\mathbb R$. Intuitively it seems to me that the goal of the definition of $\sigma(Y)$ is that it "collapses the level sets" -- that is, an alternative definition might be $$ \sigma'(Y) = \\{A \in \mathcal F \mid Y^{-1}(Y(A)) = A\\}. $$ Are these definitions equivalent? I can easily prove that $\sigma(Y) \subseteq \sigma'(Y)$, but not the other way around -- nor can I easily think of a counterexample.
They are not equivalent. Is is not true that $\sigma'(Y)\subset \sigma (Y)$. Given that $Y^{-1}(Y(A))=A$ how do you find the Borel set $B$?. The reverse inclusion is always true. Use a simple set theoretic argument for this. For an explicit counterexample consider $\mathbb R$ with the sigma algebra of all subsets and let $Y$ be the identity map on $\mathbb R$. Then $\sigma'(Y)$ contains all subsets of $\mathbb R$ whereas $\sigma(Y)$ is the Borel sigma algebra of $\mathbb R$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "measure theory, elementary set theory" }
Symfony 4: Add Twig_Extension_StringLoader In my Symfony 4 project, I have a variable containing HTML that I try to display with Twig. I want to use the `template_from_string()` function but I have to add **Twig_Extension_StringLoader** to the Twig environment. I didn't find any information to do this simple manipulation in Symfony 4.
In one of those mysteries, the string loader extension is not loaded by default. Never understood why. Seems harmless enough. S4 just needs a single line in your services file: # config/services.yaml services: Twig\Extension\StringLoaderExtension: You can then use "bin/console debug:twig | grep string" to confirm it is available.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "symfony, twig" }
"Invalid conversion" error when using malloc? > **Possible Duplicate:** > invalid conversion from `void*&#39; to `char*' when using malloc? I'm trying to allocate a matrix dinamically on the memmory using pointers, but I keep receiving the error messages: > |122|error: invalid conversion from 'void*' to 'int**'| > > |124|error: invalid conversion from 'void*' to 'int*'| Here is my code, I can't see what I'm doing wrong... this "void*" conversion does not make sense for me... int i,j; int **a; int c = 2; /* Form the matrix */ a = malloc((nxy+1)*sizeof(int *)); for (i=0;i<=nxy;i++) a[i] = malloc((nxy+1)*sizeof(int)); for (i=0;i<=nxy;i++) for (j=0;j<=nxy;j++) a[i][j] = 0;
You are compiling your program with a C++ compiler. You have two choices: 1. Don't do that. Use a C compiler. 2. Cast the return value from `malloc()`.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 2, "tags": "c, pointers, matrix" }
json_encode not working in my wamp Good day, I have a question with regards to the json_encode function. I searched the web for answers about this however, all of them says that json_encode function can be used in PHP 5.3. I am using PHP 5.3 in a wamp server, however whenever I write this code echo json_encode($months); where months is: $months = Array("January", "February", "March", "April","May","June","July","August", "September","October","November","December"); I am always getting "Unexpected T_ECHO" error. Can anyone inform me if I am missing something?
You've goofed up on the previous line. Check for a missing semicolon.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "php, wamp, json" }
How to select conversations where only two participants involved? I need to check if participant A and participant B ever had any conversation between them **privately**. If they two involved in **group** chat, **I don't want** that conversation. So how do I structure my query where it will check if `count(participant_id) == 2`? I tried this but it gives error: select conversation_id from chat where participant_id == A AND participant_id == B AND COUNT(participant_id) == 2 table structure ![enter image description here](
SELECT conversation_id FROM chat GROUP BY conversation_id HAVING COUNT(DISTINCT participant_id) = 2 AND MAX(participant_id) IN (A,B) AND MIN(participant_id) IN (A,B) The HAVING clause is required when trying to evaluate values that are calculated by aggregate functions such as count. You need to count just the unique ID's involved in the conversation too. By the way, if this query returns nothing that may mean you don't have any conversations that meet the profile.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, mysql" }
Please help me with C++ Namespace #include <iostream> #include <cstdlib> namespace A { int a = 10; void get_value(){ std::cout << "a = " << a << std::endl; } } namespace B { int b; void get_value(){ std::cout << "b =" << b << std::endl; } } void set_B(); int main(){ using namespace A; get_value(); set_B(); system("PAUSE"); return 0; } void set_B(){ using namespace B; b = 15; get_value(); // Why call to get_value() is ambiguous, error is not generated here ? } Why call to `get_value()` inside `set_B()` function is not ambiguous ( `A::get_value()` or `B::get_value()`) as both appear as `::get_value()` inside `set_B()`.
`using namespace A;` isn't active inside `set_B` because it only appears inside `main`. It is limited to the scope in which it appears: the body of `main`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c++, namespaces" }
SQL. how to compare values and from two table, and report per-row results I have two Tables. table A id name Size =================== 1 Apple 7 2 Orange 15 3 Banana 22 4 Kiwi 2 5 Melon 28 6 Peach 9 And Table B id size ============== 1 14 2 5 3 31 4 9 5 1 6 16 7 7 8 25 My desired result will be (add one column to Table A, which is the number of rows in Table B that have **size** smaller than **Size** in Table A) id name Size Num.smaller.in.B ============================== 1 Apple 7 2 2 Orange 15 5 3 Banana 22 6 4 Kiwi 2 1 5 Melon 28 7 6 Peach 9 3 Both Table A and B are pretty huge. Is there a clever way of doing this. Thanks
Use this query it's helpful SELECT id, name, Size, (Select count(*) From TableB Where TableB.size<Size) FROM TableA
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, teradata" }
Can a contract be renewed without consent? I am a contracted software developer in the United States. My contract will expire in about 5 months. Are they able to renew it without my consent? I ask this because I am not familiar with the contracting process.
Does the contract have a clause which says anything about automatic contract renewal? When it doesn't, the contract is over when it is expired and you both need to explicitly agree to a new contract. Now what if the contract ends, you both act as if it hadn't (you keep working, they keep paying) and then get into a dispute after a while? I (as a legal layman) _could imagine_ that a court of law _might_ rule that you both implicitly agreed to a contract extension through your behavior. But that depends on a lot of factors (ask a lawyer for details). Working with no contract is an ugly situation for everyone involved, so you should better sort out your working arrangement before the contract ends.
stackexchange-workplace
{ "answer_score": 2, "question_score": 0, "tags": "united states, contracts" }
HTML5 mobile app - when to simply use UIWebView and when to use PhoneGap? I am a web developer who needs to build an HTML5 mobile app - which we will need to try and submit to app stores, including Apple's App store. Therefore, I need to somehow wrap my app into a native framework. That being said, I don't have time to learn the nitty gritty of Objective-C and figure it all out. I am trying to decide between using a service like PhoneGap, or simply creating a smaller native app with a webview that pulls up my mobile app from my site's server. In this case, the only native hardware that my app needs to be in touch with are push notifications (probably through Urban Airship) and Geolocation (which can be accomplished via HTML5). When is it wise to go with something like PhoneGap vs. simply creating a UIWebView, and vice versa? Which would you suggest in this case?
Apple is loyal enough to PhoneGap apps - almost no problems with approval on iStore. You should just follow Apple Human Guidelines and everything should be OK. PhoneGap provides lot's of different and interesting features. Also it's cross-platform - works great on iOS, Android, WP7 etc. I think it's the best way to wrap your HTML5 and JS. Talking about pushes - if you select phonegap, i recommend to look at pushwoosh service.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ios, cordova, uiwebview" }
How to create the blConnection how to create the blConnection (connection to the database)
This will assign DB Connection path to a variable public class blConnection { private string constr = "Data Source=.\\MSSQLEXPRESS;Initial Catalog=DB_Name;Integrated Security=True"; public string getConstr() { return constr; } } Then you can reuse it in BL classes public class blCustomerInformation { SqlConnection conn; SqlCommand cmd; SqlDataAdapter ada; blConnection myConn = new blConnection(); public blCustomerInformation() { conn = new SqlConnection(myConn.getConstr()); conn.Open(); cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; ada = new SqlDataAdapter(); ada.SelectCommand = cmd; } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "c#, sql" }
OnTime function Confusion I have written down below VBA code to be executed after every 5 seconds but it does not work. Option Explicit Public RunWhen As Double Public Const cRunIntervalSeconds = 5 ' two minutes Public Const cRunWhat = "TheSub" ' the name of the procedure to run Sub StartTimer() RunWhen = Now + TimeValue(0, 0, cRunIntervalSeconds) Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _ Schedule:=True End Sub Sub TheSub() '''''''''''''''''''''''' ' Your code here '''''''''''''''''''''''' MsgBox "hi this is working" StartTimer ' Reschedule the procedure End Sub What is that I am missing here ? Also a simple expression like below also don't works Sub test() Application.ontime (now() + TimeValue("0:0:5")),"test" End Sub
You should be using the TimeSerial function, not TimeValue. Option Explicit Public RunWhen As Double Public Const cRunIntervalSeconds = 5 ' two minutes Public Const cRunWhat = "TheSub" ' the name of the procedure to run Sub StartTimer() RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds) Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat End Sub Sub TheSub() '''''''''''''''''''''''' ' Your code here '''''''''''''''''''''''' Debug.Print "hi this is working" StartTimer ' Reschedule the procedure End Sub This works and you can watch the VBE's Immediate window to see it run through.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "vba, excel" }
How to write Java code that is synchronized on an instance of an entity I'm using Hibernate and Spring and I want to write Service code to cater for the scenario where, in two separate threads, a `DAO` is used to fetch an entity instance by id, and it is the same id / database row in each case, and I don't want a given method to run concurrently in both threads for that entity instance. I'm not sure whether it is possible to write... synchronized(entity) {} or whether this is not possible because each thread could have created a different instance of the object in memory when retrieving from the `DAO`, both referring to the same entity instance. If indeed it is possible for Hibernate to create multiple objects in memory for the same entity instance, what is the best way to do what I am trying to do?
That won't work. Hibernate might (and often will) return a different instance when you load data from the database. The reason for this is that two threads might want to access the same object at the same time. If Hibernate would give both the same instance, then changes by one thread might (or not) be visible to the second thread. To achieve what you want, you need a central registry where you can get a lock for an entity by ID. That way, every thread can do: Object lock = lockFactory.getLock(id); synchronized(lock) {...} Your factory can then make sure that all threads get the same lock for the same ID.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 7, "tags": "java, multithreading, hibernate" }
How does spatially white noise differ from diffuse noise In noise reduction, having read that directivity index is used to reduce diffuse noise and white noise gain reduces spatially white noise, I would like to know the difference between both the noise types. Is it that diffuse noise is identically distributed but not white? Hope some one could help :)
In a diffuse noise field the noise energy flows in all directions with equal probability. This does not mean that the noise at one point is uncorrelated with the noise measured at another point. On the other hand, for spatially white noise, also called incoherent noise, the noise signals at two different points in space are always uncorrelated. An example for a diffuse noise field is noise in a car or in an office. An example for spatially white noise would be amplifier noise in a microphone array, where the noise in each channel is independent of the noise in other channels.
stackexchange-dsp
{ "answer_score": 1, "question_score": 0, "tags": "audio, noise, denoising, background subtraction" }
readlink unable to take path names mentioned in a file while read -r line do readlink -f $line > a.txt done < $1 I have a file which contains 30 symbolic destination pathnames passed by $1. I want to read this file line by line and wants to save ls results of each path in a file a.txt. The problem coming is that its only taking last path name mentioned in $1. Its ignoring upper 29 lines. Why?
Change readlink -f $line > a.txt to readlink -f "$line" >> a.txt > The >> appends to a file or creates the file if it doesn't exist. > > The > overwrites the file if it exists or creates it if it doesn't exist. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "bash, readlink" }
Azure Application Insights for Worker Role I am setting up Application Insights for a worker role, and the documentation states: > Add the Application Insights for Web NuGet package. This version of the SDK includes modules that add server context such as role information. For worker roles, use Application Insights for Windows Services. I cannot find a a Windows Service version of the Nuget package. Does anyone know what it is called (if it exists)?
You would need these nuget packages: Microsoft.ApplicationInsights Microsoft.ApplicationInsights.Agent.Intercept Microsoft.ApplicationInsights.DependencyCollector Microsoft.ApplicationInsights.PerfCounterCollector Microsoft.ApplicationInsights.TraceListener Microsoft.ApplicationInsights.Web Microsoft.ApplicationInsights.Web.TelemetryChannel Here < you can find a sample of a project that is set up with documentation. be sure to read the chapter: Report Dependencies
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "azure, azure worker roles, azure cloud services, azure application insights" }
How to use Google Map with Awesomium? How to call this code in C#? function initialize() { var mapOptions = { center: new google.maps.LatLng(-34.397, 150.644), zoom: 8 }; Awesomium v1.7.5.0
You can use `WebControl.ExecuteJavascript` method to call your JS method from C#. yourWebControl.ExecuteJavascript("initialize()"); If you need some result returned from javascript, it may be obtained from `ExecuteJavascriptWithResult`. Global javascript objects that will persist between all loaded pages can be created with `CreateGlobalJavascriptObject` method. See documentation describing Awesomium `WebControl` methods.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -4, "tags": "c#, .net, google maps, awesomium" }
HTML + CSS Image link won't work after moving the image Basically i want to position my Image under my name(in my website which is in the middle of the screen) when i move the image DOWN the link no longer works, i can move it left or right as much as i want and it works! but up and down, it no longer works? HTML: <a href=" target="_blank"> <div class="imgtest"> <img src="/images/steam-icon.png" alt="HTML tutorial" style="width:42px;height:42px;border:0;"> </div> </a> CSS: .imgtest { position: relative; left: 800px; top: 100px; border: 3px solid #73AD21; }
Fixed: I fixed it by adding: z-index: 1; To my css part of the image/Link So before it was .imgtest { position: relative; left: 800px; top: 100px; border: 3px solid #73AD21; } Now its: .imgtest { position: relative; left: 800px; top: 100px; border: 3px solid #73AD21; z-index: 1; } Hope this helps others! Thanks for those who tried to help!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css, image, hyperlink, position" }
What's the max # of concurrent connections / HTTP requests per sec I should make to a given domain? I'm downloading a full catalog worth of **static image content** (million+ images, all legal) from various webservers. I want to download the images efficiently, but I'm considering **what limits** per domain I should place on the **# of concurrent connections** and **time between connection attempts** to avoid being blacklisted by DOS tools and other limiters.
The keyword I needed to look for was "webcrawler politness", that popped up some useful articles that answer the question quite well: Typical politeness factor for a web crawler? <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "http, web, connection, web crawler, httprequest" }
Is there a nicer way to write a self referential let expression i.e. can we write the following more concisely? bar in_env a = let out_env = foo in_env (R a out_env) in out_env I want to write it something like bar in_env a = foo in_env (R a ??) But maybe it isn't possible?
First, rewrite it like this, so that you'll be able to easily eta-reduce away `out_env` in the next step: bar in_env a = let out_env = foo in_env . R a $ out_env in out_env Then, use the fact that recursive `let` is equivalent to `fix`: import Data.Function (fix) bar in_env a = fix $ foo in_env . R a
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "haskell" }