INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
django filter by date range from a foreign key I have models defined like the following: class Order(models.Model): order_date = models.DateTimeField(auto_now_add=True, blank=True) class OrderDetail(models.Model): order = models.ForeignKey(Order) I am trying to filter out some entries based on dates as follows: gl = OrderDetail.objects.filter(order.order_date__range=('2015-02-02','2015-03-10')) But i am getting the following error: File "<console>", line 1 SyntaxError: keyword can't be an expression
Django uses the `__` syntax to replace the `.` in filter queries. gl = OrderDetail.objects.filter(order__order_date__range=('2015-02-02','2015-03-10'))
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "django, django filter" }
assertions in native c++ / debugging example of using assertions during debugging: char* append(char* pStr, const char* pAddStr) { // Verify non-null pointers assert(pStr != nullptr); assert(pAddStr != nullptr); // Code to append pAddStr to pStr... } Calling the append() function with a null pointer argument in a simple program produced the following diagnostic message on my machine: Assertion failed: pStr != nullptr, file c:\beginning visual c++ 2010\examples visual studio project files\tryassertion\tryassertion\tryassertion.cpp, line 10 I would like to know if assertions are neccesary. What is the point of using them if i can use if-else expressions to output my own error messages?
An assertion **is** a conditional check; it's just a macro that's something like this (simplified): #define assert(b) if (!(b)) { std::cerr << ...; exit(1); } I can think of two advantages: 1. When you compile in release mode (i.e. not in debug mode), then all the `assert`s will compile away to nothing, so you will incur no runtime overhead. 2. `assert` is an idiom; other programmers know to look for them, and they're also distinct from "normal" control flow.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c++, debugging, assertion" }
error Failed at the [email protected] ng-high-memory script I got stuck to create build due to this issue, Why i am getting this error? ![enter image description here]( Already ran these commands but did not meet the result **ng build --prod --aot --vendor-chunk --common-chunk --delete-output-path --buildOptimizer** **npm cache clean** **npm cache clean -- force** **ng update @angular/cli@^8 @angular/core@^8** **Deleted package-lock.json and run npm install** **npm run ng-high-memory** \-- getting error while running this command for increasing memory, I already increase error and warring memory manually also. Help me find out a solution for this.
Would you try this command using the `cmd` in the same directory. Because some time the Powershell doesn't run the ng commands and npm commands properly You can change the default terminal to the Command Prompt by pressing this Keys `Ctrl + Shift + P` then type in Select Default Terminal. You will get two to three options then select the **Command Prompt** You can also select the default command prompt from the drop down available in the terminal After the selection open a new terminal and try your commands
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "angular, npm, build, angular8" }
How to use a variable in the python connection.request url Im trying to read the server names(eg: server1) in a variable and pass it to a url. However, url doesnt take the variable but only the server name hardcoded in it. Is there any way for me to accomplish this? def connect_to_BNAserver(BNAserver): connection = http.client.HTTPConnection(BNAserver) baseurl="' header = {"WSUsername": BNAUser, "WSPassword": BNAPass,"Accept": "application/vnd.brocade.networkadvisor+json;version=v1"} connection.request('POST',BaseUrl,headers=header) The below works: header = {"WSUsername": BNAUser, "WSPassword": BNAPass,"Accept": "application/vnd.brocade.networkadvisor+json;version=v1"} connection.request('POST','
First variable names are case sensitive. Second, you shouldn't put quotes in the URL (you don't have them in the working case). def connect_to_BNAserver(BNAserver): connection = http.client.HTTPConnection(BNAserver) baseurl=" header = {"WSUsername": BNAUser, "WSPassword": BNAPass,"Accept": "application/vnd.brocade.networkadvisor+json;version=v1"} connection.request('POST',baseurl,headers=header)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x, url, http.client" }
Intel x86 Assembly - Reading and copying the carry flag I am currently creating a program to convert an decimal into binary. I am currently using the shifting method in order to get the 0's and 1's. I have looked at other threads which leads to using LAHF and PUSHF to access the flags and set it; however, all I want to do is get the current value of the carry flag and store it into a register (i.e: 1's or 0's at that current position) which will later be copied into the array. Since I am not too familiar with LAFH or PUSHF, I was wondering if you can complete the same task I asked above using LAFH or PUSHF. For example, I want to move the current CF into eax: **mov edx,cf** (I know this doesn't work, but I am looking for something like this). After I have copied either the 1 or 0, I will then move it into the array which was passed from a C++ program.
I find the most obvious way to store the carry in EDX is: setc dl movzx edx, dl It is shorter (6 bytes) than the methods proposed in the other answers but the shortest (5 bytes) has to be: pushfd pop edx and edx, 1
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "assembly, x86, flags, carryflag, eflags" }
Privilege icon alignment broken when documentation tab is selected The vertical alignment of the privilege icon is broken when the "documentation" tab is selected: !good * * * !bad Why still not fixed after more than 4 months?
The cause of this bug is that when you select the "documentation" tab, the page loads the "docs.css" stylesheet, which adds `vertical-align: middle;` rule for `.icon` selector. Removing the `top: 2px;` rule from selector `.rep-card .progress-bar .icon, .progress-bar.green .icon, .rep-card .progress-bar-large .icon, .progress-bar-large.green .icon` fixes this problem.
stackexchange-meta_stackoverflow
{ "answer_score": 18, "question_score": 18, "tags": "bug, design, profile page" }
MySQL failing to log in for mysqldump I'm trying to use `mysqldump` in my server, from the command line. root@xxxxx:/xx/xx/xx/backups/09-03-13# mysqldump db_name_xxxx --tab=. --user=xxxx --password=xxxxx mysqldump: Got error: 1045: Access denied for user 'xxxxx'@'localhost' (using password: YES) when executing 'SELECT INTO OUTFILE' So I assume it's a problem with username/password. However, I can get into the MySQL command line fine using `mysql`, with exactly the same logon details. What could be causing `mysqldump` to fail, but not `mysql`?
Your problem is not with the login details but with the user you are logging in as. In order to carry out a mysqldump you need at least `SHOW DATABASES, SELECT, LOCK` privileges on every table in the database. Things get more complicated if you use more exotic options such as locking etc. This is a faily good reference for what permissions you need for what options in mysqldump.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
Omit unused XML elements during XSLT transformation I'm trying to transform XML document using XSLT. Some elements from original XML document is unused in my XSL document, but values of these elements are added to the result. How can I omit such elements? Example: XML <?xml version="1.0"?> <data> <id>1</id> <name>Test</name> <description>Test description</description> </data> XSL <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl=" version="1.0"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <xsl:template match="id"> <id> <xsl:apply-templates/> </id> </xsl:template> </xsl:stylesheet> Result <id>1</id>TestTest description Expected result <id>1</id>
What you see is the result of the built-in template rules that copy text nodes as the default. The simplest way to prevent this is to be more specific - for example, do: <xsl:template match="/data"> <xsl:copy-of select="id"/> </xsl:template>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xml, xslt" }
In yii How to generate login functionality In yii i am creating login functionalities. But in my case client side design is in extjs and server side design is in Yii framework. So in yii controller i want to create login functionality in such a way that client will enter username and password. In extjs this data will be accepted in Json format,it is then encoded and sent to server. So now at server side i will receive username and password. so my work is to create login functionality in Yii using this received username and password from extjs. i.e. at starting phase i want to create login functionality assuming hard coded username and password. So can you please help me.
If you are using POST method inf from to send JSON encrypted data in the login form, you can retrieve it in controller with $_POST['your_post_variable'] similar to actionLogin method (Note: Make sure that you are calling correct method in form action). Please share the Login Form. Regards, HBK
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "extjs, yii" }
Is it safe to migrate from composite PK to single PK like this I have a table with a composite PK _(code_id, user_id)_ , that already have 100k records. Is it safe to move from composite PK to a single PK like in the example below? ALTER TABLE orders DROP CONSTRAINT pk_code_id_user_id, ADD COLUMN order_id SERIAL, ADD CONSTRAINT pk_order_id PRIMARY KEY (order_id);
Yes, that is safe and will work. The only problem is that this statement can take a while to get done: * all rows have to get updated with the `DEFAULT` sequence value * a new unique index is built * PostgreSQL checks that `order_id IS NOT NULL` for all rows During that time, the table is locked in `ACCESS EXCLUSIVE` mode, so it is not available even for concurrent reading. But with a tiny table like that is should not be a big problem. Things get more complicated if there are foreign key constraints that reference the old primary key constraint. You'd have to drop those as well and think of a good replacement.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "postgresql" }
ionic on IOS Google Maps JavaScript API error: RefererNotAllowedMapError hay, im develop an app on ionic platform , im trying to get some information from google api to show on map In ionic 4.7.1 on IOS I try to access Google Maps services and get the following error: Google Maps JavaScript API error: RefererNotAllowedMapError < Your site URL to be authorized: ionic://my-domain/home/appointments-new/appointments-search-fields The request with an ionic preffix instead of https preffix and causes error of CORS.
The `RefererNotAllowedMapError` means that the current URL loading the Maps JavaScript API has not been added to the list of allowed referrers, as per Error Messages documentation (< As per the error message you have shared, you can add ionic://my-domain/home/appointments-new/appointments-search-fields to your list of website restrictions for the API key you're using. The steps on how to do this can be found here: * < * <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, angular, google maps, cordova, ionic framework" }
Make Unit Test Wait for Data filled by Asynchronous Fetch I have a unit test which includes rendering a component that uses `useSWR` to fetch data. But the data is not ready before the `expect()` is being called so the test fails. test("StyleOptionDetails contains correct style option number", () => { renderWithMockSwr( <StyleOptionDetails {...mockIStyleOptionDetailsProps} /> ) expect(screen.getByText(123)).toBeInTheDocument(); }); But if I put in a delay `setTimeout()`, it will pass the test. setTimeout(() => { console.log('This will run after 2 second') expect(screen.getByText(123)).toBeInTheDocument(); }, 2000); **What is the correct way to create a delay or wait for the data?**
I have a similar answer elsewhere for a ReactJS question, Web Fetch API (waiting the fetch to complete and then executed the next instruction). Let me thresh out my solution for your problem. If your function `renderWithMockSwr()` is asynchronous, then if you want it to wait to finish executing before calling the next line, use the `await` command. await renderWithMockSwr( <StyleOptionDetails {...mockIStyleOptionDetailsProps} /> ) `async` is wonderful. So is `await`. Check it out: Mozilla Developer Network: Async Function
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 6, "tags": "reactjs, unit testing, jestjs, react testing library, swr" }
Best way to add tr element mid-way through a list of table rows - jQuery first post on the site! I'm looking for some help inserting tr elements mid-way through a simple table like the one below: <table id="content"> <tr class="item"> <td><p>header content</p></td> </tr> <tr class="item"> <td><p>footer content</p></td> </tr> </table> I am adding elements using jQuery with the following code: $('<tr class="item" />').insertAfter('#content tr:first'); However after adding an element using this command, I would like to add some more (but after the last added item, not at the top of the list) Im sure there are simple ways of doing this (by assigning an id to the footer element, and using .insertBefore('#footer') for example) but it would be interesting to know some different techniques that could be used. Thanks in advance! :)
If the row will always be assigned to the element before the footer row, then your idea to add an ID would seem to make sense. If you don't want to use an ID, then use an idea similar to your `:first` selector. Do `insertBefore('#content tr:last');` $('<tr class="item" />').insertBefore('#content tr:last');
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery" }
non www .htaccess redirect - ignore other subdomains I have a .htaccess redirect for "non www" like this: RewriteEngine on RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ [R=301,L] it is working. But, i have also some subdomains other than www. If I call for example < it redirects me to: < I dont want to write the subdomains into the .htaccess file, it should work automatically, just ignore anything else than www and '' like this: if subdomain =='' -> redirect to www.HTTP_HOST.... elseif subdomain !='' && subdomain !='www' -> do nothing. thanks!
try this: Options +FollowSymlinks RewriteEngine On RewriteCond %{HTTP_HOST}//s%{HTTPS} ^www\.(.*)//((s)on|s.*)$ [NC] RewriteRule ^ http%3://%1%{REQUEST_URI} [L,R=301] Just tried it with internetagentur.drupal-webmaster.de (the subdomain) - the main is without www.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 7, "tags": "apache, .htaccess, mod rewrite, redirect" }
TypeError: 'float' object cannot be interpreted as an index, how to solve it? The error message is: File "dry.py", line 1184, in < module > grid = getmap(grid) File "dry.py", line 690, in getmap data = array(data, 'f').reshape(pts[2], pts[1], pts[0]) TypeError: 'float' object cannot be interpreted as an index I'd appreciate any help.
can you write in your question an example of what the values of pts[0], pts[1], pts[2] looks like? if the values are close to integers (like 1.00004 or 3.9998) you can use the round function to round the values to the nearest integer like: data = array(data, 'f').reshape(round(pts[2]), round(pts[1]), round(pts[0]))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "python" }
define 32bit on 64bit i have some C files here (you don't need to know what's inside), it's in stable 32bit mode (with gcc -m32), now i want to do more 64bit (gcc -m64) it has some minor bugs\ * question: so how to use a 32bit C number (how 32bit works), on 64bit\ * more understandable explanation: i want to use 32bit in 64bit mode (-m64, there is some way works 32bit C cannot work in 64bit C) The most common error about this problem: "Cast to pointer from integer of different size" I really need help!\
"Cast to pointer from integer of different size" Oh no. Go through your code and get rid of all casts between pointer and integer that don't convert from or to `intptr_t`, `uintptr_t`, or `ptrdiff_t`. If you convert between pointer and other-sized integer it won't work no matter how many layers of indirection you use. Once you've done that and you still need certain-sized integers for I/O reasons use the definitions from `stdint.h`: `int16_t`: signed 16 bit integer `uint16_t`: unsigned 16 bit integer `int32_t`: signed 32 bit integer `uint32_t`: unsigned 32 bit integer `int64_t`: signed 64 bit integer `uint64_t`: unsigned 64 bit integer Keep `size_t` for array sizes, don't use it in on-disk formats. It changes.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -2, "tags": "c, gcc" }
sql select tuples and group by id I have the current database schema EMPLOYEES ID | NAME | JOB JOBS ID | JOBNAME | PRICE I want to query so that it goes through each employee, and gets all their jobs, but I want each employee ID to be grouped so that it returns the employee ID followed by all the jobs they have. e.g if employee with ID 1 had jobs with ID, JOBNAME (1, Roofing), (1,Brick laying) I want it to return something like 1 Roofing Bricklaying I was trying SELECT ID,JOBNAME FROM JOBS WHERE ID IN (SELECT ID FROM EMPLOYEES) GROUP BY ID; but get the error not a GROUP BY expression Hope this is clear enough, if not please say and I'll try to explain better
EDIT: WITH ALL_JOBS AS ( SELECT ID,LISTAGG(JOBNAME || ' ') WITHIN GROUP (ORDER BY ID) JOBNAMES FROM JOBS GROUP BY ID ) SELECT ID,JOBNAMES FROM ALL_JOBS A,EMPLOYEES B WHERE A.ID = B.ID GROUP BY ID,JOBNAMES; In the with clause, I am grouping by on ID and concatenating the columns corresponding to an ID(also concatenating with ' ' to distinguish the columns). For example, if we have ID NAME 1 Roofing 1 Brick laying 2 Michael 2 Schumacher we will get the result set as ID NAME 1 Roofing Brick laying 2 Michael Schumacher Then, I am join this result set with the EMPLOYEES table on ID.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, oracle" }
How to log my Remote Desktop / Terminal Services activity on Windows XP I am working remotely (Windows 7), and connecting to my Windows XP machine at the office via Remote Desktop via Citrix. Is there a simple way to log my activity other than just the logon and logoff? If my boss ever questions my work, I'd like a simple way to show that my machine was connected to and very active since I get much more done from home without all the distractions of an office! Thanks.
Maybe a piece of software such as **RescueTime** will do the trick (installed on your XP computer in the office). If you have pretty graphs of computer usage to back up your argument, I doubt your boss will be able to argue back. > RescueTime sits in the background and measures which application, web site or (optionally) document is actively being used. !alt text Another option is **Wakoopa** which also has pretty graphs. > How productive are you? Know what you use and for how long.
stackexchange-superuser
{ "answer_score": 2, "question_score": 2, "tags": "windows xp, remote desktop, logging, citrix" }
Etymology of 'doylum' _Doylum_ was a word commonly used in Leeds, Yorkshire, North of England, where I grew up in the 1960s/70s. It basically means _idiot_ \- "What a doylum!" At the time I thought this was strictly a Leeds word, but a quick search online finds it is still used and appears to be very popular with fans of Newcastle United and Hartlepool football teams. What this says about their quality of players I really couldn't say. It also crops up on Yorkshire dialect sites, but so far I can't find any explanation of its origin. Does anyone have any ideas? Also, Hartlepool and Newcastle are some 75-100 miles from Leeds - does anyone know if the word has spread there in the last 40 years or has it always been used there? Someone suggested to me that it might come from Yiddish as there is a large Jewish population in Leeds, though this would only be relevant if it truly is a Leeds word.
Yaron Matras, in his 2010 Romani in Britain: The Afterlife of a Language has this entry... > **fool** n. **_doylem** ER **dinilo** ; Yiddish **goylem_** > _(ER = European Romani)_ From Wikipedia: _in Modern Hebrew, **golem** is used to mean "dumb" or "helpless". Similarly, it is often used today as a metaphor for a brainless lunk..._ The Yiddish origin is also given here, but that's a page on the University of Manchester's site, where Matras is a Professor of Linguistics. I believe him though, even if he's the only authority I can find.
stackexchange-english
{ "answer_score": 10, "question_score": 14, "tags": "etymology" }
IOS HTML5 Canvas Issue on draw / clearRect I'm using iOS 9.3.2 and having an issue where if I draw an image with a given set of dimensions, then erase that image with the same dimensions (using clearRect), there is a leftover edge of the image. To fix this I was just adjusting the dimensions that I would clear by, which worked until I rotated the phone (which didn't always break it but probably 50% of the time it would break it). Then the edge would come back. This is not a problem in Android on chrome browser, but happens on both safari and chrome on iOS. Does anyone have any suggestions? I haven't been able to find any existing issues related to this, but if you have any help I would greatly appreciate it! Thanks!
This is almost certainly due to anti-aliasing when drawing the image. Some things you can do: * Always draw images on whole pixel x,y coordinates, maybe use: `ctx.drawImage(img, x | 0, y | 0, w, h);` Make sure you are clearing in the same space. This may not work well if your currentTransform is not offset by a whole-number amount. * Set `ctx.imageSmoothingEnabled = false;`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, ios, html, canvas, orientation changes" }
How to upgrade to GNOME 3.30 on Ubuntu 18.04.1 I am a new Linux user and I heard about the new **GNOME 3.30**. Can someone help me with the steps to upgrade my GNOME? I have GNOME 3.28, **Kernel 4.18.7** **Note:** I don't wish to upgrade to 18.10
According to The Best New Features in GNOME 3.30 : > It will be available to download as source code from the GNOME Gitlab page, and be available to try via a live USB image. > > Although many Linux distributions come with GNOME by default few distribute major new releases right away, instead choosing to ship the update as part of a new release. > > Rolling release distros are the exception of course, so Arch, Manjaro and others will likely make this update available soon. Please note the second paragraph. There's also a detailed answer to an earlier question of similar nature here: How to get Gnome 3.14 on ubuntu 14.04. Edit: and now GNOME 3.30 is available via Flatpak. Edit on 20181121: I couldn't find it in <
stackexchange-askubuntu
{ "answer_score": 4, "question_score": 5, "tags": "gnome shell, ubuntu gnome" }
VSTS - How add picklist (string) into the area beside State, Reason, Area and Iteration for the bug Would you be so kind to advise on how to add picklist (string) into the area beside State, Reason, Area and Iteration for the bug, please? Many thanks, in advance! Here is place where the picklist (string) field needs to be inserted
You can't add things to that region. The grey bar is a for system fields that are outside of your control.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "azure devops, picklist" }
AJAX code returns error of "Column cannot be null" for PHP Session variable I'm trying to insert some variables to my database with AJAX but I get this error message: Uncaught mysqli_sql_exception: Column 'chname' cannot be null in clubviewhand.php:20 I don't get how I'm getting this error message. I clearly defined `chname` variable in my AJAX code so it shouldn't be null. I would greatly appreciate some help with this, Thank you.
You forgot & before sname in ajax request. replace xmlhttp.open('GET','clubviewhand.php?cbid='+chcbid+'sname='+chname+'&chpost='+chpost,true); with xmlhttp.open('GET','clubviewhand.php?cbid='+chcbid+'&sname='+chname+'&chpost='+chpost,true);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, php, mysql, sql, ajax" }
If the VP were to invoke the 25th amendment to remove the President as unfit for office, would acting secretaries be able to consent? The 25th Amendment says that the Vice-President, in conjunction with half of the fifteen executive department heads, can declare the President unfit to discharge his duties. Presently only two of the fifteen departments have confirmed heads (Defense and Homeland Security). The other thirteen are headed by acting secretaries (or equivalent). If the Vice President were to invoke the 25th Amendment, who would actually be required to support his declaration of the President's unfitness? Would eight acting secretaries be sufficient? Or do they count? Would only one of the two confirmed secretaries be sufficient? Or would he have to actually wait until there are at least eight confirmed secretaries?
The 25th amendment does not state "Secretary". It states "Principal Officers". That term is generic and has no Constitutional definition. Therefore, I would imagine that Acting Secretaries would count. However, this has never been tested by SCOTUS so there is no way to know for sure.
stackexchange-politics
{ "answer_score": 12, "question_score": 14, "tags": "united states, president, constitution, executive, vice president" }
PHP: Regex alphanumeric and some special characters only I want to use a regex to limit the characters allowed. That is: a - z /* a to z */ A - Z /* A to Z */ 0 - 9 /* 0 to 9 */ _ - /* underscore & dash */ ~ ! @ # $% ^ & * () /* allowed special characters */ and this is my regex function: function validChr($str) { return preg_match('/^[A-Za-z0-9_~\-!@#\$%\^&*\(\)]+$/',$str); } I've actually tried it and the result as I want, but I still was not sure. Is my regex is correct? Or are there other forms regex? Please help as I am still new about this regex. Thank you.
It works as it should. You should only add \ before * to escape it. Check it out here: Regular expression test
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 8, "tags": "php, regex" }
conditional statement not working in Wordpress I'm trying to remove a div if the page is 'our-values' or is a singular custom post type of 'work'. I'm using this code: <?php if( !is_singular('work') OR !is_page('our-values') ) : ?> <?php endif; ?> However, for some reason it's not working when I add the OR. If I try them individually then it works but together they don't work. Can anyone help please?
From the comments : In your case, you got the logic wrong : should be `AND` instead of `OR` \- Right now you are hitting everything - because if it is `work` then it still isn't `our-values` \- change it to `&&` and it will work Good luck to ya mann!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, wordpress" }
What is a pedestrian-friendly city? If a city satisfies a certain condition, it is a pedestrian-friendly city. Here's some examples. Pedestrian-friendly | Not pedestrian-friendly ---|--- Davenport | Fremont Asunción | Dallas Ikast | Istanbul Tucson | Phoenix Tampa | Irvine Abidjan | Chicago Indore | Dublin What is a pedestrian-friendly city? Hint 1: > The word-property tag applies. The geography tag does not apply. Hint 2: > Iraq and Iran are pedestrian-friendly countries. Delaware is a pedestrian-friendly state. Tammy, Thomas, Augustín (note the accent!), and Inez are pedestrian-friendly people. Tacos are a pedestrian-friendly food. Hint 3(a): > Pedestrian-friendliness, in a sense, is all about meters... Hint 3(b): > ...but _initially_ , it’s a matter of _feet_.
Based on hint 3(a) and 3(b), it's clear that this is about > Poetic meters. The city name first letter ("initially" in hint 3(b)) must match the first letter of the meter of that word. > The list of meters (/ is stressed, x is unstressed): > * Iambic (x /) > * Trochaic (/ x) > * Spondaic (/ /) > * Anapestic (x x /) > * Dactylic (/ x x) And the list of cities and their property: > **D** avenport ( **D** actylic) > Fremont (Iambic) > **A** sunción ( **A** napestic) > Dallas (Trochaic) > **I** kast ( **I** ambic) > Istanbul (Dactylic) > **T** ucson ( **T** rochaic) > Phoenix (Trochaic) > **T** ampa ( **T** rochaic) > Irvine (Trochaic) > **A** bidjan ( **A** napestic) > Chicago (Dactylic) > **I** ndore ( **I** ambic) > Dublin (Trochaic)
stackexchange-puzzling
{ "answer_score": 10, "question_score": 9, "tags": "knowledge, pattern, english" }
Customize Map´s Layout I'm developing an application that displays maps without using MapKit IOS. Therefore I am using **Route-Me**. However need to create a few maps with colors according to the design of my application. Is there any way to do this without being use the **MapBox** platform, which requires a payment at some point. Thanks
I am not sure if I completely get what you are asking for. You can generate map tiles from the OpenStreetMap data and configure their appearance, when generating the tiles. You can put these map tiles on a server and display them using route-me. You can as well generate a sqlite database from the tiles and put this database onto the phone together with your application.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, ios, mapkit, route me" }
GNU Find : Get a running counter for the -exec command ( to tag mp3s with running track number ) I want to automatically tag a collection of MP3 to become custom-name VA Albums. Currently, I'm using quite fail-safe commands like this one : find . -name "*.mp3" -exec eyeD3 -A "Indie 2015" -b "Various Artists" {} \; Now, I would like to add a running track number to the files. The most straightforward way would be the current match/line number in the find -exec command - is there such a command? eyeD3 sets the track number by using -n NUM, --track NUM, so I'm searching for something like find . -name "*.mp3" -exec eyeD3 -A "Indie 2015" -b "Various Artists" -n **FIND_MATCH_NUMBER** {} \;
One option, using `globstar` (assuming that you do have files in nested subdirectories, which was why you were using `find` in the first place): shopt -s globstar n=1 for file in **/*.mp3; do eyeD3 -A "Indie 2015" -b "Various Artists" -n "$((n++))" "$file" done With `globstar` enabled, the `**/*.mp3` glob expands to all files ending in `.mp3` in the current directory, as well as in subdirectories. `$((n++))` evaluates to the current value of the counter `$n` and then increments it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "bash, find, counter, gnu, eyed3" }
PHP random sorting I am executing a query which returns me an array of 10 items. Example > [1,20,4,9,56,88,64,12,33,18] How is the easiest way to randomly sort them with no rules and separate it in 2 arrays?
For randomly sort use `shuffle($array);` and for 2 array use `array_chunk() `
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "php, arrays, sorting" }
How to convert plain html to magento theme? I want to convert plain-html of online-store to magento theme. I know about magento layout and template method but is there any way to do this directly, means you just need to enter plain-html of a page and It will be converted into magento theme structure, or is there any extension which can do that?
For that you need to understand the structure of magento and use designer guide for magento documentation for more information
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "magento 1.7" }
Background doesn't resize in responsive tailwindcss I'm busing `tailwindcss` for my css. So for this I defined the image inside the tailwind config. Then I applied a `cover` on it but the image doesn't scale when I change the size of the screen. I thought by adding `max-w-full min-h-full` would fixe the problem but nothing. import React from 'react' import { CountdownEvent } from './CountdownEvent' import { CarouselSaf } from './CarouselSaf' import { Navbar } from './Navbar' export const Home = () => { return ( <section className="h-screen"> <div className="bg-safthon bg-no-repeat bg-cover max-w-full min-h-full"> <Navbar /> <div className="flex h-screen items-center"> <CountdownEvent /> </div> </div> </section> ) }
Try to keep it simple. Check this demo. <div class="min-h-screen max-h-screen bg-cover bg-center bg-no-repeat" style="background-image: url(' </div>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs, tailwind css" }
React routing : URL gets changed but content from component didn't load I am trying to implement react routing in basic react application. I have implemented it but somehow its not working properly. URL gets changed but content from component didnt load. Here is path for code : <
src/app/index.js <Route exact path="/" Component={Root} /> should be <Route exact path="/" component={Root} />
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "reactjs, react routing" }
SMBIOS Hard disk I've read the whole DMTF - SMBIOS Standard Specification but I can't find the **HARD DISK and Ethernet PCI Card Type** structure using SMBIOS Firmware Tables. Do you know which Type refers to hard disk and ethernet card, if for example I want to read the Serial Number of the hard disk and MAC?
As you have discovered, this information is not part of the SMBIOS specification. I'm not sure of your application, but this information is accessible via WMI (Windows Management Instrumentation), assuming you're running Windows. E.g.: ROOT\CIMV2:Win32_DiskDrive.SerialNumber ROOT\CIMV2:Win32_NetworkAdapter.MACAddress
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "hardware, bios" }
Bitwise structure programming in C How does this work? struct { int a : 21; int b : 11; }; Are a and b two separate int variables or the same variable using different bit fields?
These are two separate variables in the `struct`, one named `a` and one named `b`. However, they're sized so that `a` should have 21 bits and `b` should have 11 bits. Accessing one variable and manipulating it won't affect the other variable. Hope this helps!
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "c, bit fields" }
quine (self-producing) SQL query This is a very interesting wiki article about programs that print their own source code without any access to physical source file (in the filesystem). Examples in the articles include C and Scheme quine programs (yeah, it appears they are called like that). I remember someone asking me long ago (about 5 years) whether I could write an SQL query that "returns itself". I had given it little thought back then (to be perfectly honest I hadn't given it any thought at all). But After reading this article I recalled that thing. Now I want to state that the person who asked that problem is not 100% credible in that it is pretty much possible he had no idea what he was talking about. But maybe it's possible? So, does anyone know if there exist quine SQL queries, whatever "return itself" may mean in that context. Thanks.
SQL Server version, from here: SELECT Replace(Replace( 'SELECT REPLACE(REPLACE("$",CHAR(34),CHAR(39)),CHAR(36),"$") AS Quine', Char(34), Char(39)), Char(36), 'SELECT REPLACE(REPLACE("$",CHAR(34),CHAR(39)),CHAR(36),"$") AS Quine') AS Quine
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "sql, quine" }
How to plot a bar graph labels in alphabetical order in python? I have the following bar graph: Click here for bar graph I would like to alphabetically order the Y-axis labels (i.e, control, exclude, necrosis, other, tissue, tumor and not control, other, necrosis, exclude, tissue, tumor). Ho do I do that? What I tried so far? smack = df.roi_name.value_counts() plt.barh(width=smack.values, y=smack.index) plt.xlim(0,50000) plt.xlabel("ROI_NAME count") fig = plt.gcf() fig.set_size_inches(18.5, 10.5) Thanks in advance!
you just need to sort index of your dataframe when you give it to `plt.barh()`, like below: plt.barh(width=smack.values, y=smack.index.sort_values())
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas, bar chart, alphabetical" }
Spark python most repeated value for each key I have an RDD with format: (date, city). And the data inside is something like this: day1, city1 day1, city2 day1, city2 day2, city1 [...] I need to obtain the most "repeated" city by each day, ie I need the following result: day1, city2 day2, city1 day3, ... Can you help me how to do it in Python? I tried to do it like a simple wordcount: rdd.map(lambda x: (x[0], [1]. \ map(lambda y:y,1). \ reduceByKey(lambda a,b: a+b). \ takeOrdered(1, lambda s:-1*s[1]))).collect() But of course it doesn't work... Thanks in advance.
It is just a modified wordcount: rdd.map(lambda x: (x, 1)) \ .reduceByKey(lambda x, y: x + y) \ .map(lambda ((day, city), count): (day, (city, count))) \ .reduceByKey(lambda x, y: max(x, y, key=lambda x: x[1]))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python, apache spark, rdd" }
Trigonometry identities sum and substraction of cosine Someone can help me showing this identity? $\frac{cos(a-b)}{cos(a+b)}=\frac{1+tan(a)tan(b)}{1-tan(a)tan(b)}$
Using the angle sum formula for $\cos$: $$\frac{\cos(a-b)}{\cos(a+b)}= \frac{\cos a \cos b + \sin a \sin b}{\cos a \cos b - \sin a \sin b}$$ Hint: Now all you need to do is to divide the numerator and denominator by $(\cos a\cos b)...$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "trigonometry" }
MySQL workbench SSH connection error [Bad authentication type(allowed_types=['publickey'])] I have issue regarding SSH connection with my server. When i try to connect it results into error:"Bad authentication type(allowed_types=['publickey'])" Thanks
Check your username and public key this can cause problem. Attach the private key file with extension .ppk Also verify your connection with putty. Also check for the restriction on server.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 5, "tags": "mysql workbench" }
ngclass strike in angular I'm making a project in angular. When i click on the checkbox i want that there is a line trough the text. But when i click on the checkbox nothing happens .. Can you help me ? Thanks ! <h3>Todos list</h3> <ul class="list-group"> <li *ngFor="let todo of todos; let i = index" class="list-group-item"> {{todo.text}} <p [ngClass]="{strike: deleted}">test</p> <label> <input type="checkbox" ng-model="deleted"> </label> <button class="btn btn-danger btn-small" (click)="deleteTodo(i)">X</button> </li> </ul>
At first, in Angular it's `[(ngModel)]`, not `ng-model` as in `AngularJs`. Also, you can't have a single variable (`deleted`) to handle all _items_ in your `*ngFor`. To make it wok apply the changes: ... <p [ngClass]="{strike: todo.deleted}">test</p> <label> <input type="checkbox" [(ngModel)]="todo.deleted"> </label> ... **DEMO**
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "html, angular, checkbox, strikethrough" }
How to create procedural surface defects with Cycles? How to create procedural surface defects with Cycles similar to this image? ![](
The simplest way is with a bump map. You can use a mixture of various procedural noise textures and a _Bump_ node to create one quickly: ![enter image description here]( It's up to you to make come up with a texture that you like. I recommend this talk for some tips on generating realistic patterns with procedural textures. ![enter image description here]( This probably isn't necessary in your case, but if you want the bump mapping to affect the actual geometry you can use the _Displacement_ output with _Experimental Features_ enabled. See What is the difference between the displace socket and a bump map?
stackexchange-blender
{ "answer_score": 15, "question_score": 9, "tags": "cycles render engine, materials" }
SQL logical operator What are the occupations that are NOT student, lawyer or educator? List them in descending alphabetical order? SELECT Occupation FROM Viewer WHERE occupation NOT IN 'student,lawyer,educator' ORDER BY occupation desc; I keep getting an error. What am i doing wrong?
`IN` requires a list of expressions surrounded by parentheses: SELECT Occupation FROM Viewer WHERE occupation NOT IN ('student','lawyer','educator') ORDER BY occupation desc; See the documentation for `IN` to see the correct syntax: !IN condition
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "sql, oracle" }
XTickLabel not display the full range I'm trying to display the full range of x-axis labels which contain 16 elements. For some reason, only 8 show up. Please see example below: figure density = (.02:.025:.4); test=rand(1,16); plot(test) set(gca,'XTickLabel',density); As you can see, the x label only display from .02 to .22. It should cover from **.02 to .4.** I tried to play with `XLim` but that didn't help either. Can anyone tell me what I did wrong?
first, you should plot `test` against `density` \- `plot(density,test)`, the way it is now is like `plot(1:length(test),test)`. second, `'XTickLabel'` sets the xtick **labels** = the ticks **names** , what you want is to set `'XTick'` which sets the ticks **values** : figure density = (.02:.025:.4); tt = rand(1,16); plot(density,tt) set(gca,'XTick',density); ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "matlab, plot" }
Proguard with Crashlytics We have added crashlytics in our android application, and we are using `proguard`. So, as the `crashlytics` documentation says, we have added the following code in our `proguard` configuration file: -keep class com.crashlytics.** { *; } -keep class com.crashlytics.android.** -keepattributes SourceFile,LineNumberTable *Annotation* Unfortunately, when we sign the APK, we get the following error: java.io.IOException: proguard.ParseException: Unknown option '*Annotation*' What are we doing wrong? Thanks in advance
Try This ProGuard rules # Crashlytics -keep class com.crashlytics.** { *; } -dontwarn com.crashlytics.** -keepattributes SourceFile,LineNumberTable,*Annotation* -keep class com.crashlytics.android.** And please make sure that `,`s are in place.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "android, proguard, crashlytics, android proguard, crashlytics android" }
Can I operate 2 electromagnetic locks using the same power supply? I'm using this power supply: ![My power supply]( Specs: Input Voltage: AC90V-AC260V 50-60HZ Output Voltage: DC12V Momentary Current: 3A/5A Persistent Current: 3.5A To operate my electromagnetic lock situated on the top edge of the door. ![enter image description here]( Specs: Holding force: 180kg(350lbs) Voltage: DC 12V Current: 380-430mA Working temperature: -10 to 55 Celsius degree (14 to 131 Fahrenheit degree) Humidity: 0 to 95% Working mode: power-on to lock Everything works fine except that my door is aluminum and it's flexible. I want to connect a 2nd electromagnetic lock on the side of the door to make sure it's really locked. Can I use the same power line connecting the first lock to also connect the 2nd lock or is it "depleting" the power supply output? Thanks.
Two mag-locks wired in parallel will draw a max of 430 × 2 = 860 mA = 0.86 A. Your power supply has a rating of 3 A minimum continuous. You'll be running the power supply at 25% of rated power. It will be fine.
stackexchange-electronics
{ "answer_score": 4, "question_score": 1, "tags": "power supply, electromagnetic, dual" }
how can keyboard input from tcl to running bash script I want to start a bash script via Tcl. While the bash script is running, an input field appears after about ~1 minute, so you have to enter something using the keyboard. I want to insert the variable `cc` there. How can I do that? my tcl scrip: bind pub "-|-" !ttest pub:ttest proc pub:ttest {nick host handle channel arg} { set aa [lindex [split [stripcodes bcu $arg]] 0]; set bb [lindex [split [stripcodes bcu $arg]] 1]; set cc [lindex [split [stripcodes bcu $arg]] 2]; set start [exec bash -c "su user -c \"cd /home/user/; bash teststart.sh $aa $bb\""] putnow "PRIVMSG $channel :done" } this comes when I start the bash script directly in the console: user@home:/$ cd /home/user user@home:~$ bash teststart.sh testaa testbb ENTER HERE: (I would like to insert the variable cc here) script done going exit
Here's an expect script that can perform what you are looking for: #!/usr/bin/expect # Put your bash specific command here - I just have bash for now spawn /bin/bash interact { -o -nobuffer "ENTER HERE: " { send $whatever } } Sorry, I can't give you more - I don't actually use expect or tcl (well, not for many years) so I won't be much help to you. I was just hoping to point you in the right direction.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "bash, tcl" }
Lightning component with placeholder I want to create a lightning component to be used on the lightning page. In the component I want to have a placeholder for other components, so the user can add other components per via drag and drop in the lightning app builder. Is it possible? PS: There is a standard component "tabs" that have exactly that what I want. Can I do it on the custom lightning component? ![enter image description here](
You cannot at the moment (or at least there is no documented way of doing so), the only components that support drag and drop placeholder/regions are the following: 1. custom theme layouts 2. custom templates the following Ideas are still pending approval for making this feature available: * Drag communities components into other components in Community Builder * Drag and drop regions on Custom lightning components and as far as the aura frameworks components go, it looks like this may be made available some time in the future since there are several drag and drop reference components under development which can be seen on the forcedotcom GitHub Repo. Unfortuantely, I cant provide any insight on how far up in the list of priorities this is.
stackexchange-salesforce
{ "answer_score": 11, "question_score": 15, "tags": "lightning aura components" }
unity3d OpenGL issue When I start unity3d it shows "OpenGL 2.1 (Deprecated)" in the title bar. running `glxinfo | grep version` shows this: server glx version string: 1.4 client glx version string: 1.4 GLX version: 1.4 OpenGL core profile version string: 4.3.0 NVIDIA 361.45.11 OpenGL core profile shading language version string: 4.30 NVIDIA via Cg compiler OpenGL version string: 4.5.0 NVIDIA 361.45.11 OpenGL shading language version string: 4.50 ...so I have OpenGL 4? How do I fix the issue with unity3d?
From Unity forums: > Right now, the rendering backend is forced to OpenGL 2.1, until we work out some remaining issues with OpenGL core in the linux editor. And: > Unity has multiple rendering backends, even on the same platform. The OpenGL 2.1 is supposed to be removed in near future, superseded by "glcore", which handles features provided by modern OpenGL versions, like tessellation and compute shaders, thus the deprecated in the name. For now glcore has some serious issues so the editor is fixed to the legacy, but battle tested renderer. So no worries, it doesn't mean there's anything bad with your GPU or driver. **Update:** Since version 5.5.0b1, Unity now uses the OpenGL core rendering backend. This means that your development environment must support OpenGL core profile 3.2 or later.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 1, "tags": "opengl, unity3d" }
Generate cURL output from Moya request? I'm using Moya and need to print the cURL for a network request. > Usually, in Alamofire 4, I would do something like this: let req = Alamofire.request(someURLRequestConvertible) debugPrint(req) // will print cURL > My call site for Moya looks like this: MyMoyaProvider.request(MyEndPoints.login(params)) { (result) in } I've checked out the documentation for Moya, but I can't seem to get the results I'm looking for. I enabled the `NetworkLoggingPlugin` but still unsure how to print `cURL` for certain requests. Can someone help me find the proper way to print the Moya `request`'s `cURL` to console?
If you initialize your `NetworkLoggerPlugin`, its `cURL` flag is set to `false` by default. Initializing it like `NetworkLoggerPlugin(cURL: true)`, `willSendRequest` should print the `cURL`. As per @BasThomas on GitHub: <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "ios, alamofire, moya" }
ITemplate and DataGrid Column in Codebehind I have a situation where I need to work with a datagrid and adding columns dynamically in PageInit as the grid has a few conditional requests that it must handle. I'm moving along easily with BoundColumns, and ButtonColumns, those are easy. The problem is with the creation of a TemplateColumn via code. I have found examples out there about creating a custom class that add controls dynamically by creating a class that uses an implementation of ITemplate. That works, however, I'm struggling with how to databind elements. In my grid I would have used <%= DataBinder.Eval(Container.DataItem, "MyValue") %> or similar, but that isn't an option here. The Container when inside ITemplate doesn't have a data item property either, so I can't bind there. Anyone have advice or links that might help, I'm just not finding the right things in google.
You can attach an event handler to the DataBinding event of the controls you create in ITemplate.InstantiateIn as in this MSDN Article. The sender will be the control and the NamingContainer property will be the DataGridItem, which has a reference to the DataItem which you can use to get whatever data you need.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 7, "tags": ".net, asp.net, datagrid, itemplate" }
Javascript progress animation I am trying to build a progress bar using jQuery and javascript. It is basically a bar <div id="progressbar"><div id="progress"></div> <div id="number">0%</div> when you click on the next button (which isnt here) it changes the width of the progress div and using css3 it animates it nicely, but my problem here is the number. I have 5 screens so they are all 20% each and I would like to animate the numbers so while the bar is getting wider the number flicks through all numbers from 0% to 20% in the same time as the bar animation (0.5s) I know with JQuery you could just use the innerHTML command and change it from 0% to 20% but I wanted to animate it. Any idea how to do that?
1st get the jQuery progressbar plugin. Here's an example. Then create a function like: num = 0; function pbUpdate(value){ if (num <= value) { window.setInterval('updAnimation(' + value + ')', 10); }else{ clearTimeout; } } function updAnimation(value){ num += 1; if (num <= value){ $("#pb").reportprogress(num); } } If you look at the examples of the plugin and look at this code, you should get to where you want to go. I've used this code as well.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery" }
Does ArrayList in C# can contain objects various types? Is it possible, to do something like that: ArrayList arl = new ArrayList(); arl.Add(1); arl.Add("test"); int[,] tab = new int[4, 4]; init(tab); arl.Add(tab); Is it possible to contain objects of various types (Like in JavaScript or Lua)? (C#)
Yes, ArrayList contains elements of type object so this means you can put everything in it. When retrieving it again, you can then case it back to its original type. Of course, due to this casting it's less efficient.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "c#, arraylist" }
Is it acceptable to programmatically enable Powershell? I've recently discovered that by default, execution of powershell scripts is disabled. I was going to rely on it to safely remove a USB device from Windows, however if it's not enabled by default, I'd have to enable it first. Is it generally acceptable to do such things? Alternative solutions are also welcome. This question follows: <
MS used to deliver systems that were 'ready-to-exploit'. They got smarter about it, and take security much more seriously. So they now disable many features by default. As for PowerShell, the default 'execution policy' by default did not allow scripts to be run. However, on a command line you could bypass the execution policy all together (ie. without changing it) as long you have permissions to do so: PowerShell -ExecutionPolicy Bypass -file yourfile.ps1 If you are an administrator of the machine, it's perfectly OK to enable it and use it. If you are just an app-owner, you should probably consult with the administrator to change the policy, but as noted above, you may not need to.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "windows, powershell, usb" }
Javascript FileReader Tengo el siguiente código: <input type="file" id="files" name="files[]" multiple /> <output id="list"></output> <script> function handleFileSelect(evt) { var files = evt.target.files; // FileList object // files is a FileList of File objects. List some properties. var output = []; for (var i = 0, f; f = files[i]; i++) { output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes, last modified: ', f.lastModifiedDate.toLocaleDateString(), '</li>'); } document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>'; } document.getElementById('files').addEventListener('change', handleFileSelect, false); </script> Consigo los datos del archivo leído. Como leo el contenido y se lo asigno a una variable ? No consigo entender la API FileReader
Este ejemplo pones solo extraer la información del archivo, es decir, la metadata. De hecho no utilizas FileReader solo File. Te recomiendo leer el API oficial del w3 Y puedes revisar la funcionalidad en este jsfiddle (Yo no lo he creado), **en la prueba puedes subir un archivo de texto y ver el contenido en el navegador** , que es lo que quieres. El truco principal es preguntar si esta soportado el API y de ahí ejecutar el proceso Asíncrono.
stackexchange-es_stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "javascript" }
How to convert video file from ios to base64 in ionic 3 I am trying to convert a video url which we can retrieve from an iOS device and convert it to BASE64 in ionic 3, but I am unable to achieve BASE64 url. iOS Video URL: filePath = `/var/mobile/Containers/Data/Application/3436A7EB-4684-4618-8125-3E6AE1645FCE/Documents/MUS_RA/1534429730643_capturedvideo.MOV` I tried the following code to convert the video URL to BASE64 by using the BASE64 cordova plugin but no luck this.base64.encodeFile(filePath) .then((base64String: string) => { console.log("base64VideoChange"); resolve(base64String); }, (err) => { console.log("base64VideoNOTChange"); reject(err); }); Note: I am using ionic 3. Please help.
Finally i resolved my issue by using ionic readAsDataURL: Imports File plugin to app.module.ts `import { File, DirectoryEntry, FileEntry } from '@ionic-native/file';` In page.ts import { File, DirectoryEntry, FileEntry } from '@ionic-native/file'; getBase64StringByFilePath(fileURL): Promise<string> { return new Promise((resolve, reject) => { let fileName = fileURL.substring(fileURL.lastIndexOf('/') + 1); let filePath = fileURL.substring(0, fileURL.lastIndexOf("/") + 1); this.file.readAsDataURL(filePath, fileName).then( file64 => { console.log(file64); //base64url... resolve(file64); }).catch(err => { reject(err); }); }) }
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 8, "tags": "javascript, angular, ionic3, base64" }
Inequality for Hölder function Let $f$ be a $\alpha$ Hölder continuous function. I need an estimate from above for the expression $\left|f(t_{i_{1}})-f(t_{i_2})\right|+\left|f(t_{i_2})-f(t_{i_{3}})\right|$ Is it possible to estimate this expression by $\left|t_{i_1}-t_{i_3}\right|$. $t_{i_1}\leq t_{i_2}\leq t_{i_3}$?
Note that for $a < b$ and $0 < \alpha \le 1$ the function $x \mapsto (b - x)^\alpha + (x - a)^\alpha$ is concave on $[a, b]$ and therefore has a unique maximum. Since $f'(x) = -\alpha (b - x)^{\alpha - 1} + \alpha (x - a)^{\alpha - 1}$ is zero for $x = \frac{a + b}{2} \in [a, b]$, the maximum is attained at this point and $f\left(\frac{a + b}{2}\right) = 2^{1 - \alpha} (b - a)^{\alpha}$. Applied to your problem, this means $$|f(t_{i_1}) - f(t_{i_2})| + |f(t_{i_2}) - f(t_{i_3})| \le C \left((t_{i_1} - t_{i_2})^\alpha + (t_{i_2} - t_{i_3})^\alpha\right) \le C 2^{1 - \alpha} (t_{i_3} - t_{i_1})^{\alpha}$$ for $t_{i_1} \le t_{i_2} \le t_{i_3}$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "analysis, inequality" }
Should I change/normalize my ER (1:1) diagram? I made an ER of my table, im not sure if its correct. In my table (0NF) are 5 columns: DocumentID, DocumentTitel, revNr., userID, modifiedDate. The table gives an overview which person changed which document. My data (0NF): < ER diagram (bold text = primary key): < Is my ER (1:1) correct for my data? Can I normalize further?
The relationship expressed in your ER diagram appears to be one-to-many, not one-to-one (because DocumentId alone is not unique in the Version table.) Normalization should always be based on an understanding of the business rules that are applicable in your intended design. It isn't sufficient to draw conclusions based only on some sample data. For example, in your case we might easily infer from just two rows of sample data that both {DocumentId} and {Title} ought to be keys in your Document table, or that {DocumentId,revNr} and {DocumentId,modifiedDate} ought to be keys in the Version table. If those were accurate assumptions then your design is incomplete and could certainly be further normalized and improved. Only your knowledge of what dependencies you need to enforce can help you make these design decisions.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "database, database design, entity relationship, database relations, erd" }
Tracking Traffic With Same Domain but Different URL My domain: hospital.org/app 2 Type of user: **\- Patient \- Admin** Example URL for **Patient** : hospital.org/app/fp/main/PA_MedicationsProgress.php Example URL for **Admin** : hospital.org/app/fa/main/Admin_Dashboard.php Currently, I am tracking data for both Patient & Admin but I need to separate the data for 2 types of users here. The URL for the patient will contain "PA" and the URL for the admin will contain "Admin". **My current solution:** Example URL for **Patient** : hospital.org/app/fp/main/PA/MedicationsProgress.php Example URL for **Admin** : hospital.org/app/fa/main/Admin/Dashboard.php But this will require me to change the URL and set up different properties which are not integrated into 1 report. Is there any way for me to show the data differently for these two users without changes these?
You can filter or use a segment in the same Property based the currently URL: `/fp/` or `/fa/` without modify the page name.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google analytics, google analytics filters" }
Iteration in Ruby > **Possible Duplicate:** > count duplicate elements in ruby array I just started learning ruby and I wish to achieve something like this. Let say I have an array ["student", "student", "teacher", "teacher", "teacher"] What I'm trying to do is to count the number of student and teacher and store it into a hash, so that i can get {:student= > 2, :teacher=> 3} Could someone give me some kind of direction on how to do this?
You should check this answer, which gives this example: # sample array a=["aa","bb","cc","bb","bb","cc"] # make the hash default to 0 so that += will work correctly b = Hash.new(0) # iterate over the array, counting duplicate entries a.each do |v| b[v] += 1 end b.each do |k, v| puts "#{k} appears #{v} times" end
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ruby, arrays, hash, iteration" }
joomla 3 "**" stars around strings after changing database user permission I could not save Joomla 3.1 admin options, so I increased my db user privileges. Now what I get is: !enter image description here That is "**" everywhere - in menus. How can that be solved? Language is set to english, SEF is turned off, DB driver is mysql (tried mysqli also). Help appreciated.
This comes from debugging language strings. The asterisks are indicating, that the phrase actually is translated. Go to the GLobal Configuration in the administration and select the System tab. There, set 'Debug Language' to 'No'.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "joomla" }
On demand slave generation in Hadoop cluster on EC2 I am planning to use Hadoop on EC2. Since we have to pay per instance usage, it is not good to have fixed number of instances than what are actually required for the job. In our application, many jobs are executed concurrently and we do not know the slave requirement all the time. Is it possible to start the hadoop cluster with minimum slaves and later on manage the availability based on requirement? i.e. create/destroy slaves on demand Sub question: Can hadoop cluster manage multiple jobs concurrently? Thanks
This seems promising <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "amazon ec2, hadoop, mapreduce" }
a href tag to place a link I have to place a link to a webpage through an `<a>` .The webpage link contains some request parameters and I don't want to send it across through the browser directly (meaning I want to use something similar to POST method of FORM). <a href="www.abc.do?a=0&b=1&c=1>abc</a> I am using this inside a jsp page and is there a way to post it through javascript or any other way where I don't pass the request parameters through the url?
You can use links to submit hidden forms, if that's what you're asking. <a href="#" onclick="submitForm('secretData')">Click Me</a> <form id="secretData" method="post" action="foo.php" style="display:none"> <input type="hidden" name="foo" value="bar" /> </form> <script type="text/javascript"> function submitForm(formID) { document.getElementById(formID).submit(); } </script>
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "javascript, html" }
Converting DOCX file to PDF from command line I am writing a python script and would like to convert a DOCX to PDF. Are there any ways of doing this? Here's my current code: printer_path = 'C:\\Program Files\\Nitro\\Pro\\12\\NitroPDF.exe' doc_path = 'Test.docx' subprocess.call([printer_path, doc_source_path]) Nitro PDF will open and begin converting the file but won't finish. Thank you for any input. Edit 1: For the subprocess.call to work, I had to make both inputs absolute paths e.g. doc_path = 'C:\Documents\Test.docx'
If you have Microsoft Word installed the following should work: subprocess.call('docto -f "C:\Dir with Spaces\FilesToConvert\" -O "C:\DirToOutput" -T wdFormatPDF -OX .pdf', shell=True)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pdf, pdf generation, docx" }
Make the search box return results from all StackOverflowian sites? There should be an easy way to search Server Fault from Stack Overflow (and the others) The easiest thing would be to add a "Try searching Server Fault" link next to the "Alternately, try your search in Google:" on the no-results page, but this wouldn't help with overlapping searches.. For example, searching for `[sql] error 1234` might have better results of ServerFault, but a programmer might only searching SO for such a problem (a reasonable thing to do) Maybe there could be a SO/SF/SU/Meta buttons at the top of the search results, which jump you between sites? Since the user may not be logged into ServerFault, I guess it'd be best to display the results on the current site (with the different colour scheme maybe?), obviously all the links would go to the correct site (` in the example image) A good example of such a feature is Google.
implemented at < (though it searches _all_ sites in the network) > ![](
stackexchange-meta
{ "answer_score": 9, "question_score": 15, "tags": "feature request, search, stack exchange, user interface, integration" }
Changing Data type on Google Big Query: Date Field Error I have created a query to change the data type of the `Date` column from `String` to `Date` the query used is the following: SELECT *, CAST(Date AS DATE) From `table_name` However, when running the query I am receiving the following error: > Invalid date: '18/11/2020' Could someone help me with this?
Use PARSE_DATE instead: SELECT * EXCEPT (Date), PARSE_DATE('%d/%m/%Y', Date) AS Date From table_name or SELECT Account, Campaign_name, PARSE_DATE('%d/%m/%Y', Date) AS Date, Ad_set_name, Ad_name, Impressions, Cost__GBP_, Link_clicks, Reach, Website_conversions From table_name
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "google bigquery" }
differential equations - change of unit $$ \frac {d y}{d t} = -0.002\, y $$ In the above differential equation y is the amount of salt in kg and t is the time in minuttes. I was wondering when i solve the equation whether the time will change unit or not? I can solve the equation with the method separation of variables. If i integrate will the time then change unit to seconds?
The left hand side of your equation has dimension $kg \over min$. The right hand side must have the same dimension. But $y$ has dimension $kg$ which means that constant 0.002 must have dimension $1 \over min$. In other words your equation looks like this: $$\frac {d y}{d t} = -0.002\frac{1}{min}\cdot y$$ Solve equation normally. You get: $$ \ln{y}=-0.002\frac{1}{min}\cdot t+ln{C}$$ ...or: $$ y = C e^{-0.002\frac{1}{min}\cdot t}$$ For any given $t$ just make sure that you cancel the units in the exponent properly. For example, for $t=30s$ the value in the exponent would be: $$ -0.002 \frac{1}{60s} \cdot 30s = -0.001$$ Just have in mind that in the physical world most constants in differential equations have hidden dimensions. You have to understand those dimensions properly, otherwise you won't be able to calculate anything properly.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "ordinary differential equations" }
How to add Range Input to VBA UserForm Many of the built in excel dialog boxes use a range input box like this one: !Range input Boxes in Excel Im not sure if they are called "Range Inputs" or whatever. This is taken from "Data Analysis" in Excel, in case you are wondering. When you click on the little image in the text box, the dialog box disappears and excel allows you to select a range of cells, which it then places in the the text box. If there is a way to incorporate this into a UserForm, please let me know Thanks in advance!
It is called RefEdit Control and works similar to that built in Boxes. If your toolbox does not have a RefEdit control, set a reference to RefEdit control. Click Tools, References, and check Ref Edit Control. Here is an Example how to use it: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "vba, excel" }
Bluebird throwing exception at source code I am using bluebirdjs for nodejs application. It throws an exception from its source code. Line : `try {throw new Error(); } catch (e) {ret.lastLineError = e;}` Path : bluebird/js/release/util.js Line : 374 This exception seems unnecessary to me. It only throws exception. Is it rational to delete this line? Same code also exists inside async.js at line 3.
In IE an `Error` object will not have a `.stack` property unless it goes a through try catch. The `.stack` property is needed to see which line and file the code is in. `ret.lastLineError = new Error()` would therefore only work in firefox and chrome
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "node.js, promise, bluebird" }
How to solve "$4\sqrt5$ is the same as which square root?"? What is the right method for solving a problem like this: ”$4\sqrt{5}$ is the same as which square root?" Possible answers are: * $\sqrt{20}$ * $\sqrt{10}$ * $\sqrt{40}$ * $\sqrt{80}$ I have been informed that $\sqrt{80}$ is the right answer, but I do not understand why.
Because $4=\sqrt{16}$. Then $\sqrt{16}\cdot \sqrt{5} = \cdots$
stackexchange-math
{ "answer_score": 8, "question_score": 3, "tags": "square numbers" }
Meaning of `cat /dev/null > file` In a document created by a former coworker there is this command: cat /dev/null > /var/spool/mail/root It says next to it that it will clean out mailbox. Can someone please explain how/why these commands do that. I need to know what will happen before I run the command. We are trying to clean up space on var, as of right now it's at 91%.
The command will output the data from device `/dev/null` to the given file (mailbox of the root account). Since `/dev/null` responds just with end-of-file when reading from it nothing will be written to the file, but with the redirection `>` the shell will have cleared the file already. Actually this is equivalent to writing just > /var/spool/mail/root (i.e., the same without `cat` or `/dev/null`).
stackexchange-unix
{ "answer_score": 9, "question_score": 5, "tags": "shell, files, io redirection, cat, null" }
DELETE WHERE AND not functioning as expected I am attempting to delete rows from a databases. The `DELETE` query is checking for a match in date from an array and that `reason` is empty. My code is; <?php session_start(); include 'connection.php'; include 'DateTest.php'; $deleted = array(); $size = sizeof($dayOfTheWeek) - 1; for ($count = 0; $count <= $size; $count++) { $query = "DELETE FROM daysoff WHERE DATE(start) = '$dateMonthYearArr[$count]' AND reason = ''"; mysql_query($query) or die("im dead1"); $deleted[] = "Rota deleted for ". $dateMonthYearArr[$count] .".</br>"; } $_SESSION['delete'] = $deleted; header('Location: '. $_SERVER['HTTP_REFERER']) ; ?> This `DELETE` query is dying, if I remove one of the `WHERE` arguments, either one, it works, but the `AND` seems to be an issue. Where is this failing?
Try $query = "DELETE FROM daysoff WHERE DATE(start) = '" . $dateMonthYearArr[$count] . "' AND reason = ''"; And see how it goes...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, sql, where clause, sql delete" }
ССП неоднородное? Верно ли найдено в тексте ССП неоднородного состава? 1. Щель выкопали неглубокую, но зато нарвали травы и устелили ее дно. 2. Ваш сержант Бога молит о тумане, коммунист, между прочим, и потому его молитва действенна.
Все верно. Союз **_но_** и лексический конкретизатор **_поэтому_** указывают на неоднородный состав ССП.
stackexchange-rus
{ "answer_score": 1, "question_score": 1, "tags": "ссп" }
A quad Riley with 4 (little) parts My prefix is a person, trust him you cannot. My first infix is a number, must work with circles to find it. My second infix is confirmative, when you understand what you were told. My suffix is so cold. But overall I'm just tasty for some.
Are you > Spice? My prefix is a person, trust him you cannot. > Spi My first infix is a number, must work with circles to find it. > Pi My second infix is confirmative, when you understand what you were told. > From WEZL "i c(I see) what you are saying". My suffix is so cold. > Ice But overall I'm just tasty for some. > Spice
stackexchange-puzzling
{ "answer_score": 9, "question_score": 9, "tags": "riddle, word" }
MySQL SQL: SELECT (SELECT... as variable) FROM I have a simple question but I can't find an answer (please give me a link if that question is on stackoverflow forum). Table has **orderid** and **quantity** columns. How to select orderid, quantity, total_in_order, where total_in_order is a sum of quantity for current orderid So the table looks the same, but with additional column. Example: orderid - quantity - **total_in_order** 1 - 43 - **78** 1 - 24 - **78** 1 - 11 - **78** 2 - 31 - **31** 3 - 9 - **25** 3 - 16 - **25** So, how to modify `SELECT orderid, quantity, SUM(quantity) from orders;` ? Thank you.
Use a join to a subselect. In the subselect calculate the totals for each orderid. SELECT orders.orderid, orders.quantity, totals.total_in_order FROM orders JOIN ( SELECT orderid, SUM(quantity) AS total_in_order FROM orders GROUP BY orderid ) AS totals ON orders.orderid = totals.orderid
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mysql, select" }
How to know a entity is going to insert or update Because of some limitation, client asked that I can't use incremental "id" primary key, only compound primary key is allowed. And I can't use JPA annotation to have entity callback. Thus how can I know an entity is going to be inserted or updated ? thanks a lot.
Use a version column @Version public Integer getVersion() { return this.version; } Whether it is null so it is an insert else it is an update. regards,
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "hibernate, jpa" }
Auto Login using flutter when using FirebaseAuth I want to auto-login every time the app starts, I am using FirebaseAuth, so my userid is auto-fetched, but it goes to the registration page directly, I want to check if the user exists or not if it exists, move it to the home screen else to the registration page. I know what to do, but where to check this and so navigation?
What you're looking for is what we usually call a Splashscreen. That's the screen you usually see on huge app's startup, with a loader. On this screen, you can do all the stuff that is required for your app to run correctly : * Preload your images. * Load some datas from an API * Check the user's state That's the good place to choose to redirect your user toward the most appropriate screen
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "flutter, firebase, dart" }
Iterating over multidimensional numpy arrays I have a numpy array of dimension (a,b,c). And I want to slice it to over c'th dimension. For eg: A numpy array of shape (2,3,4), I want to iterate over 4 arrays of dimension (2,3). So far I have been doing for i in range(c): arr = A[::,i] But this doesn't compute the right thing. How can I compute this?
You are missing a comma. Your code should look like: for i in range(c): arr = A[:,:,i] BTW the code above is computing the right thing, but you are writing a statement that doesn't solve your problem :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, numpy" }
Jadira usertype no class def found I'm trying to persist a JODA LocalDate attribute using Hibernate. @Column(nullable = false) @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") private DateTime scheduledDepartureTime; I downloaded the following jars: usertype.jodatime-2.0.1.jar usertype.spi-3.0.0.GA.jar usertype.core-3.0.0.GA.jar and added them to my classpath. When trying to execute my application, I get java.lang.ClassNotFoundException: org.jadira.usertype.dateandtime.shared.spi.AbstractSingleColumnUserType When searching for this class in Eclipse, I can find it, but it is located in `org.jadira.usertype.shared.spi`, which explains the Exception Any idea why this class is searched in the wrong package ? Since I'm using the latest version of these jars, I doubt this comes from version problem. Thanks for your help !
`usertype.core-3.0.0.GA.jar` contains `org.jadira.usertype.dateandtime.joda.PersistentDateTime` that you need. Use only two dependencies: usertype.spi-3.0.0.GA.jar usertype.core-3.0.0.GA.jar
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "hibernate, jodatime" }
Does the azure compute emulator simulate the performance? Does the azure compute emulator try to simulate instance performance based on the vmsize specified in the service definition file?
The Azure emulator is a local (your computer) emulator of Windows Azure. It allows you to build and test logic of your application before Azure deployment. The emulator will not reduce performance if you are testing small instance on a very powerful system. So sometimes single emulator instance can perform better in compute emulator than on Azure. However, real power of Azure comes with ability of scaling out your application (among other great features).
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "azure, azure compute emulator" }
UIStoryboard Reference and root view controller I have a "Main" storyboard, inside this storyboard i have a Storyboard reference entity that links to another storyboard "Login". I'm noticing that when i attempt to access the view currently onscreen with the following: [[[[UIApplication sharedApplication]delegate]window]rootViewController] It's returning me the view on the "Main" Storyboard, but if i attempt to push a UIAlertController on this view i get the following error: Warning: Attempt to present <UIAlertController: 0x1839a000> on <ViewController: 0x17633ad0> whose view is not in the window hierarchy! Is there a reason i can't push this view on top, if not how do i get the actual uiviewcontroller currently being displayed from the "Login" storyboard?
If you are presenting `UIAlertController` from your `viewDidload` then it may happen like this because when view is loading at that time it is not in windows hierarchy until it load completely. Second thing you must present `UIAlertController` on top most view controller like, [self presentViewController......]; not on windows rootViewController. So, it's depends hows you are doing this.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "ios, objective c, uiviewcontroller, uistoryboard, uistoryboardsegue" }
Should Gradle's buildSrc folder be committed to source code repo? Sorry for the naive question. I am new to Gradle. Conceptually, it looks like we should commit the buildSrc folder to repo but I see some temp files as well in that folder, which led me to ask this question - Should we commit the entire buildSrc folder to the repo?
`buildSrc` can be used to abstract imperative logic. In other words, declutter your main Gradle build files. < The `buildSrc` folder is basically another Gradle project. So things you would normally ignored for a Gradle project, should also be ignored from the `buildSrc` project. If you have logic defined in `buildSrc` that is required for your project, then yes it should be committed. If not, then that folder should be deleted entirely to avoid Gradle attempting to automatically build it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "gradle, build.gradle, gradle plugin" }
How to upload with curl client certificate authentication? Instead of using basic or digest authentication for an upload, could it be possible for a service to generate a certificate for the client to download for authenticated uploads? Keygen could be used for example, though it might be more straightforward to "Save the certificate" somewhere. Once the user has the certificate, the user is able to then upload "foobar.png" via cURL. Perhaps like so: curl -E mycert.pem -F "[email protected]" Has anyone setup a similar scheme? I'm not sure it's possible as the `-E` switch in the manpage does not mention POST. Also I am unsure how to setup the httpd service to authenticate the certificate. Hopefully just an Apache SSL directive.
Yes its possible. -E works with any HTTP method. You'd of course need to use a HTTPS:// url. You also need to provide a passphrase, and you need to learn that -E takes a private key and the private certificate concatenated (usually, as indicated in the man page). The server-side with Apache is just following the docs as well, yes.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "authentication, ssl, upload, curl" }
Is there a command to check which pods have a service applied I have made a service.yaml and have created the service. kind: Service apiVersion: v1 metadata: name: cass-operator-service spec: type: LoadBalancer ports: - port: 9042 targetPort: 9042 selector: name: cass-operator Is there a way to check on which pods the service has been applied? I want that using the above service, I connect to a cluster in Google Cloud running Kubernetes/Cassandra on external_ip/port (9042 port). But using the above service, I am not able to. `kubectl get svc` shows NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE cass-operator-service LoadBalancer 10.51.247.82 34.91.214.233 9042:31902/TCP 73s So probably the service is listening on 9042 but is forwarding to pods in 31902. I want both ports to be 9042. Is it possible to do?
The best way is follow labels and selectros Your pod have a label section, and the service use it in the selector section, some examples in: < You can find the selectors of your service with: kubectl describe svc cass-operator-service You can list your labels with: kubectl get pods --show-labels
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "kubernetes" }
JS: function for every ul in variable I have this javascript (jquery), in which I've defined a variable. This variable contains a string which might have one or more ul's in it. I want the script to select every ul and run a function for each of them. But unfortunately, nothing happens when loading the page. <script type="text/javascript"> var wid_tekst1 = "<?php echo $wid_tekst1; ?>"; $(wid_tekst1).find('ul').each(function() { alert('hoi'); }) </script> The $wid_tekst1 contains: <p>test tekst 1</p> <ul> <li>testitem</li> <li>testitem</li> <li>testitem</li> <li>testitem</li> <li>testitem</li> <li>testitem</li> <li>testitem</li> </ul> <p>test</p> Thank you
Since the `ul`s are top level elements in your collection you should use `filter` instead of the `find` method. If you want to use the `find` method you can set the string as `innerHTML` of another element: $('<div/>').html(wid_tekst1).find('ul').each(func);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, function, html lists, each" }
JS bad words counter I try to count bad words on a string, but my code always shows 0. What is wrong? function checkWord(list){ var j = 0; var badWords = ["war", "bomb"]; //bad word list for(var i = 0; i<badWords.lenght; i++){ if( list.toLowerCase().search(badWords[i])) j++; //check is it bad word in sting if true j+1 } return j; } console.log(checkWord("sfasdf dgfdfsg sdfsA bomb war")); Always returns: 0 Should be: 2
Please find the below snapshot, this might help :) function checkWord(list){ var j = 0; var badWords = ["war", "bomb"]; //bad word list badWords.forEach(word => { list.includes(word) && j ++ }) return j } console.log(checkWord("sfasdf dgfdfsg sdfsA bomb war"));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, count" }
Vim gg=G (reindent whole file) without losing current position Recently my main work was editing .xml files. Google told me that for re-indenting a file I need to press `gg=G` in normal. But moving to `gg` is something that I don't want. Is there any way to do the same without losing the current position?
Use the ` mark: gg=G`` Or use `Ctrl-O` gg=G<Ctrl-O><Ctrl-O> Or `g;` gg=Gg;
stackexchange-unix
{ "answer_score": 5, "question_score": 2, "tags": "vim" }
Interface for diagrams and example I would like to know if there are interactive graphic-oriented programs to construct diagrams of latex. For example, I know < There are others that do something similar? I am struggling to do this diagram on tikz: ![diag Thanks
It's true—TikZ can be intimidating at first. The 1000+ page manual is downright terrifying. But it's worth it! Start with some of the tutorials at the beginning of the manual. You'll be drawing pictures like these in no time! ![enter image description here]( \documentclass{article} \usepackage{tikz} \usetikzlibrary{decorations.markings} \tikzset{dot/.style={fill, circle, inner sep=1pt}, myarrow/.style={decoration={markings, mark=at position .6 with {\arrow{>}}}, postaction={decorate}}} \begin{document} \begin{tikzpicture} \draw circle[radius=2]; \draw[very thick, myarrow] (-80:2)node[dot, label={-90:{$B'$}}]{}arc(-80:80:2)node[dot, label={90:{$A'$}}]{}; \draw[very thick, myarrow] (100:2)node[dot, label={90:{$A$}}]{}arc(100:260:2)node[dot, label={-90:{$B$}}]{}; \end{tikzpicture} \end{document}
stackexchange-tex
{ "answer_score": 4, "question_score": 0, "tags": "diagrams, tikz arrows, tikz styles, tikz cd, commutative diagrams" }
Open workbook from another workbook without firing the open workbook event? I have two workbooks integrated into the following workflow: 1. I export data from WB1 into WB2 2. I want to check, whether the data in WB2 are up to date. In my VBA Code in `WB1` I use Workbooks.Open "C:\WorkbookName.xls" to get my data from `WB1` into `WB2`. In `WB2` I have `VBA` Code within the `Open Event` to check it the data is up to date. **PROBLEM:** If I use `Workbooks.Open "C:\WorkbookName.xls"` the `Open Event` fires. Is it possible to avoid that and to manipulate the `WB2` from `WB1` without to activate the `Open Event`?
This can be done by disabling the events before opening the file: Application.EnableEvents = False After opening the file you can enable the events again: Application.EnableEvents = True
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "vba, excel" }
Data extraction in Python Pandas I am getting the results from the excel data by using groupby function of Pandas. My code for that is: results = df.groupby(['Test Result', 'Risk Rating']).size().unstack(fill_value=0) which is giving me the results in the form of this table: Risk Rating CRITICAL HIGH LOW MEDIUM Test Result FAIL 8 0 9 4 PASS 0 13 23 37 SKIP 2 0 0 0 Now, I just want to get the result of all "FAIL" which should give me: Risk Rating CRITICAL HIGH LOW MEDIUM Test Result FAIL 8 0 9 4 And, "FAIL" with just CRITICAL which should give me: Risk Rating CRITICAL Test Result FAIL 8 How can I achieve this. Any help would be appreciated.
use .loc results.loc['Fail'] would return values of the index 'Fail' results.loc['Fail', 'Critical'] would return values of the index 'Fail' for Column 'Critical' you can pass list for multiple columns or index such has: results.loc['Fail', ['Critical','HIGH']]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, pandas" }
Search Results Web results Parsing string to IP Address doesn't work some time im trying for convert String IP to ipAddress but for some string this method not working as well , what is the problem? ex: Console.WriteLine("ip address"); string ip = Console.ReadLine(); System.Net.IPAddress IP = System.Net.IPAddress.Parse(ip); Console.WriteLine(IP); for example if i use this string "192.168.001.011" then the IPAddress.Parse method will return me 192.168.1.9 or "192.168.1.012" will return '192.168.1.10' why ?? i'm confused really...
IPAddress.Parse treats leading zeros as octal which is why you're getting an unexpected result. This worked for me. using System.Text.RegularExpressions; .. .. Console.WriteLine("ip address"); string ip = Console.ReadLine(); //Remove the leading zeroes with Regex... ip = Regex.Replace(ip, "0*([0-9]+)", "${1}"); System.Net.IPAddress IP = System.Net.IPAddress.Parse(ip); Console.WriteLine(IP);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#" }
Question regarding flow control of SQL based jobs in SSIS **Question:** I have pertaining to SQL and SSIS : How do I make an SSIS package work according to a logical flow that I mapped out for it? Say there are six steps, I have the logic for how they should all run. So **for example** , if A fails, do b, regardless of failure of b, do C, etc. But it is becoming a huge pain in the back trying to implement this in SSIS. The conventional precedence constraints are too simple and 'linear' for this sort of thing. So, I thought maybe I could create a separate table that stores the values of 'flags' that I will set to 1 or 0 and these flags will correspond to the outcome of each step. I will keep two sets of 6 values in a table, one for last run of my package and one for current run, then make comparisons to ensure consistency of data across multiple tables in multiple runs (accounting for any failure of any step this way) but I have no clue how to implement this right now.
This actually is pretty easy to do within SSIS. Taking your situation, I have 3 dataflows named A, B and C. ![A B C Dataflows]( You can change whether it is on Success, Failure or Completion by right clicking on the lines and setting that value ![Right Click]( I believe this gets you what you are looking for, at least for the scenario you have presented here.
stackexchange-dba
{ "answer_score": 3, "question_score": 0, "tags": "sql server, ssis" }
How can I scaffold with multiple schemas and particular table? I have two schemas Bob and Bill. I want to scaffold with schema Bob all tables and with schema Bill only View_Otf table. If I use the following code, I get an empty DbContext: dotnet ef dbcontext scaffold "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=something)(PORT=1533)))(CONNECT_DATA=(SERVICE_NAME=otherthing)));User ID=Bob;Password=anotherthing" Devart.Data.Oracle.Entity.EFCore -o Models -t Bill.View_Otf --schema Bob If I use `--schema Bob --schema Bill` I get all tables from both schemas and I don't need that. How can I get all the tables from schema Bob and the table Bill.View_Otf? Thank you!
You will have to list all tables individually. Or you can try EF Core Power Tools, which has a UI for it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net core, entity framework core, ef database first, devart" }
How to initialize a template object inside a class C++? I want to create a template Node class like this template <class T> class Node { public: Node() { val = T; // Does not work: new T, NULL, 0, "" } // ... private: vector<Node<T> *> children; T val; Node<T> * parent = NULL; } The constructor is supposed to have no initial value as a parameter and no overloads are allowed. I could potentially not do anything in the constructor, but for example for integers, I want this base value to be 0, etc. Essentially, the problem I'm trying to avoid is to eliminate undefined behavior eg such values when using integers (the first one is root with no value set): _-1021203834 1 2 11 12 21 22 1 11 12_
Either you can write Node() : val() {} or Node() : val{} {} Or in the class definition to write T val {};
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c++, class, templates, initialization, default constructor" }
preg_replace removing single/double-character words I have this line $txt=preg_replace('#\s(\S){1,2}\s#',' ',$txt); Which i wanted to remove all the single and double character words (a, no, do etc...). It works, but not perfectly - when i have strings which look like that: xxxxx a b c d e xxxxx then my code leaves something like this (every second word that matches, is ommited) xxxxx b d xxxxx I understand that preg match sees it like " a ", "b", " c ", "d", " e ", so is there any simple way to fix that? I thought about duplicating every whitespace but maybe someone would have a better idea?
Add a repeating non-capturing group around the segments that are repeating, like this: $txt = preg_replace('#(?:\s+\S{1,2})+\s+#',' ',$txt); I also removed the unnecessary capturing group around `\S`, since you don't use or need it, and it won't capture correctly when it's repeated. You can see it working in this demo.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, regex, preg replace" }
SQL Insert invalid column name non-numeric values only I am writing a very basic insert statement. I noticed that the error message "Invalid column name" appears if the VALUE is a character besides a number. The data type is VARCHAR(50) on all three columns. Database: MS SQL 2012 Query: INSERT INTO [test-db].[dbo].[Computer] ([id] ,[name] ,[office]) VALUES (123 ,john ,main) GO ERROR: Msg 207, Level 16, State 1, Line 1 Invalid column name 'john'. Msg 207, Level 16, State 1, Line 1 Invalid column name 'main'.
Change your query to this INSERT INTO [test-db].[dbo].[Computer] ([id] ,[name] ,[office]) VALUES (123 ,'john' ,'main') GO The varchar needs quotes around it to work.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, sql server, sql server 2012, insert" }
How do I compare two objects in Perl without coercing them to the same type? In Perl, I know of three ways to test objects for equality: `==`, `eq`, and `~~`. All of these tell me that `1` is equal to `"1"` in Perl 5. However, `1` and `"1"` are not the same thing. How can I compare two objects so that `1` equals `1`, `"1"` equals `"1"`, `1` does not equal `"1"` or `2`, and `"1"` does not equal `"01"`? Answers for both Perls would be appreciated.
Don't. In Perl, _one_ is _one_. Polymorphism based on a value's type is bound to fail. That's why Perl has two comparison operators, and that's why `~~` is broken[1]. For example, the scalar returned by `!0` contains three values, _one_ stored as an integer, _one_ stored as a floating point number, and _one_ stored as a string. For example, an object of class `package Foo; use overload '0+' => sub { 1 }, fallback => 1;` might not contain _one_ at all, but it's considered to be _one_ in numerical and string contexts. * * * 1. That's why it's still flagged as experimental.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 4, "tags": "perl" }
Scientific name of square root of negative number How do you call a number in the form: $\sqrt{-4}$ ? A non real number?
It is $$1)\,\,\text{complex,}$$ (all reals like $2$, $-\pi$ and $\sqrt5+1$ are complex) $$2)\,\,\text{non-real}$$ (which is, probably, what are you interested in) and $$3)\,\,\text{purely imaginary}$$ (which, you may say, is a coincidence: although all square roots of negative reals _are_ purely imaginary, complex numbers include both real and purely imaginary numbers, _but_ there are also infinitely many other complex numbers which are non-real and non-purely imaginary). If this does not address your issue or you expect further clarification, please communicate via the comments section.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "algebra precalculus, terminology, radicals" }
Conversion string to double is not valid following code gives error conversion from string to doble is not valid Dim TaxRebate = CDbl(ComboBox1.SelectedItem) * 0.01 * CDbl(Premium) help in to this is appreciated Sunilsb
'Dim TaxRebate = CDbl(ComboBox1.SelectedItem) * 0.01 * CDbl(Premium) Dim value1 As String Dim number1 As Double Dim value2 As String Dim number2 As Double Dim TaxRebate As Double value1 = ComboBox1.SelectedItem.ToString() value2 = Premium.ToString() If False = Double.TryParse(value1, number1) then Console.WriteLine("{0} is outside the range of a Double.", value1) ElseIf False = Double.TryParse(value2, number2) Then Console.WriteLine("{0} is outside the range of a Double.", value2) Else TaxRebate = 0.01 * number1 * number2 End If
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vb.net" }
PHPexcel: Combine two variables into one cell I'm trying to create an excel sheet with data from a mysql database. At some point I want to combine two variables into one cell. **EXAMPLE:** $customer = $row["city"].' '.$row["name"]; // Doesn't work $rowNumber = 2; while ($row = mysql_fetch_assoc($result)) { $col = 'A'; $sheet->setCellValueExplicit('A'.$rowNumber, $row['routenr']); $sheet->setCellValueExplicit('C'.$rowNumber, $date); $sheet->setCellValueExplicit('D'.$rowNumber, $customer); $rowNumber++; } Any ideas?
Your example won't work because you're concatenating `$row["city"]` and `$row["name"]` **before** you've retrieved $row from the database result set. Nothing to do with PHPExcel, just basic PHP. Move your concatenation **inside** the while loop so that `$row["city"]` and `$row["name"]` will be populated with actual values from the retrieved row $rowNumber = 2; while ($row = mysql_fetch_assoc($result)) { $customer = $row["city"].' '.$row["name"]; $sheet->setCellValueExplicit('A'.$rowNumber, $row['routenr']); $sheet->setCellValueExplicit('C'.$rowNumber, $date); $sheet->setCellValueExplicit('D'.$rowNumber, $customer); $rowNumber++; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql, phpexcel" }