INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to split XML path into an array in GAS
Searching a good way to split an XML path into an array. I have the feeling my solution is not as reliable as i want.
What I have: `<product><containeditem><productidentifier>`
What I want to get is an array like: `[product, containeditem, productidentifier]`
My Code:
function GetPathArray(path) {
if (path != null) {
path = path.substring(0, path.length - 1);
path = path.substring(1);
var pathArray = [{}];
pathArray = path.split("><");
return pathArray;
}
else {
return null;
}
}
|
To ensure you return an array, not a string, you can use this for the simple case in your question:
var path = '<product><containeditem><productidentifier>';
console.log( getPathArray(path) );
function getPathArray(path){
return path.slice(1, -1).split('><');
}
The `slice` function discards the first and last characters (the opening and closing `<` and `>`).
Then the `split` is all you need - as that returns an array.
For more complex strings, this will almost certainly not be sufficient.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "xml, google apps script"
}
|
Injective endomorphism of fields
Let $F$ be a field. If $\phi:F\rightarrow F$ is an injective endormorphism, can we conclude that $\phi$ is an automorphism?
Since $\phi$ is injective, we have $F\cong \phi(F)$. This implies that $\phi$ is surjective.
In many reference books, $F$ is assumed to be finite. But the above proof also holds when $F$ is infinite. Can anyone point out the mistake I made?
|
Namely, consider the map $\Phi:\Bbb Q(X)\to\Bbb Q(X)$, $\Phi(f)=f(X^2)$.
"$\phi(F)\cong F$ implies that $\phi$ is surjective" is the mistake.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 1,
"tags": "abstract algebra, field theory, finite fields"
}
|
"Member for" display calculation
I noticed that I recently rolled over to "12 months" on my user profile on Stack Overflow and noticed that I also did not get awarded the yearling badge. I have since figured out that it appears that you need to have "1 year" on your profile before getting said badge. As such, I'm wondering exactly how the "Member for" fields are being calculated, does anyone have any ideas?
|
My guess is that it's doing `datediff(month, join_date, getdate())`, which rounds up in SQL Server.
In this case, you joined 8/13/08. You're two days away from the actual year mark.
datediff(month, '8/13/08', '8/11/09')
Returns 12 in SQL Server, hence, the months in your profile.
|
stackexchange-meta
|
{
"answer_score": 5,
"question_score": 3,
"tags": "discussion, stack exchange, algorithm"
}
|
Represent the English statement into Quantifiers
Here is a statement
`C(x): x has a cat D(x): x has a dog F(x): x has a Ferret`
represent using quantifiers and logical connectives. Under the domain "all students in your class"
1) No student in your class has a cat, a dog or a ferret.
2) For each of the three animals, there is a student in your class who has one of these animals as a pet.
Can someone provide an answer for this. Thanks in advance.
|
1) ∀x (~C(x) ^ ~D(x) ^ ~F(x))
2) (∃xC(x)) ^ (∃xD(x)) ^ (∃xF(x))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "predicate, quantifiers"
}
|
How to merge array of keys and arrays of values into an object?
I have the following arrays:
var a = ["F", "M"];
var b = ["female", "male"];
var c = ["fa-female", "fa-male"];
and I am able to assign `b` to `a` using for loop with:
ans[a[i]] = values[i]; // { M: "male", F: "female" }
how would I go about adding the third array and assign it to `a` as well?
{ M: {"male", "fa-male"}, F: {"female", "fa-female"} }
or something similar?
**EDIT:** Result could either be an array or an object.
|
use this one.
var a = ["F", "M"];
var b = ["female", "male"];
var c = ["fa-female", "fa-male"];
var resultArray = [];
for(var i = 0; i < a.length; i++) {
resultArray [a[i]] = [b[i], c[i]];
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, arrays, javascript objects"
}
|
Extract VAT identification number with Python
I am trying to extract the German VAT number (Umsatzsteuer-Identifikationsnummer) from a text.
string = "I want to get this DE813992525 number."
I know, that the correct regex for this problem is `(?xi)^( (DE)?[0-9]{9}|)$`. It works great according to my demo.
What I tried is:
string = "I want to get this DE813992525 number.
match = re.compile(r'(?xi)^( (DE)?[0-9]{9}|)$')
print(match.findall(string))
>>>>>> []
What I would like to get is:
print(match.findall(string))
>>>>> DE813992525
|
When searching within a string, dont use `^` and `$`:
import re
string = """I want to get this DE813992525 number.
I want to get this DE813992526 number.
"""
match = re.compile(r'DE[0-9]{9}')
print(match.findall(string))
Out:
['DE813992525', 'DE813992526']
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "python, regex"
}
|
Adding libraries to MonoDevelop C++ projects
How can I add `-lX11`, -`lopenal` and `-lalut` libraries to a C++ Project created in MonoDevelop IDE in linux?
|
The Code Generation tab of the Code Generation section of the project options has the option to manually add custom/extra compiler options and linker options.
Also you can add libraries via the Libraries tab (example below is from a ncurses project):
Project Options : Code Generation : Libraries tab:
 {
'use strict';
angular.module("app.my.component", [])
.component("myCard", {
templateUrl: "app/views/my.card.template.html",
bindings: {
},
controller: ComponentController
});
ComponentController.$inject = ['fetchComponentService','SweetAlert'];
function ComponentController(fetchComponentService,SweetAlert) {
var vm = this;
|
Find the issue, I didn't require it on navigate from parent that calling it :
require: ['oitozero.ngSweetAlert'],
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angularjs, sweetalert, angular components"
}
|
Beppo Levi's theorem, is this assertion correct?
My notes report the following assertion for the theorem:
**Beppo Levi's Theorem:** Let $E$ be a measurable set and $\\{ f_n(x)\\}$ a sequence of integrable functions on E, such that $\lim\limits_{n\to\infty} f_n(x) = f(x)$ (pointwise convergence) almost everywhere on E, and $f_n(x)\leq f(x)$. Then $f(x)$ is integrable on E and $\lim\limits_{n\to\infty} \int\limits_E f_n(x) = \int\limits_E f(x)$
Is this correct? Cause my book reports multiple versions of the theorem, but not this one.
|
**First this theorem is wrong**
Consider $E = \mathbb R$, $f=0$ and $f_n = -\chi_{[n,n+1]}$. Where $\chi_{[n,n+1]}$ is the indicator function of the interval $[n,n+1]$.
They satisfy the hypothesis, but the conclusion doesn't hold as
$$ -1 = \int_{\mathbb R} f_n \neq \int_{\mathbb R} f = 0$$ while $(f_n)$ converges pointwise to the always vanishing function $f$.
**Second this would more related to dominated convergence theorem**
See Dominated convergence theorem if the hypothesis would be correctly set.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "lebesgue integral"
}
|
Uncle or Aunt without sibling fact
I'm wondering how would I be able to call a nephew or niece in a family tree without using a `sibling` fact for prolog. I can't figure out a way to do it by calling the uncle directly.
For example:
parent(elli, lisa).
parent(kelly, lisa).
parent(ben, claire).
parent(lisa, claire).
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
Since ellie or kelly is ben's niece, I have the rule that when called by `grandparent(X, claire).` will give elli and kelly as the grandchild of `claire`. How would I make a rule to be able to call `niece(ben, X).` so it'll list all of ben's niece. I can't figure out a way to do it with only the parent fact, the only way of doing it would be to include a sibling fact but is there a way to do it without making a sibling fact?
I'm very new to prolog, literally like a week ago so please excuse me if I don't understand it that well.
|
brother(X, Y) :- male(X), parent(X, Z), parent(Y, Z), X \= Y.
uncle(X, Y) :- brother(X, Z), parent(Y, Z).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "prolog"
}
|
How to pass Multiple Class Object in $http Request
My requirement is to pass multiple class object(which is going to map with request param or request body in rest controller) in angular $http service.
I can't pass class object in request body since one http call has only one request body.
When i'm trying to pass class object in $http param I'm getting class cast exception.
is there any way to pass multiple object in single $http call ??
@RequestMapping(value = "CommitObject", method = RequestMethod.POST)
public void Commit(@RequestParam(value = "clazz") final String clazz,
@RequestParam(value = "Id") final String modelId,@RequestBody LinkedHashMap<String, Object> obj) {
mService.Commit(Id,clazz workingmodelObj);
}
|
I tried it many times but always failed.So to overcome this I use to create a Java Bean and encapsulate both objects into it at then accepting it in `@RequestBody`.
Your Wrapper should look like this:
public class SampleWrapper {
private Object1 object1;
private Object2 object2;
//getters setters and constructors go here
}
And your constructor should look like this:
@RequestMapping(value = "/url",method= RequestMethod.POST)
public String getRequest(@RequestBody SampleWrapper wrapper) {
Object1 o1 = wrapper.getObject1();
Object2 o2 = wrapper.getObject2();
}
JSON request should look like this:
{
"object1" : {//object1 body },
"object2" : {//object2 body }
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -2,
"tags": "javascript, java, angularjs, http, spring mvc"
}
|
approach to build the functionality to add new employee
I am newbie to intuit Platform APIs.
I started playing with the sample application and I am able to get the customer from the quickbooks online using REST apis.
My goal is : to create new employee with details for any customer using REST apis.
if anyone can just give me rough idea of how to go about it that will be helpful.
|
You can't create new employee object using QB REST APIs( It is not supported in V2 and this entity is not release yet in V3)
**V2** <
**V3** <
Thanks
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "intuit partner platform, intuit"
}
|
Why are words sometimes broken into syllables when said?
This occurrence appears to happen when the speaker is trying to sound cute, or is possibly under the influence of something... They break one of the words into syllables or characters, with pauses in between where they broke up the word.
For an archetypal example:
> ****
> "Do you want dinner? Or do you want a bath? Or do you want _me_?"
Or, when one character confesses their love to another, you might hear _da-i-su-ki_ "I-love-you".
|
Japanese is not as tonal of a language) as English with its rhythmic iambic pentameter (English is said to be "a stress-timed language") or Chinese (Japanese does have some tones, such as _kami_ [paper] vs. _kami_ [god] vs. _kami_ [hair] or _hashi_ [bridge] and _hashi_ [chopsticks]). In English, emphasis is often accomplished by changing the tonal stress of the sentence. For example, "What are you [doing NOW]{LLLLLLHHH}?" or "[What are YOU doing now?!]{LLLLLLLLLHHHLLLLLLLLLLL}" or "[What ARE you doing now?!]{LLLLLHHHLLLLLLLLLLLLLLLL}" or "[WHAT ]{HHHHL} are you doing now?!" Because Japanese does not default to this, enunciating syllables with pauses is an alternate way to create emphasis in a sentence.
|
stackexchange-japanese
|
{
"answer_score": 4,
"question_score": 1,
"tags": "spoken language, anime"
}
|
UIAccessibility.convertToScreenCoordinates() always return a CGRect(0,0,0,0)
I am trying to increase the hit target of a button within a custom UIView() that is a subview of another parentview. I use convertToScreenCoordinates() to try and achieve this. An example is below
let rect2 = CGRect(x: 25, y: 21, width: 200, height: 44)
let newRect = UIAccessibility.convertToScreenCoordinates(rect2, in: self)
where self is the custom UIView()
debugging, i see that newRect = CGRect(0,0,0,0)
therefore
button.accessibilityFrame = newRect // Does not work as intended as VoiceOver frame is now size 0,0 and origin 0,0
|
I was having the same problem. Turns out that I was setting up the `accessibilityFrame` property before the view was positioned. I fix it by changing this code to the `layoutSubviews` method of my custom view.
override func layoutSubviews() {
super.layoutSubviews()
let rect2 = CGRect(x: 25, y: 21, width: 200, height: 44)
let newRect = UIAccessibility.convertToScreenCoordinates(rect2, in: self)
button.accessibilityFrame = newRect
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ios, swift, uiaccessibility"
}
|
Capture TCP traffic from a known process when it starts
I need to capture the TCP communications that a process makes. However, I cannot just run the process, go look up its PID, and then capture. I need to get the communications that occur an instant after it starts.
It is evidently making a JSON request, over an unknown port (not 80), to another process, that registers its URL for REST calls. I have to mimick its before and thus, I need to see it.
Is there a way to capture network communications over a particular interface without knowing the port and from the time the process starts onward?
|
You can use tcpdump command in order to capture the traffic from/to your machine. The size of the packets, port, interface, protocol and lots of parameters are covered by that. for example: sudo tcpdump -i eth0 src/dst xxx.xxx.xxx.xxx port x
for more detail, please check the tcpdump manual page. Note, be careful about printing the output to the file, because the result of the packet capturing command will be huge.
BR,
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, sniffing"
}
|
df command show no output
I'm running the linux distro on my server.When i want to verify the size of the disk, i'm issuing this commnand to get the output.
df -h
But it does not produce ANY output.Strangely enough when i'm issuing other command such as fdisk -l or du -h it can show output normally.
Does anyone now why is this happening?Thanks.
edit:
here is the output of cat /etc/fstab
none /dev/pts devpts rw 0 0
and this is for mount command
none on /dev/pts type devpts (rw)
none on /proc/sys/fs/binfmt_misc tpe binfmt_misc (rw)
edit(2):
here is the output of cat /proc/mounts
/dev/vzfs / vzfs rw,relatime,usrquota,grpquota 0 0
proc /proc proc rw,relatime 0 0
sysfs /sys sysfs rw,relatime 0 0
none /dev/tmpfs rw,relatime 0 0
none /dev/pts devpts rw,relatime 0 0
none /proc/sys/fs/binfmt_misc binfmt_msc rw,relatime 0 0
|
How about this:
$ \df
`\` to ignore `df` alias.
* * *
**UPDATE**
> here is the output of cat /proc/mounts
>
>
> /dev/vzfs / vzfs rw,relatime,usrquota,grpquota 0 0
>
`/dev/vzfs` \--> looks like you're running OpenVZ (check by using virt-what). And if so, root filesystem is mounted by the host system, not the guest, therefore, there is no `/` in the `/etc/mtab` and `df` shows nothing. To fix, link `/etc/mtab` to `/proc/mounts`:
rm -f /etc/mtab
ln -s /proc/mounts /etc/mtab
Source: <
|
stackexchange-serverfault
|
{
"answer_score": 4,
"question_score": 0,
"tags": "linux, centos, df"
}
|
Deployd keeps returning Status 204
I'm developing an iOS application and using Deployd as backend .The problem is when I send a GET request to users/me with a sid cookie to identify my session, It returns 204-no content, even though user is logged-in. I'm expecting some data in return.
Xcode console output:
<NSHTTPURLResponse: 0x136ed2e00> { URL: } { status code: 204, headers {
"Cache-Control" = "no-cache, no-store, must-revalidate";
Connection = "keep-alive";
Date = "Sat, 16 Jan 2016 18:55:16 GMT";
Expires = 0;
Pragma = "no-cache"; } }
|
So I was sending SID as parameter, It was incorrect. Deployd demands a 'barrier token'.
Swift code:
let url = NSURL(string: "http:/xxxxxxxxxxxxxxxx.com:2403/users/me")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
request.setValue( "Bearer \(token!)", forHTTPHeaderField: "Authorization")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()!) { response, maybeData, error in
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
print(contents!, "bitch")
} else {
print(error!.localizedDescription)
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ios, swift, deployd"
}
|
Max length of varchar / text in cassandra
I am trying to find the answer to a simple question. Let say I have a table which I store content in it. The content is just a string. I am trying to find what is my max length for this specific one? I was reading that "text" type is just an alias to varchar. Is varchar length only 255 or it can be more?
|
You can use TEXT column in your database ( about 64KB characters).
As you know String in java has 2^31-1 characters
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 4,
"tags": "java, cassandra, cassandra 2.0, spring data cassandra"
}
|
how to use onselectedindexchanged in asp.net (how to enable or disable text box based on dropdown selection)
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">management</asp:ListItem>
<asp:ListItem Value="2">cet</asp:ListItem>
<asp:ListItem Value="3">comedk</asp:ListItem>
</asp:DropDownList>
</div>
On SELECTING "management" option "rank text box should be disabled else it should be enabled.
|
**Use below code:**
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="SelectedIndexChanged" AutoPostBack="True" >
<asp:ListItem Value="1">management</asp:ListItem>
<asp:ListItem Value="2">cet</asp:ListItem>
<asp:ListItem Value="3">comedk</asp:ListItem>
</asp:DropDownList>
protected void SelectedIndexChanged(object sender, EventArgs e)
{
if(DropDownList1.SelectedItem.Value == "1")
{
//DISABLE TEXT BOX
}
else
{
//ENABLE TEXT BOX
}
}
Do let me know if you have any issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net"
}
|
Qt Should I derive from QDataStream?
I'm currently using QDataStream to serialize my classes. I have quite a few number of my own classes that I serialize often. Should I derive QDataStream to create my own DataStream class? Or is there a better pattern than this? Note that these custom classes are used by many of our projects, so maybe doing so will make coding easier.
Another way to phrase this question is: when a framework provides you with a serialization class, how do you handle serializing your own custom-type classes such that you don't have to remember how to serialize them everytime (enhance usability) and also following best software-engineering practices (following patterns).
|
That would get out of control very quickly. A better approach is to define `operator<<` and `operator>>` between `QDataStream` and your class. Even cleaner might be to simply have serialization methods on your classes that read/write to a `QDataStream` (so that you would call for example, `obj->serialize(myStream)`).
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++, qt, code reuse"
}
|
NetworkManager not populating resolv.conf
I recently upgraded from `11.10` to `12.04`, and now `NetworkManager` isn't populating `/etc/resolv.conf` when connecting to wireless networks, when it had been working perfectly in `11.10`. I'm not seeing any explicit errors in either the `NetworkManager`, `UI` or in `syslog`. How do I diagnose what's wrong?
**Edit:** If I try to run `resolvconf`, I get the error
> resolvconf: Error: /etc/resolv.conf isn't a symlink, not doing anything.
What should it be, a `symlink` to and/or how do I get `NetworkManager` to populate it? This says the `symlink` should point to `/run/resolvconf/resolv.conf`, but that file does not exist on my system.
|
Use following command and answer YES to enable dynamic updates:
sudo dpkg-reconfigure resolvconf
Worked for me on Ubuntu 12.04.
|
stackexchange-askubuntu
|
{
"answer_score": 72,
"question_score": 43,
"tags": "network manager, dns, resolv.conf"
}
|
What is the best way to avoid SpamCop trigger a ASP.NET web page?
Good Days,
I have recently developed a web application in ASP.NET for a marketer that he has been sending emails to his potential customers to fill out a web form existing in this ASP.NET application.
Recently, he received an email from his hosting company saying that they will suspend his account because his emails were triggered by SpamCop. He basically put a link to that web form in the email messages.
What would be the best way to handle this situation? Is there a way to avoid this?
Thanks,
Niyazi
|
The best way to avoid being labeled as a spammer is to **not send spam emails**. Emailing random people and asking them to visit your website and fill out a form is spam, plain and simple.
I would suggest finding a less evil way of getting hits on a website like a Google Adwords campaign.
Also, for your convenience, I have included the first link in my google search of `"How to drive traffic to your website."`
<
Please pay attention to #3
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "hosting, spam, suspend"
}
|
Making a textbox control uneditable without disabling it?
Is it possible to take a textbox item and make it un-editable while still having it enabled for use?
Textbox1.Enabled = false;
This works for all purposes I need EXCEPT that I can't read data from it because it's disabled. If this is not possible I can find alternate solutions. Making it invisible is also not an option.
|
You can use **TextBox.ReadOnly**
Textbox1.ReadOnly = false;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "asp.net, html"
}
|
How change the default separator of opencsv?
First of all, hello and sorry for the beginner question but I already saw the documentation and tutorials but I can't make it work on my code. Maybe I'm making a little mistake but I can't catch it.
_I'm using the latest version of opencsv in a maven project._ So I need to make a .csv file and for that I use:
try (CSVWriter writer = new CSVWriter(new FileWriter("file.csv", true)) {
/* code
}
And everything works fine, but I need to use a diferent separator, so I try with:
try (CSVWriter writer = new CSVWriter(new FileWriter("file.csv", true), '-') {
/* code
}
But appears **Cannot resolve constructor 'CSVWriter(java.io.FileWriter, char)'** in IntelliJ, when in the documentation says opencsv documentation
Any idea on how fix it? (Sorry for my english, I'm not native speaker).
|
According to the documentation, the constructor is either just the file or 5 parameters, so you cannot have just 2: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "java, opencsv"
}
|
Xpath - selection based on multiple criteria
I have the following XML File:
<persons>
<person name="shawn">
<age>34</age>
<hair style="spikes">red</hair>
</person>
<person name="mike">
<age>36</age>
<hair style="bald">red</hair>
</person>
<person name="shawn">
<age>38</age>
<hair style="bald">red</hair>
</person>
</persons>
Using XPath in C#, is it possible to select the person element where the name is "Shawn", and the hair style = "bald"?
I tried using:
XElement.XPathSelectElement("//person[@name='shawn'] | //person/hair[@style='bald']
but that gives me a reference to the hair element, and not the person element.
Thanks in advance :)
Peter
|
If you want someone who is both called shawn and is bald (which your question title suggests), you want:
//person[@name='shawn' and hair/@style='bald']
If you want people who are either called shawn or are bald (which it looks like you may do from the attempt in your question), you want:
//person[@name='shawn' or hair/@style='bald']
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 4,
"tags": "c#, xpath"
}
|
javascript get substring between two sets of characters
I have the following string:
var myString = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>';
how can i get with the least code the **someExtraStuff.fileExt** section?
should i do indexOf `{{appName}}` and then until the next **`"/>`** ?
|
You could search for the pattern `{{appName}}` and take all characters who are not quotes. Then take the second element of the match.
var string = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>',
substring = (string.match(/\{\{appName\}\}([^"]+)/) || [])[1]
console.log(substring);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "javascript, string, substring"
}
|
"TypeError: can only concatenate tuple (not "float") to tuple"
I am writing a program to open and read a txt file and go through loops each line. multiply values in 2nd column and 4th column and assign it to 5th column.
A 500.00 A 84.15 ?
B 648.80 B 77.61 ?
C 342.23 B 39.00 ?
this is part of codes I wrote,
for line in infile:
a,b,c,d = line.split()
e = eval(b) + eval(d)
print("{0:20}${1:20}{2:20}${3:20}{4:20}".format(a,b,c,d,e),file=outfile)
I kept getting an error saying,
> File "C:/Users/hee lim/Desktop/readfile2.py", line 19, in main e = eval(b) + eval(d) TypeError: can only concatenate tuple (not "float") to tuple
I covert strings into numbers using "eval" to multiply those numbers. I don't understand why it flags an error.
thank you for your help.
|
Looking at this information, I could only tell that the value returned by `eval` of `b` and `d` are of `float` and `tuple` type. And you can not do `+` on `float` and `tuple`. For example:
>>> 5.0 + (2 ,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'
For debugging, add `print line` at the start of `for` loop to see at what value it is raising error.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "python"
}
|
Combine PostgreSQL query log
I set PostgreSQL's `log_statement` setting to `all` for full query logging in the `data/postgresql.conf` file. While I like that the logs can be split in to separate days how can I combine all the queries being logged in to a single file called `queries.log`?
|
I found the prefix on the existing log files in the configuration and was able to come up with the following...
log_filename = 'queries.log'
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "postgresql"
}
|
Check / Compare NSError Code in CloudKit?
I guess it is basic, but still .. how can I check whether I get a `ZoneBusy` error?
if error.code == CKErrorCode.ZoneBusy { // <- compiler says can't use '==', then what?
!enter image description here
Reference:
<
|
It appears that you are missing `.rawValue`.
So it should be:
`CKErrorCode.ZoneBusy.rawValue`
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "ios, swift, swift2, cloudkit, nserror"
}
|
Radwindow on dropdown selected indexchange
I am trying to get a pop-up window(Rad Window) with a text box and button, when a user selects a particular item in the telerik radcombobox.
Please suggest some tips/telerik samples if anyone came across this requirement.
Thanks
|
Ok figured out finally,we get radwindow on ddl selection as below
if (ddl.SelectedValue.ToString() == "n/a")
{
string script = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "asp.net, telerik, popup"
}
|
Requirejs Handlebar plugin empty lines
I do not know if this is specific to the requirejs handlebar plugin but when I have a template like :
<h1>abc</h1>
{{#if testcondition1}}
<h1>def</h1>
{{/if}}
{{#if testcondition2}}
<h1>ghi</h1>
{{/if}}
<h1>xyz</h1>
I get a empty line if one condition is false. so like:
<h1>abc</h1>
<h1>ghi</h1>
<h1>xyz</h1>
and not
<h1>abc</h1>
<h1>ghi</h1>
<h1>xyz</h1>
Is this the expected behavior? I'd like to get no lines without recurring to string manipulation after the template compilation. I know that lines get ignored in html but this can be really annoying especially in loops.
|
If you look at the newline placements in your code:
<h1>abc</h1>\n
{{#if testcondition1}}\n
<h1>def</h1>\n
{{/if}}\n
{{#if testcondition2}}\n
<h1>ghi</h1>\n
{{/if}}\n
<h1>xyz</h1>\n
You can see that if the first condition is false, the code without the skipped branch is:
<h1>abc</h1>\n
\n
{{#if testcondition2}}\n
<h1>ghi</h1>\n
{{/if}}\n
<h1>xyz</h1>\n
which gives you two newlines in a row.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, requirejs, handlebars.js"
}
|
Magento2 handling of downloadable product filetypes
If I offer downloadable products on Magento2, some of them are corrupted after download, I cannot open them. It sais things like "this zip
Working fine: PDF, EPUB
Corrupted file after download: ZIP, MOBI.
I have not tried other filetypes. Any idea how to fix that?
Magento 2.3.5-p1, PHP7.3 on Ubuntu 20.04
|
Solution found: I had empty lines in the beginning of my `registration.php` of my custom theme before the start of the opening `<?php` tag.
Outch.
|
stackexchange-magento
|
{
"answer_score": 0,
"question_score": 1,
"tags": "magento2, downloadable"
}
|
How to Get Netrw to exclude certain files?
I have vim save my undo history in files named something like `.filename.js.un~`, but I don't want this cluttering up my list of file in vim (in Netrw).
Is there a way to exclude all files with a certain file extension in Netrw?
|
For your case,
let g:netrw_list_hide='.*\.un\~$'
will do the trick. See
:help /~
for why the extra backslash preceding the tilde is needed.
|
stackexchange-vi
|
{
"answer_score": 4,
"question_score": 4,
"tags": "netrw"
}
|
SQL Server - @@connections value increasing automatically?
I just started learning SQL Server v2014, about the global variables.
select @@CONNECTIONS conns, @@MAX_CONNECTIONS mx_conns;
With every execution of this query, the value of @@CONNECTIONS is changing. As per the documentation.aspx), it says attempted successful/unsuccessful attempts. But, since it is a local installation, nobody else is trying to access it. How is the value changing?
Response much appreciated.
Regards, Ranit
|
If you actually want to see what is triggering the increase here, set up a SQL Server Profiler trace on your local SQL instance to log everything. Let it run for a few minutes, then shut it off and look at the results.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql server, global variables, connection"
}
|
My particles are vanishing after 250 frames, not sure whats going on. (Lifetime is set to 350)
Not sure whats going on with my particles here, they are vanishing after 250 frames : !enter image description here
My particle settings: !enter image description here
Sadly google search results are a bit tough to filter through for anything blender. Hopefully one of you know what the deal is.
|
Did you modify any of the settings for the second time? Like did first you set lifetime to 250 and later to 350? It that's the case, you should set current frame to 0 and replay it with `Alt``A`
Another possibility is the clipping: set the End value of clipping to a higher value or start value to a lower value (you can tab the panel with shortcut `N`
|
stackexchange-blender
|
{
"answer_score": 3,
"question_score": 3,
"tags": "particles"
}
|
Subset a data frame based on values of another column in data frame
It is possible to take one column of numeric values like in `dup$Number` and subset columns in DG that match `dup$number` and return this as a new data frame?
dup
Number Letter
59 Q
91 Q
19 Q
17 Q
DG
chr pos id ref alt refc altc qual cov line_21 line_26 line_28 line_31 line_32 line_38 line_40 line_41 line_42 line_45 line_48 line_49 line_57 line_59 line_69 line_73 line_75 line_83
1 2R 7006506 2R_7006506_SNP C A 169 26 999 29 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 2 -
|
Try
indx <- grep('line', names(DG))
DG[indx[as.numeric(sub('.*_', '', names(DG)[indx])) %in% dup$Number]]
# line_59
#1 0
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "r, dataframe, subset"
}
|
Rails inserting javascript as a flash notice or message?
I'm wondering if this is a good idea or not, either way I'd like you guys opinion on how to best achieve this sort of messaging popup system I have in my app.
Under some occasions I want to popup a lightbox for users when certain actions are triggered. I already have the lightbox working and opening when when my controller returns JS for a request.
Here is the senario, I want to check if a user has new `messages` when a new request is made, and if they do I want to show the messages in my lightbox when the new page is loaded.
Should I just put some JS at the bottom of my `<body>` and render it if the user has `messages`? Or should I use like `flash[:notice]` and have it render as JS or something... I'm a bit stuck you see.
|
Don't use flash notices, this is not what they are for at all. I would have something in the layout like this:
<% if (messages = current_user.new_messages).size > 0 %>
<%= javascript_tag "display_messages(#{messages.collect(&:message_text).inspect})" %>
<% end %>
obviously here i'm guessing at your messages' methods but you get the idea. .inspect will give it an array of strings, you could give it the message data as a json object or whatever.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails"
}
|
How should I explain to a “normal” person about gmail labels?
As a computer programmer I have no problem understanding labels/tags.
However I find it very hard to make people understand that an email can have more than one label.
Also I find it hard to explain that you can still get to an email if it is not in your inbox and does not have a label.
(Moving a email to a folder seem to be how most people think)
Is gmail just designed by computer programmers for computer programmers? (Hence why I like it so match)
|
Just tell them that every e-mail is like a movie. The same movie can belong to more than one categories/genres like `comedy`, `action`, `adventure`, etc..
|
stackexchange-webapps
|
{
"answer_score": 14,
"question_score": 8,
"tags": "gmail, gmail labels"
}
|
Classification of VDD and VSS pins
I am creating a library component for KiCAD using a convenient online app at: < The component I am making is the Microchip PIC24EP512GU814 in LQFP <
The app asks me to assign a type to each pin. The types avilable are:
Input
Output
Bidir
Tri-state
Passive
Unspecified
Power Input
Power Output
Open Collector
Open Emitter
I must now assign one of these types to the `VDD` and `VSS` pins.
My best guess is that `VDD` should be assigned as `Power Input`. Would `VSS` also be considered as a power input?
Perhaps since `VDD` is analogous to `VCC` (and `VSS` to `VEE`), I could classify `VDD` as an `Open Collector` (and `VSS` as `Open Emitter`). However I'm not sure if `VDD` and `VSS` can be considered as "open" for an IC.
What should `VDD` and `VSS` be mapped to?
|
I would recommend using `Power Input` for both `VDD` and `VSS` (or any power pins on an IC for that matter). If you choose to use these types of pin labeling, then it allows you to verify that all power supply pins are connected and that there is a source that can provide power.
If you set `VDD` or `VSS` as a `Power Output` then the software will see it as something that provides power for the circuit. This would also give you an error if you have multiple chips on the same power supply (e.g. two of these chips). The output of a linear regulator would be a good example of a `Power Output`.
Making both `VDD` and `VSS` the same is a bit counter intuitive compared to current flow, but these are being used as system terms, not electrical current/voltage terms.
|
stackexchange-electronics
|
{
"answer_score": 4,
"question_score": 4,
"tags": "microcontroller, power, schematics, kicad"
}
|
Document Management System
Is there any Document Management System in Ubuntu?
I tried Alfresco, RavenDB, Owl, Document Manager.
Alfresco, RavenDB are heavy. More than my requirements. Owl having source issues.
Document Manager im trying to install.
* Should keep data on the same machine as I am looking for more of internal purpose.
* Should allow to upload Zip files as well. If it extracts Zip it will be a great +
* Should allow to send email to preconfigured email addresses
* Should allow to upload data of size around 100MB at one go
* Should maintain history of documents also deleted documents
* Should allow role based document access.
* Should be Free :)
* It should not do any spoofing on data. Documents are confidential.
Please share your knowledge. Thanks.
|
**LogicalDOC** offers both Community(free) and Commercial editions. We used it for some customers and in comparison with Alfresco we can state that LogicalDOC is more easy and lightweight, moreover the support service on the Commercial edition is very fast.
It has a very well documented WebService we used to integrate LogicalDOC with ERP and CRM.
|
stackexchange-askubuntu
|
{
"answer_score": 7,
"question_score": 12,
"tags": "document management"
}
|
Analyze the convergence of the series $\sum_{n=1}^{\infty} \frac{\cos (in)}{2^{n}}$
Analyze the convergence of the series $\sum_{n=1}^{\infty} \frac{\cos (in)}{2^{n}}$.
$a_n=\frac{1}{2^n}, \quad b_n=\cos(in), \quad \lim(a_{n})=0$ but $\lim(b_{n})$ does not exist. So I think the series diverges. How do I prove it formally?
|
Observe that $$ \frac{\cos(in)}{2^n} = \frac{\cosh(n)}{2^{n}} = \frac{e^{-n} + e^{n}}{2^{n+1}}.$$ Now $\frac{e^{-n}}{2^{n+1}} \to 0$ and $\frac{e^{n}}{2^{n+1}}$ does not converge to 0 (you may check that $f(x) = \frac{e^x}{2^{x+1}}$ has positive derivative for every $x>0$) and hence $\frac{\cos(in)}{2^n}$ does not converge to 0 and the series diverges.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sequences and series, complex analysis"
}
|
how to keep selected on selected row in datagridview on formload
I have a datagridview. I want to keep the selected row on form_load. I am using a timer in which the datagridview is refreshing. But there I want the cursor to be on selected row. Any ideas?
|
You can try this:
dataGridView.Rows[index].Selected = true;
Set `index` the index of the row you want to keep selected, then put it on your refresh method.
**UPDATE**
add the `SelectionChanged` event to your `DataGridView` then get the selected row index by `dataGridView.CurrentCell.RowIndex;` property like so:
int selectedRowIndex;
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
selectedRowIndex = dataGridView1.CurrentCell.RowIndex;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, .net"
}
|
most visited document in document library
How to get most visited document in document library ?
|
you should try Item Level Auditing feature which is implemented by Microsoft. OR else you can use SPAudit class.
Here is the link:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sharepoint, sharepoint 2007"
}
|
Defrosting individual frozen fish fillets---- in their plastic packets, or not?
The directions in the packet says to remove the plastic packets first before defrosting. But the packet helps to manage the mess and stops fishy water running all over the place. I defrost them by submerging them in room temp. water.
Is there any danger in defrosting them in their original packet?
|
If you defrost in water, by all means keep the plastic on. If it weren't wrapped, you'd put it in a baggie anyway and not dump it directly into the water.
The instructions to unwrap are for defrosting in the fridge and to allow the water to run off. Fish is often covered in a thin protective layer of ice, which you want to be able to drain instead of staying on for a long time.
For the relatively short time in a defrosting water bath, you will be fine. Just pat the fish dry before frying or you get a lot of spattering.
* * *
From a food-safety perspective you should be using cold water, btw, it works just as well and you can be sure your fish stays out of the danger zone.
|
stackexchange-cooking
|
{
"answer_score": 8,
"question_score": 5,
"tags": "fish, defrosting"
}
|
Using mongo updateZoneKeyRange to reduce a zone range
I'm trying to update an existing zone's range named `hot` from
`{ "id" : 1507520572 }, { "id" : { "$maxKey" : 1 }`
using
`sh.updateZoneKeyRange('db.collection', { id: 1507520572 }, { id: 9999999999 }, 'hot')`,
but I'm getting the error
`Zone range: { id: 1507520572.0 } -->> { id: 9999999999.0 } on hot is overlapping with existing: { id: 1507520572 } -->> { id: MaxKey } on hot`.
My plan is to then create a new zone from `9999999999` to `MaxKey`. How can I achieve this?
|
I had to remove the previous range first with
`db.runCommand({ updateZoneKeyRange: 'db.collection', min: {id: 1507520572}, max: {id: MaxKey}, zone: null })`,
then it let me create the new ranges.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mongodb, sharding"
}
|
count number of highest ratings value
I have a table FixtureStats
Id FixtureId PlayerID Rating other Attributes
1 1 1 8.5
2 1 2 6.8
3 1 3 9.1 << man of the match(Motm)
.....
100 4 1 5.3
101 4 2 7.6 << Motm
102 4 3 4.5
I want to select a list of players and the number of Motm one's achieved.
Eg.
PlayerId Motm
1 0
2 1
3 1
Thanks all.
|
You can use the `ROW_NUMBER()` function for this:
;with cte AS (SELECT *
,CASE WHEN ROW_NUMBER() OVER(PARTITION BY FixtureID ORDER BY Rating DESC) = 1 THEN 1 END AS Motm
FROM FixturStats
)
SELECT PlayerID
,SUM(Motm) AS Motm
FROM cte
GROUP BY PlayerID
Since you only care about the `Motm` I wrapped it in `CASE` so it's either `1` or `NULL`, and can then be aggregated simply. If you wanted to look at how often someone was 2nd place or 3rd, you could remove the `CASE` and aggregate differently.
`ROW_NUMBER()` creates a number for every row in a group determined by `PARTITION BY` and are numbered according to the `ORDER BY`, in this case, you want the top `rating` from each `FixtureID`, so we use those.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "sql, sql server"
}
|
type of Date object
I just read this article on W3Schools about type conversion in JS. There stands:
> There are 3 types of objects:
>
> * Object
> * Date
> * Array
>
This confused me because to my knowledge there isn't any difference between `Date` objects and any other object (`typeof (new Date())` returns `"object"`). First I thought that it's special because it contains native code, but there are dozens of functions with native code.
Is this article wrong? Or could anybody tell my why the `Date` object is so extraordinary that it's considered a separate type of object?
|
Lemme tell you a basic thing. The articles in W3Schools are definitely outdated so you must not rely on it. Yes, when you give this in console:
typeof (new Date())
The above code returns `object` because the JavaScript has only a few primitive types:
) instanceof Date
The above code will return `true`. This is the right way of checking if the particular variable is an instance of a particular type.
`. How would I go about doing this?
>toRound <- c(-2, 3, 4, 1, -1, 0, .5)
>magicFunction(toRound, c(0, 1))
c(0, 1, 1, 1, 0, 0, 1)
>magicFunction(toRound, c(-1, 1))
c(-1, 1, 1, 1, -1, round(runif(1,min=0,max=1), 0), 1)
|
Try
toRound <- c(-2, 3, 4, 1, -1, 0, .5)
ifelse(toRound > 1, 1, ifelse(toRound < 0, 0, round(toRound)))
[1] 0 1 1 1 0 0 0
And as a function:
foo <- function(x, Min, Max) ifelse(x > Max, Max, ifelse(x < Min, Min, round(x)))
foo(toRound, -1, 1)
[1] -1 1 1 1 -1 0 0
Note that on my system a .5 is rounded to the smaller integer. If you want to round up -what your expected output suggest- you can use the solution given in this post Round up from .5 in R
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "r"
}
|
No apps can perform this action Android Intent using Kotlin
I am using the following code snippets from Android official documentation to share content through applications using `Intent` but it says "No apps can perform this action." on a physical device. I have messengers, email client and text message clients installed.
val intent = Intent().apply {
intent.action = Intent.ACTION_SEND
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, "Text to share")
}
startActivity(Intent.createChooser(intent, "Sharing"))
|
This is what I know:
As Fredy Mederos said, the value that you are modified is the `Activity.getIntent`, not the `new Intent`.
You should write like this:
val intent = Intent().apply {
action = Intent.ACTION_SEND
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, "Text to share")
}
or more precise:
val intent = Intent().apply {
this.action = Intent.ACTION_SEND
this.type = "text/plain"
this.putExtra(Intent.EXTRA_TEXT, "Text to share")
}
the `this` is pointed to your initialized `new Intent()`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android intent, kotlin"
}
|
Field Calculator python to Python code
I am trying to convert a python code from field calculator to arcpy (pycharm).
All i am wanting to do is convert the below python code into a way python in pycharm will read it.
!Owner_Ab!.title()
This is my attempt however it does not work.
feature_class = CAD_WA
FukMoO = 'Owner_Ab'
with arcpy.da.UpdateCursor(feature_class, FukMoO) as cursor:
for row in cursor:
row[0] = row[0].title
cursor.updateRow(row)
|
You are not showing all your code but
`row[0].title` should be `row[0].title()`
row = ('does not work',)
print('1:', row[0].title)
print('2:', row[0].title())
1: <built-in method title of str object at 0x7f4ae3465570>
2: Does Not Work
|
stackexchange-gis
|
{
"answer_score": 3,
"question_score": 1,
"tags": "arcpy, arcmap, cursor, pycharm"
}
|
SceneKit – How to show SCN file in the scene view?
I want to show a 3D object in my application so I used SceneKit to do so. As I never used this module before I was facing two issues to show the object:
* When I entered the name of `scn` file in sceneView at the storyboard it shows as it is and I can't make any interactions on it.
* When I use class of SCNScene to type the name as below it shows nothing and ended up with a thread found nil.
Here's a code:
private func setupScene() {
let url = Bundle(for: CarModelVC.self).url(forResource: "art.scnassets/veh",
withExtension: "scn")
scnScene = SCNSceneSource(url: url!)?.scene()
self.scene = scnScene
}
|
Use the following code to get what you want:
import SceneKit
class ViewController: UIViewController {
func setupScene() -> SCNScene? {
guard let url = Bundle(for: CarModelVC.self).url(forResource: "art.scnassets/veh",
withExtension: "scn")
else { return nil }
let scnScene = SCNSceneSource(url: url)?.scene()
return scnScene!
}
override func viewDidLoad() {
super.viewDidLoad()
let sceneView = self.view as! SCNView
sceneView.scene = self.setupScene()
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios, swift, scenekit"
}
|
Two-Dimensional Arrays multiplication in Scala
I can use zip and map method to multiply one-dimensional array.
I want to multiply two-Dimensional Arrays.
I have no idea. If I have two now
val x = Array(Array(1, 2),Array(3, 4),Array(5, 6))
val y = Array(Array(5, 10),Array(10, 15),Array(15, 20))
I wish to get Array(Array(1*5, 2*10), Array(3* 10, 4 * 15)...and so on.
In addition, I would like to get sum of all internal Arrays like: Array(1*5 + 2*10, 3*10 + 4*15 ....)
What is the ideal way to do these in Scala?
|
Longer (more readable?) version:
x.zip(y) map { case (xe, ye) =>
xe.zip(ye).map { case (a, b) => a * b }
}
Oneliner:
x.zip(y) map (_.zipped map (_ * _))
The sum:
x.zip(y) map (_.zipped map (_ * _)) map (_.sum)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "arrays, scala"
}
|
Read in JPG as RGB888 on Android
I'm trying to read in a .jpg using BitmapFactory. I want to get a RGB888 formatted bitmap, but I keep seeming to get RGB565. Is there anyway to change this?
|
BitmapFactory methods let you pass a BitmapFactory.Options instance. You can use BitmapFactory.Options to specifcy the inPreferredConfig, which defines the format of the Bitmap returned after decoding, just set it to Bitmap.Config.ARGB_8888.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "android, bitmap, jpeg"
}
|
Is there an API Explorer for Classic API NVP requests
It seems that the PayPal API Explorer only supports testing SOAP requests. Is there a tool I can use to test Name-Value Pair requests?
|
We have an "unofficial" tool that can be used to test the classic APIs in SOAP or NVP. This site is not supported by PayPal and I strongly advise to only use this with sandbox credentials.
The link is:
<
Regards,
Will
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "paypal"
}
|
stretch mask - bit manipulation
I want to stretch a mask in which every bit represents 4 bits of stretched mask. I am looking for an elegant bit manipulation to stretch using c++ and systemC
**for example:**
input:
mask (32 bits) = 0x0000CF00
output:
stretched mask (128 bits) = 0x00000000 00000000 FF00FFFF 00000000
and just to clarify the example let's look at the the byte C:
0xC = 1100 after stretching: 1111111100000000 = 0xFF00
|
Do this in a elegant form is not easy. The simple mode maybe is create a loop with shift bit
sc_biguint<128> result = 0;
for(int i = 0; i < 32; i++){
if(bit_test(var, i)){
result +=0x0F;
}
result << 4;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "c++, bit manipulation"
}
|
How to do such string manipulations in PHP?
I need to convert
"01,02,03,04,05,07:01"
to:
<b>07</b><b>09</b><b>30</b><b class="color_blue_ball">11</b>
That is ,wrap those before `:` with `<b></b>` ,but those after `:` with `<b class="color_blue_ball"></b>`.If there's no `:`,all should be wrapped with `<b></b>`
Anyone knows how to do this?
|
A tad more verbose:
<?php
function wrapValues($array, $wrapper) {
$result = array();
foreach ($array as $elem) {
$result []= str_replace('?', $elem, $wrapper);
}
return implode('', $result);
}
$values = "01,02,03,04,05,07:01,02";
$firstWrapper = '<b>?</b>';
$secondWrapper = '<b class="color_blue_ball">?</b>';
list($first, $second) = explode(':', $values);
echo wrapValues(explode(',', $first), $firstWrapper) .
wrapValues(explode(',', $second), $secondWrapper);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, regex"
}
|
Empty text template for WPF ComboBox?
How would I apply "an empty text" template for WPF `ComboBox`?
<ComboBox
ItemsSource="{Binding Messages}"
DisplayMemberPath="CroppedMessage"
Name="Messages"
Width="150" Margin="0,4,4,4">
</ComboBox>
I use the above code to display a `ComboBox` with a few messages. Now, when the application starts there's no item chosen by default, and if so, I want to display a custom text on the `ComboBox`. I think I would need some kind of template with a trigger?
|
Try this...
<ComboBox ItemsSource="{Binding Messages}"
DisplayMemberPath="CroppedMessage"
Name="Messages"
Width="150"
Margin="0,4,4,4"
IsEditable="True"
Text="select" />
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, .net, wpf"
}
|
Connecting php with html Code doesn't work
since an Image says more than Word here you go:
!enter image description here
I basically just want the 'IMDB' Label, if there is a Link inside the Article's Metadata otherwise it shouldn't be visible.
<?php $rating = get_post_meta($post->ID, 'Rating', true); ?>
<?php $imdblink = get_post_meta($post->ID, 'IMDb-Link', true); ?>
<?php if($rating==""){ echo ""; if($imdblink=="") {echo "";} } else { ?>
<div style="float: right"><a href=" echo $imdblink; ?>">IMDb <?php echo $rating; ?>/10</a> </div>
|
It could be modelled like this:
$rating = get_post_meta($post->ID, 'Rating', true);
$imdblink = get_post_meta($post->ID, 'IMDb-Link', true);
if (empty($rating) || empty($imdblink)) {
print "";
} else {
?><div style="float:right;"><a href=" print $imdblink; ?>">IMDb <?php print $rating; ?>/10</a></div><?php
}
You just missed a closing brace after the `if($rating == "")` check.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, html, wordpress"
}
|
Use Currently Saved Cookies in Watir Webdriver
Is it possible to use currently saved cookies in Watir Webdriver when launching Chrome?
I set my chrome to "remember me" when login to facebook so that the next time I access facebook, I don't have to type the username and password again. But, when using watir webdriver, the Chrome will open it like new session and accessing facebook like the first time which requires me to type the username and password again. I expected it to directly open facebook without going through the login page again. Is there a way to do that?
Thank you very much.
|
You need to create a custom profile for Chrome, adjust its settings as desired, then direct Watir to use it by setting the Chrome switches.
args = ['--user-data-dir=/path/to/your/custom/profile']
Watir::Browser.new :chrome, options: {args: args}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "ruby, google chrome, selenium, automation, watir"
}
|
Is a partial target file created if an error occurs during AWS S3 copy?
What happens to the target file (i.e. the file being written) if an error occurs _during_ the copy-operation on AWS S3? The API documentation states this;
> You create a copy of your object up to 5 GB in size in a single atomic action using this API
Does that mean that for files < 5 GB in size, no partial target file will be written/visible?
|
Objects will never be in a 'partial' in S3. Either the whole file is available, or none of it is.
If the file is less than 5GB, it can be uploaded with a normal `upload` command. If it works, then it appears. If it fails, then there is no change on S3.
Larger files need Uploading and copying objects using multipart upload - Amazon Simple Storage Service. This uploads the file in 'parts', and each part can be retried. When all parts are uploaded, a final command tells S3 to join the parts into one Object.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "amazon web services, amazon s3"
}
|
Mod Rewrite from Uppercase
I'm trying to rewrite a URL of www.somesite.com/BEARS to www.somesite.com/bears. I'm having an issue in that I don't want all my URLs lowercase right now so I just want to do it on this one.
Also www.somesite.com/bears is actually rewriting to bears.php?page=bears.
I just can't think of a way to do this correctly.
I've tried
RewriteRule ^/BEARS$ /bears [PT]
RewriteRule ^/BEARS$ /bears.php?page=bears
That doesn't work
|
Figured it out here is my solution.
RewriteRule ^BEARS bears.php?page=bears [NC,L]
Apparently the forward slash was throwing me off
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "apache, .htaccess, mod rewrite, url rewriting"
}
|
List Separator script
How can I change the List separator from the command line?
Normally I have to edit a field in: _Control Panel -> Change keyboards or other input methods -> Additional settings_
I would love to create a VBScript that I click which automatically changes from `,` to `;`, and another one that goes back.
|
A single script should suffice. The setting is stored in the registry value `HKCU\ControlPanel\International\sList` and can be toggled with something like this:
Set sh = CreateObject("WScript.Shell")
path = "HKCU\Control Panel\International\sList"
Set separator = CreateObject("Scripting.Dictionary")
separator.Add True , ";"
separator.Add False, ","
sh.RegWrite path, separator(sh.RegRead(path) = ","), "REG_SZ"
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "vbscript, windows 7"
}
|
Pop up Javascript alert when PHP code starts to run and alert when finished execution
I have a php controller that invokes according to a JavaScript click function. I want to pop up a JavaScript alert box when this code starts to run and alert again after finish execution. How to achieve this inside the php controller
example:
<?php
class admin_rentals extends base_admin {
function update_user_verification_status() {
// should pop up the alert box
// executes the code
// alert when execution finished
}
}
?>
|
You cannot do it from your controller. You can do it from your java script if that function is executed by ajax.Something like this
alert('Execution started');
$.ajax({
url : 'path/to/your/function',
type: 'post',
success: function(res){
alert('Execution completed');
}
});
PHP
class admin_rentals extends base_admin {
function update_user_verification_status() {
$arrRet = array('message'=>'This is a json');
echo json_encode($arrRet);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, php, json, codeigniter"
}
|
JSON stringify a Set
How would one JSON.stringify() a Set?
Things that did not work in Chromium 43:
var s = new Set(['foo', 'bar']);
JSON.stringify(s); // -> "{}"
JSON.stringify(s.values()); // -> "{}"
JSON.stringify(s.keys()); // -> "{}"
I would expect to get something similar to that of a serialized array.
JSON.stringify(["foo", "bar"]); // -> "["foo","bar"]"
|
`JSON.stringify` doesn't directly work with sets because the data stored in the set is not stored as properties.
But you can convert the set to an array. Then you will be able to stringify it properly.
Any of the following will do the trick:
JSON.stringify([...s]);
JSON.stringify([...s.keys()]);
JSON.stringify([...s.values()]);
JSON.stringify(Array.from(s));
JSON.stringify(Array.from(s.keys()));
JSON.stringify(Array.from(s.values()));
|
stackexchange-stackoverflow
|
{
"answer_score": 185,
"question_score": 166,
"tags": "javascript, json, ecmascript 6"
}
|
Intellij and local Tomee 7.0.1
I have instance of Tomee 7.0.1 on my local HDD with latest Intellij. When starting server using configuration in Intellij, it randomly connects, most of time it won't. Trying to manuly deploy war:exloped using button in Intellij cause message:
> Artifact xxx:war exploded: Server is not connected. Deploy is not available.
Configuration in Intellij doesn't have anything different that can be found in tutorials, etc.
I spend so much time searching for sollution of this problem, found many possible like: \- `setenv.bat` overwrting env var \- wrong env `JAVA_OPTS` \- missing `JAVA_HOME` and probably others which now I can't remember.
None of this works.
Any thoughts?
|
which version of idea is it? They had a bug when 7.x was released and you needed to customize the properties they passed to the deployer of tomee as well as tomee properties but it has been fixes in recent releases.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "debugging, intellij idea, jmx, apache tomee, tomee 7"
}
|
How to get the even item positions in a list with LINQ
I have a list like this
List<double> points1 = new List<double>
{
10, 20, 30, 40, 50, 60, 70, 80, 90, 100
};
How can I get the even positions with LINQ in order to get a list like this
20,40,60,80,100
I know how to do it with a for loop, but I want this in a single line with LINQ
|
points1.Where((value, idx) => idx % 2 != 0);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, list, linq"
}
|
Selenium: How to locate all the images on a webpage without knowing their id or name attribute?
Let us say, I loaded a URI with selenium. I have no idea how the elements are named in that page (I do not know the id, name ... of elements). I want to download all the possible pictures that may exist on that webpage. This problem is solved through the first answer of this question. But how can I located with selenium all the pictures that exist on that webpage ?
I checked answers for similar questions like this one but the answers are not useful.
|
The easiest way is to find by tag name as all images will have an image tag you can just get every element on that page with that tag. In python i believe it will be using (note note find_element_by_tag_name as that would return just one of the elements)
find_elements_by_tag_name
and you will want to find elements with the img tag <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "selenium, python 3.x, selenium webdriver"
}
|
Merge multiple flv files?
What tool in Linux can I use to merge multiple flv files ? Files are already in order, just put them altogether seamlessly
|
I didn't test the following yet, so see it just as some hints.
You could use `ffmpeg`. From the manual
* You can put many streams of the same type in the output:
ffmpeg -i test1.avi -i test2.avi -vcodec copy -acodec copy -vcodec copy -acodec copy test12.avi -newvideo -newaudio
In addition to the first video and audio streams, the resulting output file
test12.avi will contain the second video and the second audio stream found in the
input streams list.
The "-newvideo", "-newaudio" and "-newsubtitle" options have to be specified
immediately after the name of the output file to which you want to add them.
You can also use `mencoder` for example:
mencoder -forceidx -ovc copy -oac pcm -o output.flv input1.flv input2.flv
Another option is maybe `flvcat`.
You could also try `avidemux-cli`.
|
stackexchange-unix
|
{
"answer_score": 3,
"question_score": 2,
"tags": "command line, video, adobe flash"
}
|
Accessing variables in Case Classes
I have a case class called square and I want to access a variable in it called side. I then want to use pattern matching to detect the object is of type square and return side*side. However when I run the below I get value side is not a member of this object A$A43.this.square
case class square(side:Double)
def getArea(o: Object): Double = {
o match {
case s: square => s.side*s.side
case _ => 0
}
}
Thanks in advance for any advice or assistance.
|
The issue I was having was caused by the fact that I was using a non capitalised case classes. So in order to get the above working you would need to do the following.
case class Square(side:Double)
def getArea(o: Object): Double = {
o match {
case Square(side) => side*side
//would also be valid case matching syntax
//case s: Square => s.side * s.side
case _ => 0
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "scala"
}
|
How to repeat the procedure of a button
I have developed two procedures of two buttons to for task 1 and task 2. Do you know how to create the new button which can repeat the procedures of two previous buttons to perform task 1 + 2 in assigned number of times ?
|
Extract the tasks into separate methods:
procedure TForm1.DoTask1;
begin
....
end;
procedure TForm1.DoTask2;
begin
....
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
DoTask1;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
DoTask2;
end;
And then add a new button with `OnClick` handler like this:
procedure TForm1.Button3Click(Sender: TObject);
var
i: Integer;
begin
for i := 1 to N do
begin
DoTask1;
DoTask2;
end;
end;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "delphi, pascal, lazarus, fpc"
}
|
Debugging java for loop: skip to a specific iteration
I'm working on a java project in Netbeans. I have a for loop which runs 29 times and each iteration takes about 1 minute to complete. The problem is in the 29th iteration of the loop. Is there any way that I can SKIP the first 28 iterations and go directly to the one in question?
I know I can put a conditional breakpoint, but that dosent make the debugger skip the iterations, it just notifies me when a paticular iteration is reached.
Please Help! Otherwise, this would take a awful lot of time to debug!
|
You could use something like the Java Platform Debugger Architecture. That might help. On the other hand, you could do something like so:
for (int i = 0; i < ...; i++)
{
if (i == 28)
{
System.out.println("Line Found"); //put breakpoint here
}
//remainder of the code.
}
This should allow you to trigger a breakpoint on the 29th execution of the loop and you can then use the step functions offered by the debugger to go over the code for the 29th iteration.
I have never used the JPDA, and even if I did I think that the most simple and straight forward solution would be to do something like the code above.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "java, debugging, netbeans, for loop"
}
|
Unable to change file and folder owner and permission from root to other users ( Ubunto 20.4)
I am new to linux. I have a partition in which all the folder and files owner is set as root.I am unable to change anything using chomd and chown when i write the commands as : **sudo chown -c -v user testfile.txt.** The output is : _change ownership from root to user._ But when i do **ls -l** my file have user and group permission still set to root. Permission and owner changes successfully in my Desktop files and directories. Its just problem in one partition. I am very thankful if anyone help me in this problem.
|
It is failing on a partition if that partition is formatted using a file system that does not support linux file permissions. The file systems of Microsoft, i.e. fat, vfat, extfat and ntfs do not support linux permissions. Permissions for the entire drive are set during mounting.
With the utility "Disks", you can "take ownership" of an entire partition, including partitions formatted with a file system that does not support Linux permissions.
* Open Disks
* In the left pane, click the drive where the partition resides
* On the map on the right pane, click the partition you want to change
* Click the cog wheel icon and select "Take Ownership"
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 0,
"tags": "permissions, root, chmod, chown"
}
|
are singletons always closed?
I am learning about metric spaces and I find it very confusing. Is this a valid proof that a singleton must be closed?
If $(X,d)$ is a metric space, to show that $\\{a\\}$ is closed, let's show that $X \setminus \\{a\\}$ is open. Choose $y \in X \setminus \\{a\\}$ and set $\epsilon = d(a,y)$. Then since $a \not \in B(y,\epsilon)$, we have that $B(y,\epsilon) \subset X \setminus \\{a\\}$ so that $X \setminus \\{a\\}$ is open.
|
Your proof is okay. More generally, we can define any topological space to be $T_1$ if its singleton sets are closed (or equivalently, for any points $x \neq y$, there is an open set containing $x$ and not containing $y$). $T_1$ is an example of a separation axiom. You've shown that metric spaces are $T_1$, but much stronger separation axioms hold for metric spaces.
Credit to Squirtle for providing similar details in a comment.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 12,
"tags": "real analysis, general topology, metric spaces"
}
|
Use ASP.NET MVC as Email Template Engine: Good Idea?
Would it be a good idea, and executable, to use the ASP.NET MVC View Engine to render html to be sent out by email?
I know it's possible to let the view render into a string. So that could be use to build the mail message. Since ASP.NET MVC is already used in the application, I get to use all practical ASP.NET MVC stuff without having to use Brail or NVelocity for my "mail views".
Good idea? Any caveats? Examples :) ?
|
Yes it is a good idea and relatively easy to implement.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "asp.net mvc, templates, email, viewengine"
}
|
Terraform state file locked and stuck can't complete
while running terraform plan i did a CTRL C on a windows computer and now when i try to run terraform plan again i get
> Error: Error loading state: Failed to read state file: The state file could not be read: read terraform.tfstate: The process cannot access the file because another process has locked a portion of the file.
I tried
> terraform force-unlock id
but that gives me
> Local state cannot be unlocked by another process
I am kind of stuck and cannot move forward
Much appreciated if someone can please assist.
Regards, KKR
|
Did you save the state file in s3 or local? If it is from remote, try to delete that state file first and retry. If it is local process, you will need to kill the process and delete the state file from your local folder `.terraform/terraform.tfstate`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "terraform"
}
|
LIBSVM assigning parameter c
I'm trying to assign different values to c in LIBSVM in matlab. the code line is
`svmtrain(Ytrain, Xtrain, '-c C_vector(iter)')`
for different iterations and
`C_vector=1:10:100`
But this does not seem to work and prints `Error: C <= 0`
ps: I have tested the `svmtrain(Ytrain, Xtrain, '-c 1')` and `svmtrain(Ytrain, Xtrain, '-c 11')`, which are the first two values of C_vector, and they perfectly work. Any ideas what's wrong? Thanks
|
`svmtrain` cannot `eval` your subscript. Use instead:
svmtrain(Ytrain, Xtrain, sprintf('-c %d', C_vector(iter)));
that will write in the option string the value of the subscript expression.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "matlab, libsvm"
}
|
How do I contact another user?
> **Possible Duplicate:**
> How do I contact other users?
Is it possible to contact another StackOverflow user? He had the exact same problem as me and I'd like to find out if he ever solved it.
|
If the user's profile has an email address, you can contact him that way. You can get to his profile by clicking on his name.
If the user's profile doesn't have an email address, that means the user has chosen to interact only through the site directly, and does not want to be contacted privately.
|
stackexchange-meta
|
{
"answer_score": 3,
"question_score": -3,
"tags": "support"
}
|
selecting HTML element
I use a class named row across my site
.row {
max-width: 1140px;
margin: 0 auto;
}
 .works-steps { ... }` (you * can* use `>` in-between to be even more specific, but it's probably not necessary.
`:nth-child(...)` refers to the child element itself, i.e. the _child_ element that is the nth child of its parent, in your case `.steps-box` as the second child element of `.row`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css, css selectors"
}
|
Plotting curves given by equations in R
In R, is there a way to plot 2D curves given by equations? For example, how can I plot the hyperbola given by equation x^2 - 3*y^2 + 2*x*y - 20 = 0?
|
You can use `contour` to plot the two branches of your hyperbola.
f <- function(x,y) x^2 - 3*y^2 + 2*x*y - 20
x <- y <- seq(-10,10,length=100)
z <- outer(x,y,f)
contour(
x=x, y=x, z=z,
levels=0, las=1, drawlabels=FALSE, lwd=3
)
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 19,
"question_score": 12,
"tags": "r, graphics"
}
|
How do you usually take notes for reading source code of a big software
For big software, take notes is useful for understanding the big picture.
How you take notes? With pen/paper, or just a notepad; and what you usually will write for note?
|
If you're a team: install a wiki and contribute all your discoveries there. Will preserve the knowledge for eternity and sharing it will be very easy.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 6,
"tags": "knowledge management"
}
|
Update PHP7 MYSQL PHP Extension
I need to Upgrade my Server PHP version to 7.
Is there a way to update in OpenSuse 13.2 to version PHP7 via the console?
Can I install a php Extension which allows me to use the following again?
mysql_connect
mysql_query
mysql_select_db
PS: May be you could help me on another question too? <
That's the Reason why I need to updgrade to PHP to 7.
|
I answered your other question in the other thread, and, you're not going to be able to use Magento with PHP 7 at this time. However, I'm assuming you're asking about a different PHP application since Magento surely wouldn't make use of these functions.
The short answer is no, because `mysql_*()` functions are deprecated and dangerous. Everyone should be using MySQLi (the improved version) now, as it fixes these issues. Prepared statements should also be used. If you run into an issue converting a particular `mysql_*()` function call to MySQLi, just post a question to StackOverflow. There should be quite a bit of information on particular MySQLi issues on SO already.
But, as I posted to the other threat, it looks like you won't need PHP 7 yet, but you should still stop using `mysql_*()`.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, opensuse, upgrade, console"
}
|
Mysql Inner Join Issues
This gives me all my articles that contain both the mentioned entities.
SELECT COUNT(ArticlesEntity.article_id) AS article_count
FROM articles_entities ArticlesEntity
WHERE ArticlesEntity.entity_id IN ('ENTITY_ID_1','ENTITY_ID_2')
GROUP BY ArticlesEntity.article_id
HAVING article_count>=2
I now want to add something to this query that excludes any entity that has 'ENTITY_ID_3'.
I tried the following but it returned the same results:
SELECT COUNT(ArticlesEntity.article_id) AS article_count
FROM articles_entities ArticlesEntity
WHERE ArticlesEntity.entity_id IN ('ENTITY_ID_1','ENTITY_ID_2')
AND ArticlesEntity.entity_id NOT IN ('ENTITY_ID_3')
GROUP BY ArticlesEntity.article_id
HAVING article_count>=2
What am I missing / doing wrong?
Thanks in advance
|
Try something like:
SELECT COUNT(ArticlesEntity.article_id) AS article_count
FROM articles_entities ArticlesEntity
WHERE ArticlesEntity.entity_id IN ('ENTITY_ID_1','ENTITY_ID_2')
AND NOT EXISTS (
select 1
from articles_entities
where article_id = ArticlesEntity.article_id
and entity_id = 'ENTITY_ID_3')
GROUP BY ArticlesEntity.article_id
HAVING article_count>=2
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, subquery, inner join"
}
|
As Arsonist, how do I prevent lighting myself on fire if another Arsonist doused me?
OK, so in an All Any or Custom game (Rainbow in particular), you can have more than one Arsonist.
If a different Arsonist douses you and you light up all doused victims, you yourself will die.
Is there any way to prevent this?
|
This isn't actually documented in the game, but yes there is.
As an Arsonist, if you choose to not do anything for a night, you will clean the gas off your house if there is any.
I highly recommend doing this the night after you get doused so the other Arsonist can't accidentally light you on fire the next night.
|
stackexchange-gaming
|
{
"answer_score": 2,
"question_score": 1,
"tags": "town of salem"
}
|
Display Wordpress loop with first item formatted differently?
I have a series of posts in a custom post type. They each have a featured image (thumbnail)and an excerpt.
I want to display 4 items on the home page, with the first item formatted differently from the other 3, such as in the attached image. How is that done?
!enter image description here
|
You can use a counter for this. See sample below
<?php
$inc = 1;
$the_query = new WP_Query();
$the_query->query("posts_per_page=4");
if ($the_query->have_posts()) :
while($the_query->have_posts()) : $the_query->the_post();
if($inc == 1){
//first post here
//do stuffs here
}
else{
//the rest of the posts
}
$inc++; //counter
endwhile;
endif;
wp_reset_postdata();
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 0,
"tags": "wordpress theming, wordpress"
}
|
When to specify elements for classes?
/*INPUT BOXES ( input )
*/
.toggle_border_show{
border: 1px solid #cccccc;
}
.toggle_border_obscure{
border: 1px solid #888888;
}
.toggle_border_hide{
border: 1px solid #444444;
}
I noticed that these classes are only used on input elements.
Should I have pre-fixed them with input as such
/*INPUT BOXES ( input )
*/
input.toggle_border_show{
border: 1px solid #cccccc;
}
input.toggle_border_obscure{
border: 1px solid #888888;
}
input.toggle_border_hide{
border: 1px solid #444444;
}
Does it matter?
|
If you know that the classes are only used on input elements then it is unnecessary to add the input before the class name.
Furthermore - as @PaulD.Waite mentioned in the comments - even if you plan on using these classes on other elements: if you are happy for these styles to apply to them as well - then input should still not be used before the class name.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "css"
}
|
How to find a polynomial of two variables with 2 local extrema
How could I find the simplest polynomial $P[x,y]=\sum_{0\leq i,0\leq j} \alpha_{ij} x^i y^j$ with only $N$ local extrema ? I'm mostly interested in the cases $N=2$ and $N=3$.
Meaning there are only $N$ solutions for the system {$\frac{\partial P}{\partial x}=0,\frac{\partial P}{\partial y}=0\\}$
|
For $N=2$ local _extrema_ , a suitable Cassini oval works. For instance, $$ ((x-a)^{2}+y^{2})((x+a)^{2}+y^{2})=b^{4} $$ with $a=1$ and $b^4=0.9$, which gives
(x^2 +y^2 −2)(x^2 +y^2 −3)+x^6=0 $$
. Is there a simple way to identify the final part of a file name and rename it in a loop?
For example, the directories are ...
/data/images/projects/MM/1/scans/16/7__ep2d_fid_basic_bold_293_Resting_State
/data/images/projects/MM/1/scans/20/7__ep2d_fid_basic_bold_293_Resting_State
/data/images/projects/MM/1/scans/03/8
I want to change them to...
/data/images/projects/MM/1/scans/16/rs
/data/images/projects/MM/1/scans/20/rs
/data/images/projects/MM/1/scans/03/rs
I can't figure out a way to do this, although it should be simple. Sorry, a newbie here.
|
I wrote a small script that will do the job for you.
It will read the content of an input file, remove everything after last slash + slash sign, and append /rs at the end, and then write the changes to a new file (called output.txt).
Create a script.sh and chmod +x it and add the following to it,
#!/bin/bash
# Usage: ./script.sh input.txt, where input.txt is your input file with the
# raw data you want to change.
while IFS='' read -r line
do
name=$line
echo "Before: $name"
name=`echo $name | awk -F '/' '{ for(i=1; i<=8; i++) {print $i} }' | tr '\n' '/'|sed 's/.$//'`
echo "$name/rs" >> output.txt
done < "$1"
# EOF
Run it by typing `./script.sh input.txt` in the console.
Note: This is one way of doing it and it probably fits your current specific problem. It does not update the input file. Rather, it creates a new file (output.txt) with the new content.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "linux"
}
|
Linux Java: load .so dynamically without dlopen
I have 2 libs (first.so and second.so), and I need to call a function from 'second.so' in the 'first.so'. Now in my case I don't want to do static link to second.so. I need to call it dynamically. So what I need is to use
System.loadlibrary("first.so") System.loadlibrary("second.so")
Now in the c++ code of "first.so" I need to call a function from the second.so. Can I do this without dlopen?
|
When you compile the C++ code and build your first.so you instruct the linker to use external symbols from the second library. The second library must be on the library search path at run time so that the systems dynamic linker can find it.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, java native interface"
}
|
Yii different model value displayed in cgridview and views
I have values that are stored in raw number form percents (e.g .998) in my generated models.
However, for my views, as well as display in CGRIDview I would like these data points to be multiplied by 100, but retain the same value in the backend database. So in my view the above example should display as 99.8 %
|
Define your CGridView columns the following method:
'columns' => array(
// ... fields
array(
'name' => 'fieldWithPecent',
'value' => 'sprintf("%3.1f%%", $data->fieldWithPecent * 100)',
),
// other fields definition
),
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php, mysql, yii"
}
|
Что не так в регулярном выражении?
Почему не работает регулярка?
Elapsed\sTime:\D+(.+?)<\/font>[\n]*.Last\sCalled\sNumber:\D+(\d{5,})@gw0<\/font>\D+(\d{5,})<\/font>
Elapsed Time:</td><td><font color="darkblue">16 days and 12:42:31</font><>
<>
<><>
<>
<>7gt757tLast Called Number:</td><td>
<font color="darkblue">67678799989@gw0</font>
</td><td>Last Caller Number:</td>
<td><font color="darkblue">876868856454</font>
Между `</font> и Last Called Number:` может быть любой текст и любое количество переносов строки (/n). Ожидаемый результат:
16 days and 12:42:31
67678799989
876868856454
|
Если реализовать через замену, что-то такое должно быть:
^.*?<font.*?>(.*?)<\/font>(.|\r|\n)*?<font.*?>(.*?)\@.*?<\/font>(.|\r|\n)*?<font.*?>(.*?)<\/font>$
в первых, третьих и пятых скобках нужные данные.
Псевдокодом так:
string txt = '
Elapsed Time:</td><td><font color="darkblue">16 days and 12:42:31</font><>
<>
<><>
<>
<>7gt757tLast Called Number:</td><td>
<font color="darkblue">67678799989@gw0</font>
</td><td>Last Caller Number:</td>
<td><font color="darkblue">876868856454</font>';
print regRepace(/^.*?<font.*?>(.*?)<\/font>(.|\r|\n)*?<font.*?>(.*?)\@.*?<\/font>(.|\r|\n)*?<font.*?>(.*?)<\/font>$/, \1\r\n\3\r\n\5);

with worksheets("sheet1")
tmp = .range(.cells(1, "A"), .cells(.rows.count, "A").end(xlup)).value2
end with
redim arr(0)
for i=lbound(tmp, 1) to ubound(tmp, 1)
if tmp(i, 1) = dt then
redim preserve arr(j)
arr(j) = i 'collect row numbers
j=j+1
end if
next i
for i=lbound(arr) to ubound(arr)
debug.print arr(i) 'print row numbers
next i
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "excel, vba"
}
|
Recursively loop through an array and return number of items?
I apologize if this has been asked before but I could not find an answer. How do I loop through an array with nested arrays and in the console print out the number of instances an item appears?
So `console.log` should print out the number 2 for the name "bob" because "bob" appears twice in the array.
Here is my array and what I have so far:
var names = ["bob", ["steve", "michael", "bob", "chris"]];
function loop(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
loop(arr[i], item);
} else {
if (arr[i] == item) {
console.log(arr[i]);
}
}
}
}
loop(names, "bob");
|
here you go, note that you can keep the counter value internally, to keep the rest of your code cleaner:
var names = ["bob", ["steve", "michael", "bob", "chris"]];
function loop(arr, item) {
var result = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
result += loop(arr[i], item);
} else {
if (arr[i] == item) {
result++;
}
}
}
return result;
}
var result = loop(names, "bob");
console.log(result);
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 5,
"tags": "javascript, arrays, recursion"
}
|
Node.js: use request module receive error bytes in http response
I'm using nodejs to send http request to a server, and get http response from it(the http response body is **encrypted** , while the http header is **normal** ). The response body will be written to a file. But I find the response body is different from what the server sent.
This is what I've done:
request.post({
headers: {'content-type':'application/json'},
url:'url-to-server',
body:data-to-send
}, function(error, response, body){
if(!error && response.statusCode==200){
fs.writeFile(path-to-file,body,function(err){
});
}
});
The problem is, some byte values are replaced by **`ef bf bd`**
Server Send:
**f5** cb b6 48 77 **b6** 26 6a d2 4c d8 d9 ...
Received data:
**ef bf bd** cb b6 48 77 **ef bf bd** 26 6a ...
Any ideas?
|
I've found that `ef bf bd` occurs when it tries to use `utf-8` encoding. So I want to recieve raw data without encoding.
And I found this question about getting binary content, according to this link, i add `encoding:null` in my code, see below:
request.post({
headers: {'content-type':'application/json'},
url:'url-to-server',
**encoding:null** ,
body:data-to-send
}, function(error, response, body){
if(!error && response.statusCode==200){
fs.writeFile(path-to-file,body,function(err){
});
}
});
And now the received data is correct.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js"
}
|
Shopify check if image exists
I added an image upload setting to my Theme's settings. It's id is `slider.jpg` and I want to know what the liquid function is to check if the image exists. I don't want to show the image if it doesn't exist yet ( Hasn't been uploaded in the theme settings, in admin.
|
Just do
{% for i in (1..6) %}
{% assign display_slide = 'display_slide_' | append: forloop.index %}
{% assign slide_img = 'slider_' | append: forloop.index | append: '.jpg' %}
{% if settings[display_slide] %}
<li>{{ slide_img | asset_url }}</li>
{% endif %}
{% endfor %}
and then in your settings file do this for numbers 1 - 6
{
"type": "checkbox",
"id": "display_slide_1",
"label": "Display Slide One?"
},{
"type": "image",
"id": "slider_1.jpg",
"label": "Slide Image One"
},
{
"type": "checkbox",
"id": "display_slide_2",
"label": "Display Slide Two?"
},{
"type": "image",
"id": "slider_2.jpg",
"label": "Slide Image Two"
},
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "shopify"
}
|
Calculate difference between dates returning datetime result
I need to get the difference between two dates in datetime format: `HH:mm:ss`. Is it possible using some T-SQL function? I always used `DATEDIFF` but it returns only `int`.
|
declare @date1 datetime = '2012-08-04 12:10'
declare @date2 datetime = '2012-08-04 13:10'
select cast(@date2 - @date1 as time(0))
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "tsql"
}
|
What cable do I need to connect this internal hard drive to my computer?
This is an image:
 internal hard drive. It's Samsung model HD103SJ.
What cable do I need to connect this to a USB 3 port?
|
An adapter like this would do the trick.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "hard drive, usb, usb 3"
}
|
Error 24 too many files open
I am doing a game. it requires lots of images. When using the app in normal case it will be quite running fine. But when it rash then i get the error 24 - too many files open.
I searched it but , i didn't get the appropriate answer.
please reply.
Code from comment formatted:
-(void)flowerImagesAnimate {
self.flowerImage.animationImages = self.flowerArray;
self.flowerArray = nil;
self.flowerImage.animationDuration = 1.0;
self.flowerImage.animationRepeatCount = 3;
[self.flowerImage startAnimating];
}
– Munnu 1 hour ago
|
Don't open so many files.
If you have more open than you need, close them. If you need that many open, collect them in to 1 larger image and use portions.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "iphone, objective c, ipad, memory, memory management"
}
|
express gateway не работает команда eg в консоли?
Установил express-gateway и глобально и локально, но команда eg gateway create не является внутренней или внешней командой. В переменные среды добавлял пути
 VALUES (23) ON DUPLICATE KEY UPDATE ProductCode = FLOOR(RAND() * 500)
The problem with the above query is that it always fails
Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '88' for key 'ProductCode' in
How can i do my query so if the key already exists generate another one and continue with the inserts?
|
The simple way to do this query would be to do a while in php and from there check if the product code is unique or not and if it's not unique generate a new one. don't forget to -1 the answer cuz i won't post the code how i did it just to make sure i get -1 :-). I heard it takes less time to do -1 on a question and move on when no one know's a good way to do it.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "mysql"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.