text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Intelligent credit cards fields iOS i'm currently developing an app for iOS 8 in swift with a credit card payment functionality.
I searched on the web for a library with intelligent credit card fields, but all i could find is BKMoneyKit, which is not really customizable, and doesn't fit my needs.
What i want is something with fancy features, like telling you if your card is a visa/mastercard when you enter the number, adding the "/" between month and year of expiration date etc... I've already used card.io, but it doesn't offer the possibility to include it's intelligent fields in my view, like said here by the developer himself.
Does anybody knows a tool like this ?
Thanks in advance for help :)
A: The functionalities you are asking for are provided by the PaymentKit library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34038553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to store and pass information between list views The functionality of my app can be modeled after something like wanelo.
The user will enter a search term for what they want to buy in one Activity. They will get presented with a list of items that match that search term. So, the ListView will contain Items. An Item has many attributes, the main ones being:
*
*id - corresponds to the Item's id in a database
*date_modified - timestamp to know whether the Item was updated
*remote_directory - a URL to the base directory of the Item's assets like icon and other images. The URL is formatted like this: http://my.domain.com/items/a1bc234d/ where a1bc234d is randomly generated, seeded by date_modified.
*remote_dir_name - a substring of remote_directory. From the example above, this value would be a1bc234d.
From the list of search results, the user can mark an item to be viewed later. This will trigger a couple of things:
*
*First, I want to ad the Item to a different ListView that represents the Items the user has "downloaded".
*Then, I want to actually download of all of the Item's data: description, all assets in remote_directory. These things get stored my app's internal storage in folders remote_dir_name: /data/data/my.app.package.name/files/a1bc234d/.
These "downloaded" items are meant to be viewable in offline mode.
This "downloaded" ListView corresponds to a different Activity and will have list items that show a progress bar of the download status for an Item. Also, this ListView should be editable: use should be able to delete and re-order the Items in the list.
Finally, the "downloaded" ListView needs to be persistent. It should preserve order. The ListView of search results need not persist.
I'm having a lot of trouble figuring out how to store the list of Items getting downloaded. The "download" ListView needs to know when to update a list item's progress bar if it's getting downloaded. I think it's a little overkill to store the Items in a database because I'll be constantly updating a row's column until the download finishes. How should I pass this download status information between these two ListViews?
A: I am not entirely sure I am grasping the whole picture here, but it seems to me that you need two ArrayList fields.
List<Item> downloadedItems = new ArrayList<Item>;
List<Item> searchItems = new ArrayList<Item>;
then what you need to do is create your own custom ListAdapter for the DownloadListView and create your own custom download_item.xml that you will inflate inside of the ListAdapter. In your case it sounds like this download_item.xml will consist of a textview, and a progressbar, and will need the containing (or top layer) layout set to wrap content.
Now in the on click listener for the SearchListView set it so that it will call a function that will take the item that was tapped and add it to the downloadedItems ArrayList and start the download, as well as refresh the listadapter dataset so it knows to update the items in the list.
The download should be in a AsyncTask, and you will want to use the @Override publishProgress() portion of this, so that you can update the status of the download bar.
forgive me for any mis sights or mistakes, I just woke up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14428253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: calling instance method on model and passing its parameters I have model.rb
class Foo
def baz(param1, param2, param3, param4)
puts 'something'
end
end
controller.rb
def signup
param4 = params[:param4] || 'N'
begin
@foo.baz(Integer(params[:param1]),
params[:param2],
params[:param3],
param4)
head :ok
rescue ArgumentError => e
render_error(:bad_request, e.message)
end
end
Is this the right way to call instance method on model? also should this param4 = params[:param4] || 'N' be done in model?
A:
Is this the right way to call instance method on model?
Yes, if @foo is an instance of Foo
should this param4 = params[:param4] || 'N' be done in model?
You can set the last parameter variable on you model to be option like so
class Foo
def baz(param1, param2, param3, param4 = 'N')
puts 'something'
end
end
And remove the need to set it within the controller
def signup
@foo.baz(Integer(params[:param1]),
params[:param2],
params[:param3],
params[:param4])
head :ok
rescue ArgumentError => e
render_error(:bad_request, e.message)
end
Since if params[:param4] is nil it will be set to 'N' as specified within the baz method on the Foo model.
Whether or not if you should set param4 in the model is up to you:
*
*Yes, if setting the last parameter param4 to 'N' should or need to occur outside the controller, or
*No, if setting a default value for param4 is unique to the signup controller action and param4 should not have default set, since it might be used elsewhere
A: I think you should handle it in model:
class Foo
def baz(param)
param1 = Integer(params[:param1])
param2 = params[:param2]
param3 = params[:param2]
param4 = params[:param4] || 'N'
puts 'something'
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42776363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wordpress Custom Fields not displaying the section I have added a new layout in the Wordpress Custom fields plugin, and after adding it I have added the fields in the corresponding php file too. But for some reason, its printing the code in the browser. I am not sure what I am doing wrong here. I am new to WordPress, so can someone please help me?
Screenshots attached for reference.
PHP file code - https://codeshare.io/GklExO
A: Figured it out, I had to add an image tag and then it worked fine.
However, there are other PHP files in the site, where
<?php the_sub_field('image'); ?> displays the image, but in this particular case I had to write it as
<img src="<?php echo esc_url($image['url']); ?>"/>
Still trying to understand how this works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63318214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Covert name part after "ACCOUNTS\\" to lower case? I have web method to get user from this.User.Identity.Name.string username = "ACCOUNTS\Ninja.Developer" I want to convert username part after "ACCOUNTS\" to lower case to be username = "ACCOUNTS\ninja.developer"
public User GetUser()
{
var user = new User
{
Username = this.User.Identity.Name,<-- convert it here
IsAuthenticated = this.User.Identity.IsAuthenticated
};
return user;
}
note: double \ not single \
A: Use this code:
var Identity = this.User.Identity.Name;
var Username = Identity.Split('\\')[0] + @"\\" + Identity.Split('\\')[2].ToLower();
Of course you should check before in the name have the \ character, etc.
A: You can use Regex.Replace to achieve it :
Username = Regex.Replace(this.User.Identity.Name, @"(?<=ACCOUNTS\\).+", n => n.Value.ToLower()),
The regex pattern (?<=ACCOUNTS\\).+ will match for anything after ACCOUNTS\, and the match is then replaced by its lower case equivalent.
A: As mentioned in other answers, you can use Regex or Split, but here's a substring approach specific to your case.
var user = new User
{
Username = this.User.Identity.Name.Substring(0,9) + this.User.Identity.Name.Substring(9, name.Length - 9).ToLower(),
IsAuthenticated = this.User.Identity.IsAuthenticated
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37687261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Swift 2.0 NSJSONSerialization fails if response has only one item Here is a snippet of my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
do {
guard let json = try NSJSONSerialization.JSONObjectWithData
(data!, options: .MutableContainers) as? [NSDictionary] else {
throw HttpError.ParsingFailed
}
completionHandler(success: true, data:json, error: nil)
}
catch HttpError.ParsingFailed {
...
It works fine, if the response data has more than one element.
However the NSJSONSerialization.JSONObjectWithData fails (goes in the else block which throws the exception), if there is only one item in the response.
Why doesn't it still parse the response in this case, and returns an array with one element inside?
How should be this problem generally solved?
Of course it would help to do an other parsing in the catch block with as? NSDictionary instead of as? [NSDictionary], but I would avoid this when possible.
EDIT:
object to be parsed which works:
[
{
"id": 1,
"idConsumer": 12
},
{
"id": 2,
"idConsumer": 12
}
]
and which does not work:
{
"id": 65,
"delivery": {
"id": 29,
"idConsumer": 19
},
"postman": {
"id": 13,
"email": "testpostman"
},
"price": 89
}
A: It's failing because you are casting your JSON to [NSDictionary]. When you get multiple objects, you get an array of dictionaries, but when you get a single object, you get a single dictionary.
You should try to cast to NSDictionary if casting to [NSDictionary] fails.
If both fail then you should throw the error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36901231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Read a text file into a pandas dataframe or numpy array I have a file that looks like this - http://pastebin.com/u1A7v1CV
It's just a sample of two rows from a file.
The rows contain word_label_id followed by freq.
For example, word_label_id 1237 occurs 1 time in the first row, 1390 occurs 1 time and so on...
I need to use this sparse representation but I'm unable to convert it into a DataFrame or any other usable format.
Edit: I know that pandas has a read_csv method where I can use a space as the delimiter. This is not ideal as I need two separators - one between word_label_id and freq and a different separator between this pair and the next.
A: Ok, it's not ideal but you can use notepad++.
It had a "find and replace" feature and you can use \t to replace tabs as \n
Then you can record a macro to move any given line to the previous, skipping lines.
Then you can use pandas, pd.from_csv but you have to define delimiters as tabs instead of commas
Another option is to read each line,and process it separately. Basically a while loop with the condition being not m_line == null
Then inside the loop, split the string up with str.split ()
And have another loop that makes a dictionary, for each row. In the end, you'd have a list of dictionaries where each entry is ID:frequency
A: Have you tried work separately with each item?
For example:
Open document:
with open('delimiters.txt') as r:
lines = r.readlines()
linecontent = ' '.join(lines)
Create a list for each item:
result = linecontent.replace(' ', ',').split(',')
Create sublist for ids and freqs:
newResult = [result[x:x+2] for x in range(0, len(result), 2)]
Working with each data type:
ids = [x[0][:] for x in newResult]
freq = [x[1][:] for x in newResult]
Create a DataFrame
df = pandas.DataFrame({'A ids': ids, 'B freq': freq})
A: Here's what I did.
This creates a dictionary containing key-value pairs
from each row.
data = []
with open('../data/input.mat', 'r') as file:
for i, line in enumerate(file):
l = line.split()
d = dict([(k, v) for k, v in zip(l[::2], l[1::2])])
data.append(d)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39969302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting cache info using C/C++ with inline assembly/intrinsics in osx I wrote the following program using both gcc __get_cpuid and inline assembly to get the cache info of my laptop but fail to identify them on the table about (Encoding of Cache and TLB Descriptors) I found online.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <math.h>
#include <cpuid.h>
static inline void cpuid(uint32_t *eax, uint32_t *ebx,
uint32_t *ecx, uint32_t *edx);
int main() {
uint32_t a, b, c, d;
uint32_t eax, ebx, ecx, edx;
eax = 2; /* processor info and feature bits */
uint32_t command = 2;
cpuid(&eax, &ebx, &ecx, &edx);
__get_cpuid(command, &a, &b, &c, &d);
printf("eax: %08x\n", eax);
printf("ebx: %08x\n", ebx);
printf("ecx: %08x\n", ecx);
printf("edx: %08x\n", edx);
printf("a: %08x\n", a);
printf("b: %08x\n", b);
printf("c: %08x\n", c);
printf("d: %08x\n", d);
}
static inline void cpuid(uint32_t *eax, uint32_t *ebx,
uint32_t *ecx, uint32_t *edx)
{
/* ecx is often an input as well as an output. */
asm ("cpuid"
: "=a" (*eax),
"=b" (*ebx),
"=c" (*ecx),
"=d" (*edx)
: "0" (*eax));
}
my output:
eax: 76036301
ebx: 00f0b5ff
ecx: 00000000
edx: 00c10000
a: 76036301
b: 00f0b5ff
c: 00000000
d: 00c10000
I found this table from here
I use sysctl hw.cachesize and find that
L1 cache: 32KB
L2 cache: 256KB
L3 cache: 6MB
My Environment:
system: os x 10.10.1
compiler: clang-602.0.53
CPU: I7-4850 HQ 2.3HZ
What's wrong with my program? My program should work since both methods give the same result... I am confused about this. Thank you!
EDIT:
I try what Mats' suggested and get the following as my output:
gcc intrinsic
a: 76036301
b: 00f0b5ff
c: 00000000
d: 00c10000
eax: 2
eax: 76036301
ebx: 00f0b5ff
ecx: 00000000
edx: 00c10000
eax: 4, ecx: 0
eax: 1c004121
ebx: 01c0003f
ecx: 0000003f
edx: 00000000
eax: 4, ecx: 1
eax: 1c004122
ebx: 01c0003f
ecx: 0000003f
edx: 00000000
eax: 4, ecx: 2
eax: 1c004143
ebx: 01c0003f
ecx: 000001ff
edx: 00000000
eax: 4, ecx: 3
eax: 1c03c163
ebx: 02c0003f
ecx: 00001fff
edx: 00000006
eax: 4, ecx: 4
eax: 1c03c183
ebx: 03c0f03f
ecx: 00001fff
edx: 00000004
eax: 4, ecx: 5
eax: 00000000
ebx: 00000000
ecx: 00000000
edx: 00000000
I look up the table at here
static cpuid_cache_descriptor_t intel_cpuid_leaf2_descriptor_table[] = {
// -------------------------------------------------------
// value type level ways size entries
// -------------------------------------------------------
{ 0x00, _NULL_, NA, NA, NA, NA },
{ 0x01, TLB, INST, 4, SMALL, 32 },
{ 0x02, TLB, INST, FULLY, LARGE, 2 },
{ 0x03, TLB, DATA, 4, SMALL, 64 },
{ 0x04, TLB, DATA, 4, LARGE, 8 },
{ 0x05, TLB, DATA1, 4, LARGE, 32 },
{ 0x06, CACHE, L1_INST, 4, 8*K, 32 },
{ 0x08, CACHE, L1_INST, 4, 16*K, 32 },
{ 0x09, CACHE, L1_INST, 4, 32*K, 64 },
{ 0x0A, CACHE, L1_DATA, 2, 8*K, 32 },
{ 0x0B, TLB, INST, 4, LARGE, 4 },
{ 0x0C, CACHE, L1_DATA, 4, 16*K, 32 },
{ 0x0D, CACHE, L1_DATA, 4, 16*K, 64 },
{ 0x0E, CACHE, L1_DATA, 6, 24*K, 64 },
{ 0x21, CACHE, L2, 8, 256*K, 64 },
{ 0x22, CACHE, L3_2LINESECTOR, 4, 512*K, 64 },
{ 0x23, CACHE, L3_2LINESECTOR, 8, 1*M, 64 },
{ 0x25, CACHE, L3_2LINESECTOR, 8, 2*M, 64 },
{ 0x29, CACHE, L3_2LINESECTOR, 8, 4*M, 64 },
{ 0x2C, CACHE, L1_DATA, 8, 32*K, 64 },
{ 0x30, CACHE, L1_INST, 8, 32*K, 64 },
{ 0x40, CACHE, L2, NA, 0, NA },
{ 0x41, CACHE, L2, 4, 128*K, 32 },
{ 0x42, CACHE, L2, 4, 256*K, 32 },
{ 0x43, CACHE, L2, 4, 512*K, 32 },
{ 0x44, CACHE, L2, 4, 1*M, 32 },
{ 0x45, CACHE, L2, 4, 2*M, 32 },
{ 0x46, CACHE, L3, 4, 4*M, 64 },
{ 0x47, CACHE, L3, 8, 8*M, 64 },
{ 0x48, CACHE, L2, 12, 3*M, 64 },
{ 0x49, CACHE, L2, 16, 4*M, 64 },
{ 0x4A, CACHE, L3, 12, 6*M, 64 },
{ 0x4B, CACHE, L3, 16, 8*M, 64 },
{ 0x4C, CACHE, L3, 12, 12*M, 64 },
{ 0x4D, CACHE, L3, 16, 16*M, 64 },
{ 0x4E, CACHE, L2, 24, 6*M, 64 },
{ 0x4F, TLB, INST, NA, SMALL, 32 },
{ 0x50, TLB, INST, NA, BOTH, 64 },
{ 0x51, TLB, INST, NA, BOTH, 128 },
{ 0x52, TLB, INST, NA, BOTH, 256 },
{ 0x55, TLB, INST, FULLY, BOTH, 7 },
{ 0x56, TLB, DATA0, 4, LARGE, 16 },
{ 0x57, TLB, DATA0, 4, SMALL, 16 },
{ 0x59, TLB, DATA0, FULLY, SMALL, 16 },
{ 0x5A, TLB, DATA0, 4, LARGE, 32 },
{ 0x5B, TLB, DATA, NA, BOTH, 64 },
{ 0x5C, TLB, DATA, NA, BOTH, 128 },
{ 0x5D, TLB, DATA, NA, BOTH, 256 },
{ 0x60, CACHE, L1, 16*K, 8, 64 },
{ 0x61, CACHE, L1, 4, 8*K, 64 },
{ 0x62, CACHE, L1, 4, 16*K, 64 },
{ 0x63, CACHE, L1, 4, 32*K, 64 },
{ 0x70, CACHE, TRACE, 8, 12*K, NA },
{ 0x71, CACHE, TRACE, 8, 16*K, NA },
{ 0x72, CACHE, TRACE, 8, 32*K, NA },
{ 0x78, CACHE, L2, 4, 1*M, 64 },
{ 0x79, CACHE, L2_2LINESECTOR, 8, 128*K, 64 },
{ 0x7A, CACHE, L2_2LINESECTOR, 8, 256*K, 64 },
{ 0x7B, CACHE, L2_2LINESECTOR, 8, 512*K, 64 },
{ 0x7C, CACHE, L2_2LINESECTOR, 8, 1*M, 64 },
{ 0x7D, CACHE, L2, 8, 2*M, 64 },
{ 0x7F, CACHE, L2, 2, 512*K, 64 },
{ 0x80, CACHE, L2, 8, 512*K, 64 },
{ 0x82, CACHE, L2, 8, 256*K, 32 },
{ 0x83, CACHE, L2, 8, 512*K, 32 },
{ 0x84, CACHE, L2, 8, 1*M, 32 },
{ 0x85, CACHE, L2, 8, 2*M, 32 },
{ 0x86, CACHE, L2, 4, 512*K, 64 },
{ 0x87, CACHE, L2, 8, 1*M, 64 },
{ 0xB0, TLB, INST, 4, SMALL, 128 },
{ 0xB1, TLB, INST, 4, LARGE, 8 },
{ 0xB2, TLB, INST, 4, SMALL, 64 },
{ 0xB3, TLB, DATA, 4, SMALL, 128 },
{ 0xB4, TLB, DATA1, 4, SMALL, 256 },
{ 0xBA, TLB, DATA1, 4, BOTH, 64 },
{ 0xCA, STLB, DATA1, 4, BOTH, 512 },
{ 0xD0, CACHE, L3, 4, 512*K, 64 },
{ 0xD1, CACHE, L3, 4, 1*M, 64 },
{ 0xD2, CACHE, L3, 4, 2*M, 64 },
{ 0xD3, CACHE, L3, 4, 4*M, 64 },
{ 0xD4, CACHE, L3, 4, 8*M, 64 },
{ 0xD6, CACHE, L3, 8, 1*M, 64 },
{ 0xD7, CACHE, L3, 8, 2*M, 64 },
{ 0xD8, CACHE, L3, 8, 4*M, 64 },
{ 0xD9, CACHE, L3, 8, 8*M, 64 },
{ 0xDA, CACHE, L3, 8, 12*M, 64 },
{ 0xDC, CACHE, L3, 12, 1536*K, 64 },
{ 0xDD, CACHE, L3, 12, 3*M, 64 },
{ 0xDE, CACHE, L3, 12, 6*M, 64 },
{ 0xDF, CACHE, L3, 12, 12*M, 64 },
{ 0xE0, CACHE, L3, 12, 18*M, 64 },
{ 0xE2, CACHE, L3, 16, 2*M, 64 },
{ 0xE3, CACHE, L3, 16, 4*M, 64 },
{ 0xE4, CACHE, L3, 16, 8*M, 64 },
{ 0xE5, CACHE, L3, 16, 16*M, 64 },
{ 0xE6, CACHE, L3, 16, 24*M, 64 },
{ 0xF0, PREFETCH, NA, NA, 64, NA },
{ 0xF1, PREFETCH, NA, NA, 128, NA }
};
The problem right now is that I still cannot get the correct size of my L3 cache(when ecx=1, I get 22 i.e. 512K, but the correct value is 6MB). Also, there seems to be some conflicts in terms of the size of my L2 cache(43(when ecx=2) and 21(when ecx=0) )
A: So, your data seems to be reasonably correct, just that you are using an old reference. Unfortunately, Intel's website is either broken presently or it doesn't like Firefox and/or Linux.
76036301
76 means trace cache with 64K ops.
03 means 4 way DATA TLB with 64 entries.
63 is 32KB L1 cache - the source here shows that value, which is not in your docs.
01 means 4 way Instruction TLB with 32 entries.
00f0b5ff gives
00 "nothing"
f0 prefetch, 64 entries.
0b Instruction 4 way TLB for large pages, 4 entries.
b5 is not documented even on that link. [guessing small data TLB]
To get L2 and L3 cache sizes, you need to use CPUID with EAX=4, and set ECX to 0, 1, 2, ... for each caching level. The linked code shows this, and Intel's docs have details on which bits mean what.
A: Intel's Instruction Set Reference has all the relevant information you need (at around page 263), and is actually up to date unlike every other source I have found.
Probably the best way to get the cache info is mentioned in that reference.
When eax = 4 and ecx is the cache level,
Ways = EBX[31:22]
Partitions = EBX[21:12]
LineSize = EBX[11:0]
Sets = ECX
Total Size = (Ways + 1) * (Partitions + 1) * (Line_Size + 1) * (Sets + 1)
So when CUPID is called with eax = 4 and ecx = 3, you can get your L3 cache size by doing the computation above. Using the OP's posted data:
ebx: 02c0003f
ecx: 00001fff
Ways = 63
Partitions = 0
LineSize = 11
Sets = 8191
Total L3 cache size = 6291456
Which is what was expected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35395811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android 6 Permissions - managing foreign apps permissions Using the package manager I can see what permissions foreign apps request. But is it possible to find out what permissions the user allows for other apps? And can you change the permissions of other apps from your application? These questions apply on non-rooted devices.
A: I solved this problem in a rooted device; the way I follow to manage permission require root privileges:
Process su = Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(su.getOutputStream());
dos.writeBytes("pm revoke/grant " + packageName + " " + permissionName);
dos.flush();
dos.close();
Maybe studing android security architecture you will be cabable to find a way to solve the problem on non-rooted devices but you'll waste a lot of time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36425774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 0 value not working when import excel sheet for if condition in laravel excel Excel file as below
Id | pro name | status
1 | test. | 0
*
*Laravel 5.6
*PHP 7.2
*Maatwebsite/excel 2.*
Below my Laravel code
$data = Excel::load($path)->get();
if print $data then its show me 0.
echo $data[0]->status; // output:0
if($data[0]->status === ""){
echo "Status field required"; exit;
}
if($data[0]->status === 0 || $data[0]->status === 1){
echo "successfully";exit;
}else{
echo "status format 0 or 1 required"; exit;
}
if I set 0 value in the status column then also print Status field required.
if I set (int)$data[0]->status then Null value show as 0.so how can i solve this issues ?
A: Excel sheet import value always return in string format so you try below code
$status = $data[0]->status;
if(is_null($status)){
echo "Status field required";exit;
}else{
$status = (int)$status;
}
if($status === 0 || $status === 1){
echo "successfully";exit;
}else{
echo "status format 0 or 1 required"; exit;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54127938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Attempting to set variable based on conditional statement in Python So today is literally my first day of learning a programming language so I'm very new to Python. I'm taking the online Python for Informatics course at the University of Michigan and our first real assignment is to create a simple gross pay rate calculator.
That was simple enough so I decided I wanted to expand what the program could do to calculate net pay and account for taxes. The trouble I'm having is determining how I can dynamically (if that's even the right word) set the value of the variable "taxrate" based on a series of conditional statements.
I have yet to find the answer in searching through Python's site and Stack Overflow. I think my limited understanding of programming probably is limiting my ability to interpret properly what I have found.
Just looking for a little help:
Code:
#This program is intended to calculate the net pay of employees
#This first section includes a loop for mistakes and finds gross pay
while True:
hours = raw_input('How many hours do you work weekly?')
hours1 = float(hours)
rate = raw_input('What is your hourly rate of pay?')
rate1 = float(rate)
grosspay = hours1 * rate1
taxstatus = raw_input('Do you pay taxes?')
#This secdtion is establishing the tax bracket the user falls into
taxbracket = taxrate
if grosspay <= 1000:
taxrate = 0.90
if grosspay > range(1000,1500):
taxrate = 0.78
if grosspay >= 1501:
taxrate = 0.63
# This section is intended to calculate pay after taxes
grosspay = hours1 * rate1
if taxstatus == 'yes':
netpay = grosspay * taxrate
print'Your weekly pay after taxes is',netpay
if not taxstatus:
print grosspay
When I run this in PyCharm it lets me know that "taxrate" hasn't been defined. I ultimately want the program to set the "taxrate" based on what the users "grosspay" is. Is what I'm trying to do possible? I'm assuming it is and that I just don't understand how to do it.
Any help is greatly appreciated and in case someone is wondering what the loop is for I've got a user error checker that I'm working on after this portion of the program completes.
A: Your logic is a bit suspect in if grosspay > range(1000, 1500). What would it mean to be "greater" than a range of numbers? my guess is that the grosspay you input is, in fact, within the range [1000, 1500), so it hits this logic bug in your code and fails to assign it to anything.
The usual way to check if a number is within a range is to use the in operator.
if some_num in range(1, 10):
print("some_num is 1, 2, 3, 4, 5, 6, 7, 8, or 9")
However you'll notice that some_num MUST be contained in the integer range [1, 9] for this to trigger. If some_num is 7.5, this will fail. This is incredibly likely in the case of gross pay. What are the chances of someone's pay coming out to an exactly even dollar amount?
Instead what you could do is:
if grosspay <= 1000:
taxrate = 0.90
elif 1000 < grosspay <= 1500:
taxrate = 0.78
elif 1500 < grosspay:
taxrage = 0.63
using elif instead of a series of ifs makes the code slightly more efficient, since if/elif/else is by definition one block that is mutually exclusive. In other words:
a = 1
b = 2
if a == 1:
print("This gets done!")
if b == 2:
print("This gets done!")
if a == 1:
print("This gets done!")
elif b == 2:
print("BUT THIS DOESN'T!")
else:
print("(this doesn't either...)")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31497989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unknown permission android.permission.RECORD_VIDEO Suddenly in my logs in "warn" I've found this :
unknown permission android.permission.RECORD_VIDEO
And this happened on a device that fails to do a MediaRecorder.start() method with simple and uninformative "start fails" error message.
java.lang.RuntimeException: start failed.
at android.media.MediaRecorder.start(Native Method)
at com.vladdrummer.headsup.ScreenVideoRecorder.record(ScreenVideoRecorder.java:94)
App is working on many devices, but some have this kind of a problem - it fails to start, although , preparing went fine
So, may be theese two errors are connected? what should I do with "unknown permission android.permission.RECORD_VIDEO" ??
A: There is no permission as
android.permission.RECORD_VIDEO
See here
Ideally you should be using these permission
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Also manifest should have
<uses-feature android:name="android.hardware.Camera"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37755734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to edit a user in ASP.NET Identity I am new to the ASP.NET Identity framework and I am trying to do some things. What I want to do is to edit the user who has already register and then update the user details to the database...
Previously, I use entity framework, and then its generated my controller view and model it self. But I want to update my user details and getting a list of users into a list..
How do I do these stuff? I have seen role methods..but I never understand,
How can I do? without using role..Because, I don't need administrator purposes. Only, I want to update my user details.
A: There is a class that comes with asp.net identity called UserManager
this class will help with the user information management you can first find a user using either
*
*FindByIdAsync
*FindByEmailAsync
*FindByUserName
with the user object, you can then update it with new information for the user profile
and then use the method UpdateAsync to update the user information in the database.
when it comes to getting a list of users you can use the IdentityDbContext class to get the list of users from.
A: Create a dbcontext object "context" and you also need to create a model class "UserEdit" and include those fields in it which you wants to edit.
private ApplicationDbContext context = new ApplicationDbContext();
// To view the List of User
public ActionResult ListUsers ()
{
return View(context.Users.ToList());
}
public ActionResult EditUser(string email)
{
ApplicationUser appUser = new ApplicationUser();
appUser = UserManager.FindByEmail(email);
UserEdit user = new UserEdit();
user.Address = appUser.Address;
user.FirstName = appUser.FirstName;
user.LastName = appUser.LastName;
user.EmailConfirmed = appUser.EmailConfirmed;
user.Mobile = appUser.Mobile;
user.City = appUser.City;
return View(user);
}
[HttpPost]
public async Task<ActionResult> EditUser(UserEdit model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new UserManager<ApplicationUser>(store);
var currentUser = manager.FindByEmail(model.Email);
currentUser.FirstName = model.FirstName;
currentUser.LastName = model.LastName;
currentUser.Mobile = model.Mobile;
currentUser.Address = model.Address;
currentUser.City = model.City;
currentUser.EmailConfirmed = model.EmailConfirmed;
await manager.UpdateAsync(currentUser);
var ctx = store.Context;
ctx.SaveChanges();
TempData["msg"] = "Profile Changes Saved !";
return RedirectToAction("ListUser");
}
// for deleting a user
public ActionResult DeleteUser(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = context.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(context.Users.Find(id));
}
public async Task<ActionResult> UserDeleteConfirmed(string id)
{
var user = await UserManager.FindByIdAsync(id);
var result = await UserManager.DeleteAsync(user);
if (result.Succeeded)
{
TempData["UserDeleted"] = "User Successfully Deleted";
return RedirectToAction("ManageEditors");
}
else
{
TempData["UserDeleted"] = "Error Deleting User";
return RedirectToAction("ManageEditors");
}
}
Below is the View for ListUser:
@model IEnumerable<SampleApp.Models.ApplicationUser>
@{
ViewBag.Title = "ListUsers";
}
<div class="row">
<div class="col-md-12">
<div>
<h3>@ViewBag.Message</h3>
</div>
<div>
<h2>ManageEditors</h2>
<table class="table">
<tr>
<th>
S.No.
</th>
<th>
Email
</th>
<th>
EmailConfirmed
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Mobile
</th>
<th></th>
</tr>
@{ int sno = 1;
foreach (var item in Model)
{
<tr>
<td>
@(sno++)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailConfirmed)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Mobile)
</td>
<td>
@Html.ActionLink("Edit", "EditUser", new { email=item.Email})
@Html.ActionLink("Delete", "DeleteUser", new { id = item.Id })
</td>
</tr>
}
}
</table>
</div>
</div>
</div>
// below is my UserEdit Model
public class UserEdit
{
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Mobile")]
public string Mobile { get; set; }
[Display(Name = "Address")]
public string Address { get; set; }
[Display(Name = "City")]
public string City { get; set; }
public bool EmailConfirmed { get; set; }
}
//below is my IdentityModel.cs class which have ApplicationDbContext class
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace SampleApp.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//Extra column added to auto generated Table by Code First approach (ASPNETUSERS) by Entity Framework
public string FirstName { get; set; }
public string LastName { get; set; }
public string DOB { get; set; }
public string Sex { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Mobile { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
Hope this help you :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43362226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: ASP.NET C# OData Service + Navigation Property + $expand = null. What am I missing? I will try to explain my problem as thoroughly as possible with a simplified example. Please note that I am NOT using Entity Framework.
I have this model:
public class Person
{
[Key]
public Guid Id { get; set; }
public string GivenName { get; set; }
public string FamilyName { get; set; }
public List<Employment> Employments { get; set; }
}
public class Employment
{
public string Role { get; set; }
public Guid? ManagerId { get; set; }
public virtual Person Manager { get; set; }
}
I create an in-memory data source:
public class MyDataSource
{
private static MyDataSource instance = null;
public static MyDataSource Instance
{
get
{
if (instance == null)
{
instance = new MyDataSource();
}
return instance;
}
}
public List<Person> Persons { get; set; }
private MyDataSource()
{
this.Persons = new List<Person>();
this.Persons.AddRange(new List<Person>
{
new Person()
{
Id = Guid.Parse("00000000-0000-0000-0000-000000000001"), //Just for simplicity
GivenName = "John",
FamilyName = "Doe",
Employments = new List<Employment>()
{
new Employment()
{
Role = "Boss"
}
}
},
new Person()
{
Id = Guid.Parse("00000000-0000-0000-0000-000000000002"), //Just for simplicity
GivenName = "Clark",
FamilyName = "Kent",
Employments = new List<Employment>()
{
new Employment()
{
Role = "Worker",
ManagerId = Guid.Parse("00000000-0000-0000-0000-000000000001"), //Just for simplicity
}
}
}
});
}
}
I have this controller:
[EnableQuery]
public class PersonsController : ODataController
{
public IHttpActionResult Get()
{
return Ok(MyDataSource.Instance.Persons)
}
}
I configure the EndPoint:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapODataServiceRoute("ODataRoute", "odata", CreateEdmModel());
config.Select().Expand().Filter().OrderBy().MaxTop(null).Count()
}
public static IEdmModel CreateEdmModel()
{
var builder = new ODataConventionModelBuilder();
var persons = builder.EntitySet<Person>("Persons");
builder.ComplexType<Employment>().HasOptional(e => e.Manager, (e, p) => e.ManagerId == p.Id);
return builder.GetEdmModel();
}
}
Checking the $metadata I see this:
<NavigationProperty Name="Manager" Type = "MyNamespace.Person">
<ReferentialConstraint Property="ManagerId" ReferenceProperty="Id" />
</NavigationProperty
Everything looks fine from what I can tell but:
https://example.com/odata/persons?$expand=Employments/Manager
receives everything fine but:
Manager is null for both persons. I was expecting to see John Doe on Clark Kents employment.
What am I missing?
A: I have solved it myself.
I realised that it doesn't work like I thought and that I have to add a reference to the manager directly in MyDataSource. After that it works to $expand the manager.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66387369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HH:MM:SS:Msec to HH:MM:SS in stored procedure I have a stored procedure which update a table based on such calculation and the calculation is done as column name (Calendatedate) - (Current System Date Time) and update this information to a column (TimeSpent) and display the value in Hh:Mm:SS:Msec format.
The query is working fine but I want to update it in such a way so that the time spent should be only HH:MM:SS format. Please help me that how I remove that Msec from the time spent.
CREATE procedure St_Proc_UpdateTimeSpent
@timeEntryID int,
@status int output
as begin
set nocount on;
declare @Date dateTime;
set @Date=GETDATE();
update Production set TimeSpent=(SELECT CONVERT(VARCHAR(20),DateAdd(SS,Datediff(ss,CalendarDate, @Date)%(60*60*24),0),114)),
IsTaskCompleted=1
where productionTimeEntryID=@timeEntryID
set @status=1;
return @status;
end
A: You can just use style 108 instead of 114 in the CONVERT function to get only the hh:mm:ss:
CREATE PROCEDURE dbo.St_Proc_UpdateTimeSpent
@timeEntryID int,
@status int output
AS BEGIN
SET NOCOUNT ON;
DECLARE @Date DATETIME;
SET @Date = GETDATE();
UPDATE dbo.Production
SET TimeSpent = CONVERT(VARCHAR(20), DATEADD(SS, DATEDIFF(ss, CalendarDate, @Date)%(60*60*24),0), 108),
IsTaskCompleted = 1
WHERE
productionTimeEntryID = @timeEntryID
SET @status = 1;
RETURN @status;
END
See the excellent MSDN documentation on CAST and CONVERT for a comprehensive list of all supported styles when converting DATETIME to VARCHAR (and back)
BTW: SQL Server 2008 also introduced a TIME datatype which would probably be a better fit than a VARCHAR to store your TimeSpent values ... check it out!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11102895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Add(3)(5) nn.Sequential. How it works? class Add(nn.Module):
def __init__(self, value):
super().__init__()
self.value = value
def forward(self, x):
return x + self.value
calculator = nn.Sequential(
Add(3),
Add(2),
Add(5),
)
x = torch.tensor([1])
output = calculator(x)
print(output) # tensor([11])
I made Add Model. but I can't understand how 'nn.Sequential' works.
at the firsttime, I understood like this
add = Add(torch.tensor([1]))
add(3) # tensor([4])
add = Add(add(3))
add(2) # tensor([6])
add = Add(add(2))
add(5) # tensor([11])
but Add(3)(1) also works.
I can't understand why 'Add(3)(1)' works. help me plz
A: The core thing to remember is that when you instantiate a Module class, you are creating a callable object, i.e. something that can behave like a function.
In plain English and step by step:
*
*When you write something like add5 = Add(5), what you are doing is assigning an "instance" of the PyTorch model Add to add5
*More specifically, you are passing 5 to the Add class's __init__ method, and so its value attribute is set to 5.
*PyTorch Modules are "callable" meaning you can call them like functions. The function you call when you use an instance of a Module is that instance's forward method. So concretely, with our add5 object, if we pass a value, x = 10, by writing something like add5(10) it is like we ran x + add5.value, which equals 10 + 5 = 15.
Now putting this together, we should view the Sequential interface for building neural network models that don't have branching structures as just sequentially invoking each of the instantiated Modules' forward methods.
Omitting the definition of Add and focussing just on calculator as a series of computations we have the following (I've added the comments to show you what you should think of at each step)
calculator = nn.Sequential(
# given some input tensor x...
Add(3), # run: x = x + self.value with self.value = 3
Add(2), # run: x = x + self.value with self.value = 2
Add(5), # run: x = x + self.value with self.value = 5
)
Now we can see that it's reasonable to expect that if we pass the value 1 (albeit wrapped up as a PyTorch Tensor) we are just doing 1 + 3 + 2 + 5 which of course equals 11. PyTorch returns us back the value still as a Tensor object.
x = torch.tensor([1])
output = calculator(x)
print(output) # tensor([11])
Finally, Add(3)(5)* works for exactly this same reason! With Add(3) we are getting an instance of the Add class with the value to add being 3. We then use it immediately with the somewhat unintuitive syntax Add(3)(5) to return the value 3 + 5 = 8.
*I think you intended the capitalised class name, not an instance of the class
A: You understand it right, the Sequential class in a nutshell just calls provided modules one by one. Here's the code of the forward method
def forward(self, input):
for module in self:
input = module(input)
return input
here, for module in self just iterates through the modules provided in a constructor (Sequential.__iter__ method in charge of it).
Sequential module calls this method when you call it using () syntax.
calculator = nn.Sequential(
Add(3),
Add(2),
Add(5),
)
output = calculator(torch.tensor([1]))
But how does it work? In python, you could make objects of a class callable, if you add __call__ method to the class definition. If the class does not contain this method explicitly, it means that it possibly was inherited from a superclass. In case of Add and Sequential, it's Module class that implements __call__ method. And __call__ method calls 'public' forward method defined by a user.
It could be confusing that python uses the same syntax for the object instantiation and function or method call. To make a difference visible to the reader, python uses naming conventions. Classes should be named in a CamelCase with a first capital letter, and objects in a snake_case (it's not obligatory, but it's the rule that better to follow).
Just like in you example, Add is a class and add is a callable object of this class:
add = Add(torch.tensor([1]))
So, you can call add just like you have called a calculator in you example.
>>> add = Add(torch.tensor([1]))
>>> add(2)
Out: tensor([3])
But that won't work:
>>> add = Add(torch.tensor([1]))
>>> add(2)(1)
Out:
----> 3 add(2)(1)
TypeError: 'Tensor' object is not callable
That means that add(2) returns a Tensor object that does not implement __call__ method.
Compare this code with
>>> Add(torch.tensor([1]))(2)
Out:
tensor([3])
This code is the same as the first example, but rearranged a little bit.
--
To avoid confusion, I usually name objects differently: like add_obj = Add(1). It helps me to highlight a difference.
If you are not sure what you're working with, use functions type and isinstance. They would help to find out what's going on.
For example, if you check the add object, you could see that it's a callable object (i.e., it implements __call__)
>>> from typing import Callable
>>> isinstance(add, Callable)
True
And for a tensor:
>>> from typing import Callable
>>> isinstance(add, torch.tensor(1))
False
Hence, it will rase TypeError: 'Tensor' object is not callable in case you call it.
If you'd like to understand how python double-under methods like init or call work, you could read this page that describes python data model
(It could be a bit tedious, so you could prefer to read something like Fluent Python or other book)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70754176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DialogFragment return onClick result to MainActivity This has been asked and answered at least a dozen times yet I still can't get mine going. I've tried 4 or more of the listed answers and get no errors, a result simply isn't returned. here's the most recent code that I've tried. I really wanted this solution to work because it was the most readable to me.
I welcome any suggestions, Thanks.
MainActivity
...
private void showAlertDialog() {
FragmentManager fm = getSupportFragmentManager();
MyAlertDialogFragment alertDialog =
MyAlertDialogFragment.newInstance("Some title");
alertDialog.setTargetFragment(alertDialog, 1);
alertDialog.show(fm, "fragment_alert");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intentdata)
{
// Stuff to do, dependent on requestCode and resultCode
if(requestCode == 1) // 1 is an arbitrary number, can be any int
{
// This is the return result of your DialogFragment
if(resultCode == 1) // 1 is an arbitrary number, can be any int
{
Toast.makeText(MainActivity.this, "result received",
Toast.LENGTH_SHORT).show();
Log.d("onActivityResult", "result received" + resultCode);
}
}
}
MyDialogFragment
...
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
...
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage("Are you sure?");
alertDialogBuilder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// on success
}
});
alertDialogBuilder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getTargetFragment().onActivityResult(getTargetRequestCode(),
1, getActivity().getIntent());
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
A: I found it, added a onDialogOKPressed method to my MainActivity and put this inside the onClick of my dialog ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
so now it looks like this
MyDialogFragment
...
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage("Are you sure?");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// on success
((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getTargetFragment().onActivityResult(getTargetRequestCode(), 1, getActivity().getIntent());
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
MainActivity
...
public void onDialogOKPressed () {
// Stuff to do, dependent on requestCode and resultCode
Toast.makeText(MainActivity.this, "OK pressed", Toast.LENGTH_SHORT).show();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33378531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Bitbucket call webhook php code not executing git command and when I execute from command prompt same command runs perfectly When I commit my code form source tree bitbucket triggers a webhook that hit php code
exec('cd /d ' . $web_root_dir . ' && '. $git_bin_path . ' pull origin master');
it won't execute but when I copy the same command by copying from the log on command prompt it execute perfectly.
I've tried my heart out on this but no result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68728328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android, Java, Eclipse: Syntax Error on token "if", ( expected after this token Why do i get the following Syntax error ?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences pvtPref = getPreferences(MODE_PRIVATE);
Boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch == true) { // <<<< Syntax Error ?
// Do Something
}
}
Error:
Multiple Markers at this line
-Syntax error on token "if", ( expected after this token
-Line breakpoint:LaunchEngine[line:30] - onCreate(Bundle)
A: Try it like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences pvtPref = getPreferences(MODE_PRIVATE);
boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch) { // <<<< Syntax Error ?
// Do Something
}
}
A: Try this...
*
*First see that you have declared isFirstLaunch as boolean, if you have it should work.
*No need to use isFirstLaunch == true
if(isFirstLaunch)
A: You are getting a Boolean instead of a boolean. So you should use either :
Boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch.booleanValue()) {
}
or :
boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch) {
}
And try to click on the error icon on the left, and choose "Clear all lint marker" (if it's there).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11492657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Firefox and IE6 issue with document.ready() I have created an html page with a Tabber tab functionality.
*
*Each tab has its own table that loads when the tab is clicked and only loads once on the initial tab click to stop the tables loading more than once.
*Each tab table exists in its own .jsp html file and is loaded through javascript using the $("#tab1").load('tabqtable.jsp'); call.
I currently have a document.ready() within the individual tab html files to run when each tab loads. The scripts run and work perfectly in Chrome, but the document.ready() functions don't run in Firefox and IE6.
I can put an alert(); outside of the document.ready() function and it works, so I know the script tag is being run. I also tried moving all the javascript to the return function call in the .load() function so the javascript will run when the .load() runs successfully from the m/ain html page, but still ended up with the same result.
I am at a loss and would really appreciate some help on this issue if I could get it. The tables load perfectly, I just don't get any of the functionality I need in order to interact with the table. It's not the scripts I am running either, because they all work with the main html page. Thanks for any help in advance.
A: well it looks like you are already using a framework like jquery...use $(document).ready (assuming that's jquery you are using...) the point of frameworks like jquery is that it (in principle) should be crossbrowser compatible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3326081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to increase the base address of this string? I'm trying to get a pointer to the fourth element of this array, but I keep getting type mismatch errors when doing so. What am I doing wrong? How do I fix this?
int main()
{
char str[]="0111010";
str = str+3;
printf("%s",str);
return 0;
}
A: The line
str = str + 3;
isn't legal C code. In C, you can't assign one array variable to another. (There's no fundamental reason why the language couldn't have made this work; it's just not supported.)
That being said, the expression str + 3 is a perfectly legal expression that results in a pointer to the third (zero-indexed) element of the array. You could either print it by writing
printf("%s\n", str + 3);
or by writing
char* midPtr = str + 3;
printf("%s\n", midPtr);
Either approach works. That first one is probably easier if you just need to do this once, and the second one is a bit easier if you plan on using that pointer more than once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43088017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: alignment breaks when placed inside other container I am exploring Flexbox and am trying to align some items. The following code works and shows what I want to achieve (successful codepen here):
.labelinput {
display: flex;
flex-flow: row;
margin: 1px;
}
.labelinput > *:first-child {
flex-basis: 10em;
flex-grow: 0;
flex-shrink: 0;
}
.labelinput > *:nth-child(2) {
flex-grow: 1;
flex-shrink: 1;
border: 3px solid purple;
}
<div class='labelinput'>
<div>1st input</div>
<div>this is just a div</div>
</div>
<div class='labelinput'>
<div>2nd:</div>
<input type="text" name="foo" value="this is an input box" />
</div>
The above code produces the nicely align output shown below:
My reading of the above code is that it works because the first child in every div has a determined size (10em) and is totally inflexible (flex-grow and flex-shrink set to 0) whereas the second child has no determined size and will grow and shrink as appropriately.
What breaks though is when I try to embed the two top-level div elements (of class labelinput) into yet another container (failing codepen here):
#container {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
margin: 5px;
border: 1px solid grey;
}
.labelinput {
display: flex;
flex-flow: row;
margin: 1px;
}
.labelinput > *:first-child {
flex-basis: 7em;
flex-grow: 0;
flex-shrink: 0;
}
.labelinput > *:nth-child(2) {
flex-grow: 1;
flex-shrink: 1;
border: 3px solid purple;
}
<div id='container'>
<div class='labelinput'>
<div>1st input</div>
<div>this is just a div</div>
</div>
<div class='labelinput'>
<div>2nd:</div>
<input type="text" name="foo" value="this is the input box" />
</div>
</div>
The above produces the following unsatisfactory output:
I can't explain why this fails as I am just inserting the content of the successful case into a container that simply performs the default vertical stacking (flex-direction: column;).
By experimentation I have discovered that removing the align-items property from the outer level container (#container) fixes the problem but I can't explain that either.
I understand that the outermost container (#container) is asked to layout two other containers (of class labelinput) so whatever property I set for align-items in the outermost container should apply to the inner containers as a whole, not change the layout of their internal items.
Moreover I can't explain why the layout is changed based on the element type when there's nothing in my CSS that differentiates between items of element div versus items of element input.
A:
I can't explain why this fails as I am just inserting the content of the successful case into a container that simply performs the default vertical stacking (flex-direction: column).
The difference is that this new primary container has align-items: flex-start.
By experimentation I have discovered that removing the align-items property from the outer level container (#container) fixes the problem but I can't explain that either.
When you nest the .labelinput flex containers in the larger container (#container), then the .labelinput elements become flex items, in addition to flex containers.
Since the #container flex container is set to flex-direction: column, the main axis is vertical and the cross axis is horizontal1.
The align-items property works only along the cross axis. It's default setting is align-items: stretch2, which causes flex items to expand the full width of the container.
But when you override the default with align-items: flex-start, like in your code, you pack the two labelinput items to the start of the container, as illustrated in your problem image:
Because stretch is the default value for align-items, when you omit this property altogether, you get the behavior you want:
I understand that the outermost container (#container) is asked to layout two other containers (of class labelinput) so whatever property I set for align-items in the outermost container should apply to the inner containers as a whole, not change the layout of their internal items.
The outermost container is not changing the layout of the inner container's children. At least not directly.
The align-items: flex-start rule on the outermost container is applying directly to the inner containers. The internal items of the inner containers are just responding to the sizing adjustment of their parent.
Here's an illustration of align-items: flex-start impacting .labelinput (red borders added).
#container {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
margin: 5px;
border: 1px solid grey;
}
.labelinput {
display: flex;
flex-flow: row;
margin: 1px;
border: 2px dashed red;
}
.labelinput > *:first-child {
flex-basis: 7em;
flex-grow: 0;
flex-shrink: 0;
}
.labelinput > *:nth-child(2) {
flex-grow: 1;
flex-shrink: 1;
border: 3px solid purple;
}
<div id='container'>
<div class='labelinput'>
<div>1st input</div>
<div>this is just a div</div>
</div>
<div class='labelinput'>
<div>2nd:</div>
<input type="text" name="foo" value="this is the input box" />
</div>
</div>
Moreover I can't explain why the layout is changed based on the element type when there's nothing in my CSS that differentiates between items of element div versus items of element input.
There may be no difference between div and input in your code, but there are intrinsic differences.
Unlike a div, an input element has a minimum width set by the browser (maybe to always allow for character entry).
You may be able to reduce the input width by applying min-width: 0 or overflow: hidden3.
Footnotes
1. Learn more about flex layout's main axis and cross axis here: In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?
2. Learn more about the align-items property in the spec: 8.3. Cross-axis Alignment: the align-items and align-self properties
3. Why doesn't flex item shrink past content size?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40476931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: proportion data frame for each factor level based on another column I would like to summarize a data frame by month where each column is the proportion of each factor level based on the Records column in the data frame below. I have been attempting to use dplyr but haven't quite figured it out.
library(dplyr)
set.seed(100)
df=data.frame(Month=rep(c("1/1/2017","2/1/2017","3/1/2017","4/1/2017","5/1/2017","6/1/2017","7/1/2017",
"8/1/2017","9/1/2017","10/1/2017","11/1/2017","12/1/2017"),10),
Records=round(runif(120,6000,10000),0),
V1=as.factor(sample(c("T","F"),120,replace=TRUE)),
V2=as.factor(sample(c("A","B","C"),120,replace=TRUE)),
V3=as.factor(sample(c("X","Y","Z","W"),120,replace=TRUE)),
V4=as.factor(sample(c("YES","NO","Maybe"),120,replace=TRUE)))
Here is what I would like the output to be
> dput((resultsdf))
structure(list(Month = c("1/1/2017", "2/1/2017", "3/1/2017",
"4/1/2017", "5/1/2017", "6/1/2017", "7/1/2017", "8/1/2017", "9/1/2017",
"10/1/2017", "11/1/2017", "12/1/2017"), V1.F = c(0.4, 0.71, 0.63,
0.35, 0.37, 0.41, 0.37, 0.61, 0.29, 0.5, 0.38, 0.82), V2.T = c(0.6,
0.29, 0.37, 0.65, 0.63, 0.59, 0.63, 0.39, 0.71, 0.5, 0.62, 0.18
), V2.A = c(0.2, 0.28, 0.3, 0.31, 0.29, 0.3, 0.32, 0.45, 0.1,
0.41, 0.3, 0.11), V2.B = c(0.59, 0.33, 0.19, 0.5, 0.51, 0.19,
0.59, 0.22, 0.77, 0.2, 0.41, 0.16), V2.C = c(0.22, 0.38, 0.51,
0.19, 0.21, 0.51, 0.09, 0.32, 0.12, 0.39, 0.29, 0.73), V3.W = c(0.42,
0.11, 0, 0.21, 0.23, 0.3, 0.12, 0.45, 0.32, 0.28, 0.19, 0.19),
V3.X = c(0.19, 0.32, 0.18, 0.19, 0.19, 0.11, 0.19, 0, 0.27,
0.11, 0.23, 0.19), V3.Y = c(0.3, 0.29, 0.39, 0.4, 0.18, 0.4,
0.62, 0.34, 0.21, 0.33, 0.21, 0.1), V3.Z = c(0.09, 0.28,
0.43, 0.2, 0.4, 0.19, 0.07, 0.2, 0.2, 0.29, 0.38, 0.53),
V4.Maybe = c(0.4, 0.23, 0.39, 0.38, 0.62, 0.5, 0.2, 0.4,
0.4, 0.32, 0.3, 0.49), V4.NO = c(0.32, 0.5, 0.39, 0.31, 0.18,
0.29, 0.22, 0.42, 0.29, 0.3, 0.44, 0.3), V4.YES = c(0.28,
0.27, 0.22, 0.31, 0.2, 0.21, 0.58, 0.18, 0.3, 0.39, 0.26,
0.22)), row.names = c(NA, -12L), class = c("tbl_df", "tbl",
"data.frame"), spec = structure(list(cols = list(Month = structure(list(), class = c("collector_character",
"collector")), V1.F = structure(list(), class = c("collector_double",
"collector")), V2.T = structure(list(), class = c("collector_double",
"collector")), V2.A = structure(list(), class = c("collector_double",
"collector")), V2.B = structure(list(), class = c("collector_double",
"collector")), V2.C = structure(list(), class = c("collector_double",
"collector")), V3.W = structure(list(), class = c("collector_double",
"collector")), V3.X = structure(list(), class = c("collector_double",
"collector")), V3.Y = structure(list(), class = c("collector_double",
"collector")), V3.Z = structure(list(), class = c("collector_double",
"collector")), V4.Maybe = structure(list(), class = c("collector_double",
"collector")), V4.NO = structure(list(), class = c("collector_double",
"collector")), V4.YES = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector"))), class = "col_spec"))
A: Please check your expected output. I believe there are some mistakes.
Here is a tidyverse option:
library(tidyverse)
df %>%
gather(key, value, -Month, -Records) %>%
group_by(Month, key, value) %>%
summarise(freq = n()) %>%
mutate(freq = freq / sum(freq)) %>%
unite(col, key, value, sep = ".") %>%
spread(col, freq)
## A tibble: 12 x 13
## Groups: Month [12]
# Month V1.F V1.T V2.A V2.B V2.C V3.W V3.X V3.Y V3.Z V4.Maybe V4.NO
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1/1/… 0.4 0.6 0.2 0.6 0.2 0.4 0.2 0.3 0.1 0.4 0.3
# 2 10/1… 0.5 0.5 0.4 0.2 0.4 0.3 0.1 0.3 0.3 0.3 0.3
# 3 11/1… 0.4 0.6 0.3 0.4 0.3 0.2 0.2 0.2 0.4 0.3 0.4
# 4 12/1… 0.8 0.2 0.1 0.2 0.7 0.2 0.2 0.1 0.5 0.5 0.3
# 5 2/1/… 0.7 0.3 0.3 0.3 0.4 0.1 0.3 0.3 0.3 0.2 0.5
# 6 3/1/… 0.6 0.4 0.3 0.2 0.5 NA 0.2 0.4 0.4 0.4 0.4
# 7 4/1/… 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.4 0.2 0.4 0.3
# 8 5/1/… 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.2 0.4 0.6 0.2
# 9 6/1/… 0.4 0.6 0.3 0.2 0.5 0.3 0.1 0.4 0.2 0.5 0.3
#10 7/1/… 0.4 0.6 0.3 0.6 0.1 0.1 0.2 0.6 0.1 0.2 0.2
#11 8/1/… 0.6 0.4 0.5 0.2 0.3 0.5 NA 0.3 0.2 0.4 0.4
#12 9/1/… 0.3 0.7 0.1 0.8 0.1 0.3 0.3 0.2 0.2 0.4 0.3
## ... with 1 more variable: V4.YES <dbl>
A: Here is an alternative approach which uses the table() and prop.table() functions from base R and dcast() for reshaping to wide format. Unfortunately, I am not fluently enough in dplyr so I resort to data.table for grouping.
library(data.table)
library(magrittr)
setDT(df)[, lapply(.SD, function(.x) table(.x) %>% prop.table %>% as.data.table) %>%
rbindlist(idcol = TRUE), .SDcols = V1:V4, by = Month] %>%
dcast(Month ~ .id + .x)
Month V1_F V1_T V2_A V2_B V2_C V3_W V3_X V3_Y V3_Z V4_Maybe V4_NO V4_YES
1: 1/1/2017 0.4 0.6 0.2 0.6 0.2 0.4 0.2 0.3 0.1 0.4 0.3 0.3
2: 10/1/2017 0.5 0.5 0.4 0.2 0.4 0.3 0.1 0.3 0.3 0.3 0.3 0.4
3: 11/1/2017 0.4 0.6 0.3 0.4 0.3 0.2 0.2 0.2 0.4 0.3 0.4 0.3
4: 12/1/2017 0.8 0.2 0.1 0.2 0.7 0.2 0.2 0.1 0.5 0.5 0.3 0.2
5: 2/1/2017 0.7 0.3 0.3 0.3 0.4 0.1 0.3 0.3 0.3 0.2 0.5 0.3
6: 3/1/2017 0.6 0.4 0.3 0.2 0.5 0.0 0.2 0.4 0.4 0.4 0.4 0.2
7: 4/1/2017 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.4 0.2 0.4 0.3 0.3
8: 5/1/2017 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.2 0.4 0.6 0.2 0.2
9: 6/1/2017 0.4 0.6 0.3 0.2 0.5 0.3 0.1 0.4 0.2 0.5 0.3 0.2
10: 7/1/2017 0.4 0.6 0.3 0.6 0.1 0.1 0.2 0.6 0.1 0.2 0.2 0.6
11: 8/1/2017 0.6 0.4 0.5 0.2 0.3 0.5 0.0 0.3 0.2 0.4 0.4 0.2
12: 9/1/2017 0.3 0.7 0.1 0.8 0.1 0.3 0.3 0.2 0.2 0.4 0.3 0.3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52573655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to write to file in C++ without locking it? C++ In Windows 7.
When writing to my log file, i sometimes set a breakpoint, or the program gets stuck at something. When i try too peek in my logfile from another program it says "The file cannot be opened because it is in use by another process". Well thats true, however I've worked with other programs that still allows reading from a logfile while they are writing to it, so I know it should be possible. Tried the _fsopen and unlocking the file but without success.
FILE* logFile;
//fopen_s(&logFile, "log.log", "w");
logFile = _fsopen("log.log", "w", _SH_DENYNO);
if (!logFile)
throw "fopen";
_unlock_file(logFile);
A: If you have the log-file open with full sharing-mode, others are still stopped from opening for exclusive access, or with deny-write.
Seems the second program wants more access than would be compatible.
Also, I guess you only want to append to the log, use mode "a" instead of "w".
Last, do not call _unlock_file unless you called _lock_file on the same file previously.
There is a way to do what you want though:
Open your file without any access, and then use Opportunistic Locks.
Raymond Chen's blog The Old New Thing also has a nice example: https://devblogs.microsoft.com/oldnewthing/20130415-00/?p=4663
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26198169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: in Unix concatenation of two variables i have a file C20140728 I want a variable which will store C and other varibale which will store 20140728(here second variable is current systemdate in %Y%m%d format) and third variable when I echo should concatenatae and show C20140728
A: In general to concatenate two variables you can just write them one after another:
a='C'
b='20140728'
c=$a$b
edit:
to get the current date
b = $(date +'%Y%m%d')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25013796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the maximum value(s) in a (seaborn) JointKDE plot? How do I get the maximum value(s) in a (seaborn) JointKDE plot? Like the image below. I want to get the blue points coordinate like (121.53,31.29) and (121.58,31.27)。
Thanks a lot!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64019217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: c++ - char const * const * - I have a variable that is a pointer to a constant pointer to a constant char.
char const * const * words;
I then add the word "dog" to that variable.
words = (char const * const *)"dog";
However, when when I debug the code, it states this about words:
{0x616d7251 Error reading characters of string.}
My question is, how would I properly access the characters of that variable to the point where I can record each individual character of the string.
Here is some example code below:
char const * const *words;
words = (char const * const *)"dog";
for (int i = 0; i < 5; ++i)
{
char c = (char)words[i]; // Gives me, -52'i symbol', 'd', and then '\0'
// How do I access the 'o' and 'g'?
}
Thanks for the help in advance.
A: maybe you mean this
char const * const words = "dog";
for (int i = 0; i < strlen(words); ++i)
{
char c = words[i];
}
now of course in c++ code you should realy be using std::string
A: You are consistently missing the second *.
Ignoring the const stuff, you are declaring a char** word, which is a pointer to a pointer to a single char. You won't get a word or many words into that, and casting just hides the problem.
To get "dog" accessible through such a pointer, you need to take an extra step; make a variable that contains "dog", and put its address into your word.
A: Short answer:
Your program has undefined behavior. To remove the undefined behavior use:
char const * word = "dog";
for (int i = 0; i < std::strlen(word); ++i)
{
char c = word[i];
}
or
char const * word = dog;
char const * const *words = &word;
for (int i = 0; i < std::strlen(*words); ++i)
{
char c = (*words)[i];
}
Long answer:
You are forcing a cast from char const* to char const* const* and treating the location of memory that was holding chars as though it is holding char const*s. Not only that, you are accessing memory using an out of bounds index.
Let's say the string "dog" is held in some memory location as (it takes four bytes that includes the null character) and give it an address.
a1
|
v
+---+---+---+----+
| d | o | g | \0 |
+---+---+---+----+
You can treat the address a1 as the value of a pointer of type char const*. That won't be a problem at all. However, by using:
words = (char const * const *)"dog";
You are treating a1 as though it is holding objects of type char const*.
Let's assume for a moment that you have a machine that uses 4 bytes for a pointer and uses little endian for pointers.
words[0] evaluates to a pointer. Its value will be:
'd' in decimal +
256 * 'o' in decimal +
256*256 * 'g' in decimal +
256*256*256 * '\0' in decimal.
After that, you truncate that value to char, which will give you back the character d, which is not too bad. The fun part (undefined behavior) begins when you access words[1].
words[1] is same as *(words+1). words+1 evaluates to a pointer whose value is the address a2.
a2
|
v
+---+---+---+----+
| d | o | g | \0 |
+---+---+---+----+
As you can see, it points to memory that is beyond what the compiler allocated for you. Dereferencing that pointer is cause for undefined behavior.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48567148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I want to make the spline chart from highcharts.com smaller in size I want to minify the chart Interface. Currently I am using chart with size 600 x 300 px, which is working fine.
Now I want to show 3 charts at the same place so in order to save space. I want to show 3 charts thumbnails (working charts). If user click on any chart it should appear as full chart. I can show it on the popup or expand it on the page itself.
I checked the Highchart website. It provide option to resize chart using height & width properties.
http://api.highcharts.com/highcharts/chart.height
http://api.highcharts.com/highcharts/chart.width
This option do not actually resize the chart. Char layout get smaller but the title label stay at the same size. I want chart to resize and work in a smaller version with text and chart show in smaller box like 100 x 100 px.
I can use chart.setSize(); function to resize the chart.
Does it make any sense? Please guide me.
I am using highcharts 5.0 version js file.
Here is my code:
var seriesData1 = {
name: "Series1Label",
data: Series1Data
},
seriesData2 = {
"name": "Series2Label",
"data": Series2Data
},
seriesData3 = {
"name": "Series3Label",
"data": Series3Data
},
completedData = [seriesData2, seriesData3, seriesData1];
var elem = par.find('<some class>');
elem.highcharts({
chart: {
type: 'areaspline'
},
colors: ['#21d0b8', '#2248B5', '#5B82A1'],
title: {
text: ""
},
legend: {
layout: 'horizontal',
align: 'left',
verticalAlign: 'top',
useHTML: true,
itemDistance: 5,
},
xAxis: {
'title': {
text: xAxisTitle
},
categories: categories,
tickmarkPlacement: 'on',
title: {
enabled: false
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
shared: true
},
credits: {
enabled: false
},
plotOptions: {
series: {
events: {
legendItemClick: function(event) {
}
}
},
areaspline: {
fillOpacity: 0.8
},
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: completedData,
exporting: {
buttons: {
contextButton: {
text: 'Export',
useHTML: true,
align: 'right',
symbolY: 15,
}
}
},
responsive: {
rules: [{
condition: {
maxWidth: 100
},
chartOptions: {
legend: {
align: 'center',
verticalAlign: 'bottom',
layout: 'horizontal'
},
yAxis: {
gridLineWidth: 0,
minorGridLineWidth: 0,
labels: {
enabled:false,
},
title: {
text: null
}
},
xAxis: {
labels: {
enabled:false,
},
title: {
text: null
}
},
title:{
text: '',
},
subtitle: {
text: null
},
tooltip:{
enabled:false,
},
legend:{
enabled:false,
},
credits: {
enabled: false
}
}
}]
}
});
The 'elem' chart element occurs 7 times on a single page, so I have made a single code to fill all the charts on different data and trigger them all at single function.
I need all the 7 charts to show in thumbnail and show certain chart in large size on user click.
using your example when I update my code.
var getChart = ele_.highcharts({.....});
Resize code:
getChart.setSize(100, 100);
Error encountered
getChart.setSize is not a function
Can anyone guide me how to fix this issue?
A: check responsive and set rules accordingly.
For 100 by 100 you should remove all gridlines, credits, labels, title
Example will be
Highcharts.chart('container', {
chart: {
type: 'line',
width: 100,
height: 100
},
legend: {
align: 'center',
verticalAlign: 'bottom',
layout: 'horizontal'
},
yAxis: {
gridLineWidth: 0,
minorGridLineWidth: 0,
labels: {
enabled: false,
},
title: {
text: null
}
},
xAxis: {
labels: {
enabled: false,
},
title: {
text: null
}
},
title: {
useHTML: true,
text: ''
},
subtitle: {
text: null
},
tooltip: {
enabled: false,
},
legend: {
enabled: false,
},
credits: {
enabled: false
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
$('#container').highcharts().renderer.text('mini Highcharts', 20, 90)
.css({
fontSize: '8px',
color: '#7d7d7d'
})
.add();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px"></div>
check this using chart.setSize();
Fiddle
Update
You could use $(elem).highcharts().setSize(100, 100);
Updated fiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46620911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pagination. Why only one page is showing? I have been trying to get pagination to work and I have to a certain extent but it only shows one page of results.
I have 18 listings in my database and have it set to show 6 per page.
Can anyone see what the problem is?
<?php include('includes/configsql.php');
//include header template
include('layout/header.php');
//include navbar template
include('layout/navbar.php');
?>
<?php
$con = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
$sql = "SELECT COUNT(id) FROM basic WHERE status='active'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$rows = mysqli_num_rows($query);
$page_rows = 6;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT id, name, address, telephone, email, category FROM basic WHERE status='active' ORDER BY name ASC $limit";
$query = mysqli_query($con, $sql);
$textline1 = "Basic Listing (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'">Previous</a> ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <a href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">Next</a> ';
}
}
$list = '';
while($row = mysqli_fetch_array($query)){
$id = $row["id"];
$name = $row["name"];
$category = $row["category"];
$list .= '<p><a href="business.php?id='.$id.'">'.$name.' | '.$category.' </a> - Click the link to view this business</p>';
}
mysqli_close($con);
?>
<div id="wrapper">
<div id="bizlist">
<div id="pagination">
<h2><?php echo $textline1; ?></h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $list; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</div>
<?php
//include footer template
include('layout/footer.php');
?>
A: I think you have to remove the line:
$rows = mysqli_num_rows($query);
It is in beginning of the script.
Another way is if you modify the first line like this:
$sql = "SELECT * FROM basic WHERE status='active'";
And remove the next 3 rows
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
You have to choice one of above, but not both :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29729569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular-fullstack get current user ID I'm using https://github.com/DaftMonk/generator-angular-fullstack.
I have 2 schemas:
*
*charts
*
*title: String
*datasets: Array
*_creator: logged in user ID
*users
*
*name
*email
*_id
When I console.log the current user returns
$scope.getCurrentUser = Auth.getCurrentUser();
console.log($scope.getCurrentUser);
But when I try to console log the _id:
$scope.getCurrentUser = Auth.getCurrentUser();
console.log($scope.getCurrentUser._id);
Returns
undefined
Can someone explain what I'm doing wrong?
A: Objects in chrome console get evaluated only when they are first opened.
This means that when you console.log an object like the return value of Auth.getCurrentUser(), the console displays a reference to it - this at the time of the log call contains a promise object, but it's most likely resolved by the time you open it on the console, so you see the property you're looking for.
On the other hand, when you're logging $scope.getCurrentUser._id, that's the result of a property lookup on the promise object - and it prints the current value of the property, which is undefined.
A note about clean code: your scope variable is called getCurrentUser, which makes one think it's a getter function, but it is infact the return value of a getter function. This is confusing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28966023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Permutations of a list with constraints python I am desperately trying to get all the permutations of a list while enforcing position assignment constraints.
I have a list [1,2,3,4,5,6] (6 is just an example, I would like to find something that could work with every lenght) and I want to find all the lists of lenght 3 (also an example) with the following constraints :
*
*position 1 can be occupied by numbers 1 and 2
*position 2 can be occupied by numbers 1,2 and 3
*position 3 can be occupied by numbers 2,3 and 4
*repetions of a same number are not allowed
That would give these lists : [1,2,3],[1,2,4],[1,3,2],[1,3,4],[2,1,3],[2,3,4],[2,1,4]
For those interested, what I am trying to implement is what is explained pages 5 and 6 of this paper
A: Filter the product() of those subsets:
from itertools import product
for combo in product([1, 2], [1, 2, 3], [2, 3, 4]):
if len(set(combo)) == 3:
print(combo)
or as a list comprehension:
[combo for combo in product([1, 2], [1, 2, 3], [2, 3, 4]) if len(set(combo)) == 3]
Output:
>>> from itertools import product
>>> [combo for combo in product([1, 2], [1, 2, 3], [2, 3, 4]) if len(set(combo)) == 3]
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (2, 1, 3), (2, 1, 4), (2, 3, 4)]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41409481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Lazy Deferred List reaching maximum recursion depth I have a large list of documents to upsert into MongoDB (possibly n > 100000). I don't want to create 100000 deferreds all at once, but I don't want to execute and wait for each query sequentially because I have a connection pool to MongoDB and I want to utilize it fully. So I have a generator function that will yield deferreds to be consumed by a DeferredLazyList.
def generate_update_deferreds(collection, many_docs):
for doc in many_docs:
d = collection.update({'_id': doc['_id']}, doc, upsert=True)
yield d
This is the code linking the generation of the deferred upserts, and the DeferredLazyList.
@defer.inlineCallbacks
def update_docs(collection, many_docs):
gen_deferreds = generate_update_deferreds(collection, many_docs)
results = yield DeferredLazyList(gen_deferreds, count=pool_size, consume_errors=True)
The DeferredLazyList is similar to DeferredList, but instead of accepting a list of deferreds to wait for it accepts an iterator. The deferreds are retrieved from the iterator while only having count deferreds active simultaneously. This is used to effectively batch deferreds because they are created as they are yielded.
class DeferredLazyList(defer.Deferred):
"""
The ``DeferredLazyList`` class is used for collecting the results of
many deferreds. This is similar to ``DeferredList``
(``twisted.internet.defer.DeferredList``) but works with an iterator
yielding deferreds. This will only maintain a certain number of
deferreds simultaneously. Once one of the deferreds finishes, another
will be obtained from the iterator.
"""
def __init__(self, deferreds, count=None, consume_errors=None):
defer.Deferred.__init__(self)
if count is None:
count = 1
self.__consume_errors = bool(consume_errors)
self.__iter = enumerate(deferreds)
self.__results = []
for _i in xrange(count):
# Start specified number of simultaneous deferreds.
if not self.called:
self.__next_save_result(None, None, None)
else:
break
def __next_save_result(self, result, success, index):
"""
Called when a deferred completes.
"""
# Make sure we can save result at index.
if index is not None:
results_len = len(self.__results)
if results_len <= index:
self.__results += [NO_RESULT] * (index - results_len + 1)
# Save result.
self.__results[index] = (success, result)
# Get next deferred.
try:
i, d = self.__iter.next()
d.addCallbacks(self.__next_save_result, self.__next_save_result, callbackArgs=(True, i), errbackArgs=(False, i))
except StopIteration:
# Iterator is exhausted, callback self with results.
self.callback(self.__results)
# Pass through result.
return result if success or not self.__consume_errors else None
The problem is when the deferreds are yielded from generate_update_deferreds() their .called is already set to True which is causing DeferredLazyList to recursively call itself.
What's happening is:
*
*In DeferredLazyList.__init__(), self.__next_save_result() is called count times (say 5).
*Each call to self.__next_save_result() consumes 1 deferred from self.__iter, and itself is added as a callback.
*Because the yielded deferred has .called set to True, d.addCallbacks(self.__next_save_result, ...) immediately calls self.__next_save_result() and this loop continues until a RuntimeError is raised because recursion depth has been reached.
I've printed a stacktrace before the recursion limit was reached to confirm that this is the cause of the problem:
File "/home/caleb/it/Development/projects/python/amazon/bin/feeds-daemon/lib/server.py", line 937, in update_many_docs
results = yield DeferredLazyList(gen_deferreds, count=self.mongo_connections, consume_errors=True, return_results=True)
File "/home/caleb/it/Development/projects/python/amazon/bin/feeds-daemon/lib/twisted.py", line 157, in __init__
self.__next_save_result(None, None, None)
File "/home/caleb/it/Development/projects/python/amazon/bin/feeds-daemon/lib/twisted.py", line 222, in __next_save_result
d.addCallbacks(self.__next_save_result, self.__next_save_result, callbackArgs=(True, i), errbackArgs=(False, i))
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 290, in addCallbacks
self._runCallbacks()
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 551, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/caleb/it/Development/projects/python/amazon/bin/feeds-daemon/lib/twisted.py", line 222, in __next_save_result
d.addCallbacks(self.__next_save_result, self.__next_save_result, callbackArgs=(True, i), errbackArgs=(False, i))
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 290, in addCallbacks
self._runCallbacks()
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 551, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/caleb/it/Development/projects/python/amazon/bin/feeds-daemon/lib/twisted.py", line 222, in __next_save_result
d.addCallbacks(self.__next_save_result, self.__next_save_result, callbackArgs=(True, i), errbackArgs=(False, i))
# Repeated until the RuntimeError
exceptions.RuntimeError: maximum recursion depth exceeded
Any help would be greatly appreciated. By the way, I am running Python 2.7.3 with Twisted 12.1.0 and the MongoDB stuff is really only relevant to understand the context.
I wanted the result from each deferred, but cooperate() doesn't return those so I added a callback to each deferred before yielding them to the CooperativeTasks:
from twisted.internet.defer import DeferredList, inlineCallbacks
from twisted.internet.task import cooperate
NO_RESULT = object()
def generate_update_deferreds(collection, many_docs, save_results):
for i, doc in enumerate(update_docs):
d = collection.update({'_id': doc['_id']}, doc, upsert=True)
d.addBoth(save_result, i, save_results) # Save result
yield d
def save_result(result, i, save_results):
save_results[i] = result
@inlineCallbacks
def update_docs(collection, many_docs):
save_results = [NO_RESULT] * len(many_docs)
gen_deferreds = generate_update_deferreds(collection, many_docs, save_results))
workers = [cooperate(gen_deferreds).whenDone() for _i in xrange(count)]
yield defer.DeferredList(workers)
# Handle save_results...
A: There are some tools in Twisted that will help you do this more easily. For example, cooperate:
from twisted.internet.task import cooperate
def generate_update_deferreds(collection, many_docs):
for doc in update_docs:
d = collection.update({'_id': doc['_id']}, doc, upsert=True)
yield d
work = generate_update_deferreds(...)
worker_tasks = []
for i in range(count):
task = cooperate(work)
worker_tasks.append(task)
all_done_deferred = DeferredList([task.whenDone() for task in worker_tasks])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15626076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Linq Group By With Having Here is my example:
class test{
public DateTime dt;
public double value;
public int id;
}
i have:
IEnumerable<Test> TestList;
I want select rows from it, with group by id, with max(dt).
my query:
var q = from p in TestList
group p by p.id
into g
select new { id = g.Key, dt = g.Max(w => w.dt) });
In result i have anonyoumus class with {id_param,dt}, but i want to have field "value" too, like {id,dt,value},how can i do it?
A: You have to group by all fields that are not aggregated. So value needs to be summed up or grouped by.
Try:
var result = TestList
.GroupBy(t => t.id)
.Select(g => new { id = g.Key, g.OrderByDescending(c => c.dt).First().dt, g.OrderByDescending(c => c.dt).First().value });
A: Based on comments and the question, you want: for each distinct id, the instance with the maximum dt.
I would add a help method: MaxBy which allows a whole object to be selected based on the value of a function1:
public static T MaxBy<T,TValue>(this IEnumerable<T> input, Func<T,TValue> projector)
where TValue : IComparable<TValue> {
T found = default(T);
TValue max = default(TValue);
foreach (T t in input) {
TValue p = projector(t);
if (max.CompareTo(p) > 0) {
found = t;
max = p;
}
}
return found;
}
And then the query becomes:
var q = from p in TestList
group p by p.id into g
select g.MaxBy(w => w.dt);
NB. this implementation of MaxBy will only work for objects where the value of the member being compared is greater than its type's default value (e.g. for int: greater than zero). A better implementation of MaxBy would use the enumerator manually and initialise both found and max variables directly from the first element of the input.
1 if you are using The Reactive Extensions (Rx) this is included in the System.Interactive assembly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3870884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to mock an object with a function that has a callback? I have this simple method that i'm trying to test.
function isS3Healthy(s3, logger = console) {
return new Promise((resolve, reject) => {
s3.listObjects({}, (err, data) => {
if (err) {
logger.error(err)
return resolve(['s3', false])
}
return resolve(['s3', true])
})
})
}
My test keeps timing out and it has to do with my mocked object isn't right. What does this mock object need to look like in order to test my method properly?
describe.only('#isS3Healthy', () => {
let s3
before(() => {
s3 = {
listObjects: ({}, (err, data) => {
return Promise.resolve(['s3', true])
})
}
})
it('should return that it is healthy', () => {
return isS3Healthy(s3)
.then(result => {
const [name, status] = result
expect(name).to.equal('s3')
expect(status).to.be.true
})
.catch(err => {
console.log('err = ', err)
})
})
})
A: Based on the code you've provided, it looks like listObjects is a function that accepts an object and a callback, and at some point calls that callback, so probably the simplest way to mock it would be like this:
listObjects: (_, c) => c()
The function you're testing only seems to care whether listObjects is passing an error to the callback or not, so this should seemingly be sufficient.
Side note: you have return resolve in two places in your isS3Healthy function, but using return here almost certainly serves no purpose. To resolve a promise, just call resolve(...) without returning it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54892171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to start up MySQL Instance before Apache Instance on Scalr? I am using Scalr for scaling the website server.
On the Apache server, I have installed Sakai, and created an boot-up script for Linux machine.
The question is, how can I ensure that MySQL Instance is booted up and running before the Apache server is booted up, because if Apache server gets booted up first, then the connection for running Sakai will fail, and that causes all sorts of problems.
How I can ensure the instance start at the way I need it to start? I am still new to Scalr so any help would be appreciated.
Thanks
A: If you wrote the Apache startup-script yourself, you can include a check if the database instance is already running.
You can include a simple wait-loop:
MYSQL_OK=1
while ["$MYSQL_OK" -ne 0] ; do
echo "SELECT version();" | mysql -utestuser -ptestpassword testdb
MYSQL_OK=$?
sleep 5
done
Obivously you have to create some testuser and the test-database in Mysql:
CREATE DATABASE testdb;
GRANT USAGE,SELECT ON testdb.* TO 'testuser'@'localhost' IDENTIFIED BY 'testpassword';
FLUSH PRIVILEGES;
Simply put the while-loop somewhere in the start) part of your script. If your system is some kind of Redhat-system, you will notice that the start-script /etc/init.d/httpd has a line like this:
Required-Start: $local_fs $remote_fs $network $named
If you add $mysqld to that line, Apache will insist on a running mysqld before startup:
Required-Start: $local_fs $remote_fs $network $named $mysqld
However, the disadvantage is that the Apache startup will fail instead of waiting for running mylsqd.
Good luck,
Alex.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5506821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I dynamically change ng-grid table size when parent containing div size changes? I am changing the size of the containing div using ng-class and an expression that evaluates whether or not an edit form is displayed. If the edit form is displayed I want to change the size of the div containing the ng-grid and the ng-grid itself.
<div class=" row-fluid">
<div ng-class="{'span7' : displayEditForm == true, 'span12': displayEditForm == false}" >
<ul class="nav nav-tabs" style="margin-bottom: 5px;">
<li class="active"><a href="#" ng-click="getActivitiesThatNeedMyApproval()" data-toggle="tab">Activities Needing My Approval</a></li>
<li><a href="#" ng-click="getMyActivitiesNeedingApproval()" data-toggle="tab">My Activities Needing Approval </a></li>
<li><a href="#" ng-click="getMyActivities()" data-toggle="tab">My Activities</a></li>
</ul>
<div class="edus-admin-manage-grid span12" style="margin-left:0;" ng-grid="gridOptions"></div>
</div>
<div class="span5" ng-show="displayEditForm">
<div class="edus-activity-container">
<div class="edus-admin-activities-grid">
<div ng-include="'/partials/' + activity.object.objectType + '.html'" class="edus-activity"></div>
<!-- <div ng-include="'/partials/admin-activity-actions.html'"></div>-->
</div>
</div>
<div ng-include="'/partials/admin-edit-activity-grid-form.html'"></div>
</div>
</div>
The div containing the navbar and grid changes size via ng-class (from span12 to span7), but the ng-grid does not refresh. How can I trigger the refresh of ng-grid given the change in the parent div?
I've included my gridOptions below:
$scope.gridOptions = {
plugins: [gridLayoutPlugin],
data : 'activities',
showFilter: true,
/* enablePaging: true,*/
showColumnMenu: true,
/* showFooter: true,*/
rowHeight: 70,
enableColumnResize: true,
multiSelect: false,
selectedItems: $scope.selectedActivities,
afterSelectionChange: function(rowItem,event){
if($scope.selectedActivities && $scope.selectedActivities.length > 0){
$scope.activity = $scope.selectedActivities[0];
$scope.activityViewState.index = $scope.activities.indexOf($scope.activity);
$scope.displayEditForm = true;
console.log("DEBUG :::::::::::::::: updated displayEditForm.", $scope.displayEditForm);
if($scope.activity.ucdEdusMeta.startDate) {
// $scope.activity.ucdEdusMeta.startDate = new Date($scope.activity.ucdEdusMeta.startDate);
$scope.edit.startDate = moment($scope.activity.ucdEdusMeta.startDate).format("MM/DD/YYYY");
$scope.edit.startTime = moment($scope.activity.ucdEdusMeta.startDate).format("hh:mm A");
}
if($scope.activity.ucdEdusMeta.endDate) {
// $scope.activity.ucdEdusMeta.endDate = new Date($scope.activity.ucdEdusMeta.endDate);
$scope.edit.endDate = moment($scope.activity.ucdEdusMeta.endDate).format("MM/DD/YYYY");
$scope.edit.endTime = moment($scope.activity.ucdEdusMeta.endDate).format("hh:mm A");
}
}
},
/* pagingOptions: { pageSizes: [5, 10, 20], pageSize: 10, totalServerItems: 0, currentPage: 1 },*/
columnDefs: [
{field: 'title', displayName: 'Title', width:'15%',
cellTemplate: '<div class="ngCellText", style="white-space: normal;">{{row.getProperty(col.field)}}</div>'},
{field: 'actor.displayName', displayName: 'DisplayName', width:'10%',
cellTemplate: '<div class="ngCellText", style="white-space: normal;">{{row.getProperty(col.field)}}</div>'},
{field: 'object.content', displayName:'Content', width:'35%',
cellTemplate: '<div class="ngCellText", style="white-space: normal;">{{row.getProperty(col.field)}}</div>'},
{field: 'ucdEdusMeta.startDate', displayName: 'Start Date', width:'20%',
cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{row.getProperty(col.field) | date:"short"}} </span></div>'},
{field: 'ucdEdusMeta.endDate', displayName: 'End Date', width:'20%',
cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{row.getProperty(col.field) | date:"short"}} </span></div>'}
// {field: '', displayName: ''},
]
};
Here's the CSS used by the grid:
.edus-admin-manage-grid {
border: 1px solid rgb(212,212,212);
width: 100%;
height: 700px
}
A: You can use ng-grid's layout plugin (ng-grid-layout.js). It should come with ngGrid located at:
ng-grid/plugins/ng-grid-layout.js
(UPDATED: now at https://github.com/angular-ui/ng-grid/blob/2.x/plugins/ng-grid-layout.js)
You will have to include an additional script tag pointing to this js file in your main index.html file. And the order of including this versus ng-grid.js is important.
You would have to set a watch on displayEditForm and then call the plugin's updateGridLayout() function.
So it would be something like:
var gridLayoutPlugin = new ngGridLayoutPlugin();
// include this plugin with your grid options
$scope.gridOptions = {
// your options and:
plugins: [gridLayoutPlugin]
};
// make sure grid redraws itself whenever
// the variable that ng-class uses has changed:
$scope.$watch('displayEditForm', function() {
gridLayoutPlugin.updateGridLayout();
});
From my understanding, watches generally belong in the link function rather than the controller but it will work in either spot. You could also go a bit further and say:
$scope.$watch('displayEditForm', function(newVal, oldVal) {
if (newVal !== undefined && newVal !== oldVal) {
gridLayoutPlugin.updateGridLayout();
}
});
To make sure this only fires when the data switches from true/false. This would matter if your data is initially undefined and you waste time calling grid redraw before you give it an initial value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21917942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Storage additional on AWS Lightsail I need to free up space on disc on AWS lightsail but I prefer to add storage to increase the limit, somebody knows a easy way to do that? Im not good at coding
A: You can add additional disks to an Amazon Lightsail instance. (It seems like you cannot extend an existing disk.)
The main steps are:
*
*Select your instance in the Amazon Lightsail console
*In the Storage section, click Create new disk and enter details
*In Attach to an instance, select your instance
*Login to the instance to format and mount the disk
See:
*
*Create and attach additional block storage disks to your Linux-based Lightsail instances | Lightsail Documentation
*Creating and attaching a block storage disk to your Windows Server instance in Amazon Lightsail | Lightsail Documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68213527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Chrome refused to display GoogleMaps Frame because X-Frame-Options is set to deny I'm working on a website for a shop and I'm using the GooleMaps Engine Lite to show his location. It works on IE9 and 10, Safari for Windows, iOS and MacOs and Mozilla Firefox, but it's not working on Chrome. If I use the Javascript Console I can see the following error:
Refused to display 'https://accounts.google.com/ServiceLogin?service=mapsengine&passive=1209600…up=https://mapsengine.google.com/map/embed?mid%3DzehbkDaSW5QM.kyKZHGifzxMc' in a frame because it set 'X-Frame-Options' to 'DENY'.
Could anybody help me?
A: First time I had the problem it disappeared when I rebooted my computer, but today the problem appeared again. I've read on Google forums that the conflict comes when you are semi-logged with your Google account. If I log out completely my account or log in the map re-starts to work. In Safari you will find the same issue.
A temporary solution is sandbox the map iframe to forbid it to access the cookies.
A: https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame> or <iframe>. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.
The counter-question I have to you is why are you implementing that URL in an iframe, when it specifically tells the browser it does not want to be loaded in an iframe?
Did you follow the instructions at https://support.google.com/mapsenginelite/answer/3024935?hl=en when embedding the map?
*
*Make sure you have your desired map open and that it is set to be accessible by the Public.
*Click the folder button.
*Select Embed on my site.
*In the box that appears, copy the HTML under 'Embed on the web,' and paste it into the source code of your website or blog.
A: You're linking to the Google Account login page for the maps generator, not to a map. The link is probably not what you want.
To make an embeddable map from Google Maps Engine,
*
*click on the green "Share" button on the top right and set you map to public
*click on the folder icon on the top left (next to "Add layer") and choose "Embed on my site"
A: 1) in the left bottom corner click on 6 teeth wheel , 'Share and integration of map'
2) In opened dialog press on 'integrate map'
3) you got iframe line with correct src .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20702957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Does committing peer sign the new block using private key to produce new block in Hyperledger Fabric? I tried to find about how committing peer works in hyperledger fabric technically in producing new block but I couldn't seem to find resources that explain to me in a very detail manner(such as sign using private key, how transaction is validated technically, etc). My question is after committing peer validate the transaction which they got from ordering service node, who will create the new block exactly? If it's the committing peer, committing peer is not one node but usually it has multiple committing peer node(which represents number of company participating in the network), so how do the system decide which committing peer will produce the new block?
Any reference link about this will be highly appreciated.
A: Please refer to the Transaction Flow in the documentation. Furthermore, Please check out the Key Concept Section too (Both Ledger and Ordering Service for you to understand the flow and also what is inside a block).
Committing peers do not create new blocks, they execute, validate and commit the block created by orderer to their ledger. The signing is done by Endorsing Peers using private key with ECDSA-SHA256 signing. Then of course, verification uses ECDSA-SHA256 too.
Validation is basically executing the read write set and check if the output is deterministic (and thus the result should be same with all other nodes).
I am over simplifying here tho.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70416736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: keras ImageDataGenerator flow_from_directory generated data I'm trying to see the result of using ImageDataGenerator for data augmentation.
Keras reads the data but it seems that it doesn't perform any generation on them. I get as output:
Found 32 images belonging to 1 classes.
but no generated images are saved in the directory I mentioned in save_to_dir parameter of flow_from_directory method.
Here my code:
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from keras import backend as K
K.set_image_dim_ordering('th')
#the path of images to apply augmentation on them
images_path='train'
#create an instance of ImageDataGenerator
datagen = ImageDataGenerator(width_shift_range=0.2,
height_shift_range=0.2)
datagen.flow_from_directory(directory=images_path, target_size=(480,752),color_mode='grayscale', class_mode=None, save_to_dir='saved',save_prefix='keras_')
img = load_img('train/images/photon10.png')
x = img_to_array(img)
x = x.reshape((1,) + x.shape)
datagen.flow(x,batch_size=1,save_to_dir='saved',save_format='png')
I even tried to perform augmentation on one image and it wasn't saved.
What could be the reason? I'm a starter with Keras.
Note: class mode is None because I don't have a specific category.
A: flow_from_directory() returns a DirectoryIterator. The files are not saved until you iterate over this iterator.
For example,
iterator = datagen.flow_from_directory(...)
next(iterator)
will save a batch of augmented images to save_to_dir. You can also use a for loop over the iterator to control how many images will be generated.
A: Its only a declaration, you must use that generator, for example, .next()
datagen.next()
then you will see images in saved
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46391810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Maven only picks src/main/java or src/main/scala as source folder, never both I'm using Eclipse 3.7 w/ m2e (installed 2 weeks ago), with Java 6 and Scala 2.10.
When ever I use m2e to update the project configuration, depending on how I have my .pom configured, it always either picks src/main/java && src/test/java or it picks src/main/scala && src/test/scala as my source folders. I would like it to have all four as source folders.
Here is my .pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.my.name</groupId>
<artifactId>ai.chess</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>chessAI</name>
<description>Chess AI</description>
<repositories>
<repository>
<id>scala-tools.org</id>
<name>Scala-tools Maven2 Repository</name>
<url>http://scala-tools.org/repo-releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>scala-tools.org</id>
<name>Scala-tools Maven2 Repository</name>
<url>http://scala-tools.org/repo-releases</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- <sourceDirectory>src/main/scala</sourceDirectory>
<testSourceDirectory>src/test/scala</testSourceDirectory> -->
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmArgs>
<jvmArg>-Xms64m</jvmArg>
<jvmArg>-Xmx1024m</jvmArg>
</jvmArgs>
<sources>
<source>src/main/scala</source>
<source>src/main/java</source>
<source>src/test/scala</source>
<source>src/test/java</source>
</sources>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.scala-tools
</groupId>
<artifactId>
maven-scala-plugin
</artifactId>
<versionRange>
[2.15.2,)
</versionRange>
<goals>
<goal>compile</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
Eventually, I would like to create an UberJar with all the necessary dependencies so it can run on a server that doesn't support scala (but does Java). The framework for the Chess game is given in Java, so I would like to use that along side with Scala
I may just switch back to using Ant to build if Maven continues to be a pain.
P.S. With the given .pom it uses the java source folders
A: The scala-maven-plugin (previously named the maven-scala-plugin) requires some extra configuration to do mixed Scala/Java projects, but if you follow their instructions (copied below), it should add all the necessary directories to your build path.
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>scala-test-compile</id>
<phase>process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
A: You have two options: the first is to split your project in a parent project with two modules, each of them with its own pom. This is the more natural way to do that with maven but as I am not a scala user myself, I not completely sure is feasible in your setup.
<parent> ai.chess (packaging: pom)
<module> ai.chess.java (packaging: jar)
<module> au.chess.scala (using <sourceDirectory>)
The second option is keep the layout as it is, and use build-helper-maven-plugin to add source directories to the build; like this:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/scala</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-test-source</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/scala</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
A: *
*update to scala-maven-plugin (scala-tools.org no longer exists, since 2 years)
*use the goal add-source (do the same that build-helper-maven-plugin for scala only)
You can also store your .java and .scala files under the same src/main/xxx and src/test/xxx, the java compiler ignore *.scala, and the scala compiler used both.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15236687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Either disable double tap or detect second tap location I have a GLSurfaceView with a GestureDetector and an extended SimpleOnGestureListener. I need to be able to select multiple items on the surface view by tapping them quickly. I overrode onSingleTapUp to detect the touches quickly since onSingleTapConfirmed was too slow. The problem now is that if two items on the surface view are close to one another and the user taps one and then the other quickly, then the onSingleTapUp method is called for the first item, but not for the second. The second one calls the onDoubleTap method whether it's overridden or not.
To resolve this I tried to simply not override the onDoubleTap method and I also tried to do nothing in the overridden onDoubleTap and return false. Neither solves the problem. The onSingleTapUp method will still not get called for the second tap.
I decided to try detecting the second tap in the onDoubleTap method and select the item from there. The problem with that is the motion event returned from onDoubleTap contains "The down motion event of the first tap of the double-tap." - http://developer.android.com/reference/android/view/GestureDetector.OnDoubleTapListener.html
Is there any way to either disable double taps, change the double tap time so it will never fire, change the double tap radius to something very small, or get the first tap location in the onDoubleTap method?
Here's my SimpleOnGestureListener:
public class ViewGestureListener extends
GestureDetector.SimpleOnGestureListener {
private ViewRenderer renderer;
private GLSurfaceView surfaceView;
public ViewGestureListener(GLSurfaceView surfaceView,
ViewRenderer renderer) {
this.renderer = renderer;
this.surfaceView = surfaceView;
}
// Pan
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
renderer.pan(distanceX, distanceY);
surfaceView.requestRender();
return true;
}
// Double touch and release
@Override
public boolean onDoubleTap(MotionEvent e) {
// Note: e.getX() doesn't return the second tap's location!
renderer.singleTouch(e.getX(), e.getY());
surfaceView.requestRender();
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
renderer.singleTouch(e.getX(), e.getY());
surfaceView.requestRender();
return true;
}
}
Thanks,
Matt
A: I might come too late to help the author of this post but I just faced the same problem, so here is the answer for other people who is wondering about it.
ANSWER:
You need to override the following method, it will provide you the down, move, and up events of the second tap:
onDoubleTapEvent(MotionEvent e)
If you want the UP motion of the second tap then:
onDoubleTapEvent(MotionEvent e) {
if(e.getAction() != MotionEvent.ACTION_UP) {
return false; // Don't do anything for other actions
}
// YOUR CODE HERE
return true;
}
Good Luck!
/Carlos
A: It's not well documented but in order to ignore double tap, and detect it as two separate taps, it's enough to set null as double tap listener.
GestureDetector gd = new GestureDetector(context, gestureListener);
gd.setOnDoubleTapListener(null);
Works for both GestureDetector and GestureDetectorCompat.
A: the GestureDetector.OnDoubleTapListener has the following method
enter code here
public class ViewGestureListener extends GestureDetector.SimpleOnGestureListener,
GestureDetector.OnDoubleTapListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d(TAG, "onSingleTapConfirmed");
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.d(TAG, "onDoubleTap");
return false;
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
Log.d(TAG,"onDoubleTapEvent");
return false;
}
the OnDoubleTapEvent is called after each tap of the double tap. You can return true here and get each tap separately.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10824388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to add company name field in admin console (new user) alfresco community? I'm using Alfresco Community 5.0.d and it does not show the fields for company info.
If I search for user then it shows all details but don't let me add company info while creating a user.
So far I came across user.js file at /Applications/alfresco-5.0.d/tomcat/webapps/share/components/console but I'm not able to add the field for new user.
form.addValidation(parent.id + "-create-companyname", Alfresco.forms.validation.mandatory, null, "keyup"); // ADDED this but not showing in form.
form.addValidation(parent.id + "-create-firstname", Alfresco.forms.validation.mandatory, null, "keyup");
form.addValidation(parent.id + "-create-email", Alfresco.forms.validation.mandatory, null, "keyup");
form.addValidation(parent.id + "-create-email", Alfresco.forms.validation.email, null, "change", parent._msg("Alfresco.forms.validation.email.message"));
form.addValidation(parent.id + "-create-username", Alfresco.forms.validation.mandatory, null, "keyup");
form.addValidation(parent.id + "-create-username", Alfresco.forms.validation.nodeName, null, "keyup", parent._msg("Alfresco.forms.validation.nodeName.message"));
Also I have added the key-value in personObj created in users.js as below.
var personObj =
{
userName: username,
password: password,
firstName: fnGetter("-create-firstname"),
lastName: fnGetter("-create-lastname"),
email: fnGetter("-create-email"),
organization: fnGetter("-create-companyname"),
disableAccount: Dom.get(me.id + "-create-disableaccount").checked,
quota: quota,
groups: groups
};
PersonObj is:
personObj
disableAccount : false
email : "[email protected]"
firstName : "test"
groups : Array[0]
lastName : "test"
organisation : "test" //added this key-value
password : "admin"
quota : -1
userName : "test_test"
But company name is not coming. Moreover, I have tried adding multiple user using .csv file link and it does not show the company name (column name is Company as given in guide lines) but do show like mobile number, fax, etc.
Is this is a bug with Alfresco community 5.0.d?
Screenshot of new user form for reference.
I need to add company name field in above form of new user so it could be pre-populated for those new user's.
How could I add the company name field so it gets added to new user's profile?
Thanks
A: Hi you can add user company details using.
Javascript. example
var x =people.getPerson("admin");
logger.log(x.properties["companyemail"]);
//getting the current Company email
x.properties["companyemail"]="[email protected]";
//setting new company email
logger.log(x.properties["companyemail"]);
//getting the new Company email
companytelephone
companyaddress2
companyaddress1
companyfax
companyemail
companypostcode
These are the some properties of user comapny
A: To add a field which is already a property of user model.
In case of adding company field, follow below steps:
*
*In users.get.properties file - Add below line.
label.companyname=Company
*In users.js file - Added fields company property for not null check and getting it's value followed with clearing the value after a valid entry.
form.addValidation(parent.id + "-create-companyname",Alfresco.forms.validation.mandatory, null, "keyup"); // Add validation
organisation: fnGetter("-create-companyname"), // Get company value
fnClearEl("-create-companyname"); // Clear company field
*In users.get.html.ftl file - Added div for company
<div class="field-row">
<span class="crud-label">${msg("label.companyname")}: *</span> </div> <div class="field-row">
<input class="crud-input" id="${el}-create-companyname" type="text" maxlength="100" />
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42342490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: select a specific range on a excel sheet in vba I am trying to developp a small tool in vba and as I am a beginner in this, I am having some trouble.
I would like to apply on specific cells of a column a treatment. This is my actual code :
For Each C In ActiveSheet.UsedRange.Columns("B").Cells
The problem with this code, is that is applying to all the cells of my column B, whereas I would like to stop at a specific line (line which I am getting for another function (GetLine) that I have developped) :
Function GetLine(rw As Long) As Long
GetNextEmptyCell = //my code
End Function
So I would like to know how to specify in my foreach to stop at the number returned by my function.
thanks in advance for your help
A: You could use something like this to loop from row 1 to the specified row:
For Each C In ActiveSheet.Range("B1:B" & GetLine).Cells
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28673441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: replacing a character in a textbox? in vb6 i would like to be able to detect when the user presses the space key and instead of putting in a space an underscore symbol is used. is that a possibility or am i just being hopeful? i cant seem to quite make out how to do this, i have tried fiddling around with the key-press methods however i don't know of the right code to do this.
Private Sub txtbarcode_KeyPress(KeyAscii As Integer)
if keyascii = vbkeyspace then
'replace space with underscore
end if
end sub
A: This should work
Private Sub txtbarcode_KeyPress(KeyAscii As Integer)
If KeyAscii = 32 Then
'replace space with underscore
KeyAscii = 95
End If
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23699656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Selecting IDs linked with CPC codes in the same column I am using the PATSTAT database to select the APPLN_ID of patent applications that have a cpc classification symbol but not another. I need to do this in order to retrieve a control dataset of patents to verify my hypothesis.
PATSTAT is a relational database where each patent application has a set of attributes. The TLS224 table contains multiple rows with the same APPLN_ID and different CPC symbols. I want to retrieve the APPLN_IDs that have a set of symbols A but that do not have a set of symbols B.
From this example data
| APPLN_ID | CPC_CLASS_SYMBOL |
| 2345 | C07K 16/26 |
| 2345 | C07K2317/34 |
| 2345 | C07K2317/76 |
| 2345 | G01N 33/74 |
| 2345 | B01L 9/527 |
| 1000 | C07K2317/34 |
| 1000 | C07K 16/26 |
| 1000 | C07K2317/76 |
| 1000 | B01L 3/5025 |
| 9999 | B01L 3/5025 |
| 9999 | G01N2333/47 |
| 9999 | G01N2333/4727 |
I want to obtain this as a result.
| APPLN_ID |
| 1000 |
Here, the set of values A that must be included are 'C07K 16/26' ,'C07K2317/34', 'C07K2317/76', while the value B that must NOT be present is G01N 33/74.
How can I do that?
This is what I came out with so far (I know that the WHERE IN and NOT IN clauses nullify each other, but it is just to show an example).
SELECT DISTINCT p2.APPLN_ID
FROM (SELECT p1.APPLN_ID, p1.PUBLN_AUTH, YEAR(p1.PUBLN_DATE)
FROM TLS211_PAT_PUBLN p1
WHERE YEAR(p1.PUBLN_DATE) = 2008
AND PUBLN_AUTH = 'WO') p2
JOIN (SELECT DISTINCT cpc3.APPLN_ID
FROM TLS224_APPLN_CPC cpc3
WHERE cpc3.APPLN_ID IN
(SELECT APPLN_ID
FROM TLS224_APPLN_CPC
WHERE CPC_CLASS_SYMBOL NOT IN ('G01N 33/74'))
AND cpc3.APPLN_ID IN
(SELECT APPLN_ID
FROM TLS224_APPLN_CPC
WHERE CPC_CLASS_SYMBOL IN ('C07K 16/26', 'C07K2317/34', 'C07K2317/76'))
) cpc1
ON cpc1.APPLN_ID = p2.APPLN_ID
I am still a newbie to SQL so any help is appreciated!
Thank you
A: your IN and NOT IN doesn't make sense.
if CPC_CLASS_SYMBOL are in the first Group they are automatocally NOT IN your second
Your WHERE clause would only give you APPLN_ID (and some more) the have these symbols and everything else is excluded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64634509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cluster environment with SQL Server 2008 Does SQL Server 2008 web edition support cluster environment?
A: Only Standard, Enterprise and Datacenter editions support clustering:
SQL 2008 - Compare Edition Features
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3953578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angularjs give classes based on variable value I have the following php expression.
$isActive = ($value['is_active'] == 1) ? '<i class="btn fa fa-toggle-on
isActive"></i>' : '<i class="btn fa fa-toggle-off isInactive"></i>';
How can i translate that into angularjs if statement?
Thanks in advance!
A: I believe you're asking for ng-class.
you need to set a variable to represent 'is_active', and use it in your html like so:
<i class="btn fa" ng-class="{'fa-toggle-on isActive' : is_active,
'fa-toggle-off isInactive' : !is_active}"></i>
A: Thanks for your time and answers.
I found the following and get my work done.
Using ng-if inside ng-repeat?
So my code now looks like this
<td ng-if="client.clientStatus == 0"><i class="btn fa fa-toggle-off isInactive"></i></td>
<td ng-if="client.clientStatus == 1"><i class="btn fa fa-toggle-on isActive"></i></td>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28405196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Nativescript onesignal push notification ios error i've a nativescript (2.4.0) project with platform ios and android with this plugin to use onesignal push notifications.
Android works perfectly but not Ios. When i try to build ios i receive these messages:
app/main.ts(9,30): error TS2304: Cannot find name 'UIResponder'.
app/main.ts(9,53): error TS2304: Cannot find name 'UIApplicationDelegate'.
app/main.ts(11,40): error TS2304: Cannot find name 'UIApplicationDelegate'.
app/main.ts(13,63): error TS2304: Cannot find name 'UIApplication'.
app/main.ts(13,93): error TS2304: Cannot find name 'NSDictionary'.
Thanks for your support.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41084388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Consistent width for geom_bar when y-axis is a "Count" rather than an explicit variable I am attempting to make a bar graph figure in ggplot2 with all bars having an equal width regardless if there is data present for a particular variable combination. This question is quite similar to the one found here "Consistent width for geom_bar in the event of missing data"; however, I do not have a variable mapped to the y-axis, but rather I am doing a count of the number of times a specific combination of variables occurs.
Does anyone know of a way to work around this? Also, in my original "actual" dataset, I have two variables to account for in facet_wrap, rather than one. Would answers differ when including this extra variable?
The code I have worked out currently is giving me uneven bar widths:
library(ggplot2)
ggplot(dat, aes(Subjective_Assessment, fill=pts))+geom_bar(position="dodge")+
facet_wrap(~background)+
labs(y="Count")
Example Bar graph resulting in uneven bar widths
species background pts Subjective_Assessment
Species_1 State_1 Factor_1 Good
Species_2 State_1 Factor_1 Good
Species_3 State_1 Factor_1 Good
Species_4 State_1 Factor_1 Good
Species_1 State_1 Factor_2 Poor
Species_2 State_1 Factor_2 Poor
Species_3 State_1 Factor_2 Moderate
Species_4 State_1 Factor_2 Poor
Species_1 State_1 Factor_3 Moderate
Species_2 State_1 Factor_3 Moderate
Species_3 State_1 Factor_3 Moderate
Species_4 State_1 Factor_3 Poor
Species_1 State_2 Factor_1 Good
Species_2 State_2 Factor_1 Good
Species_3 State_2 Factor_1 Good
Species_4 State_2 Factor_1 Good
Species_1 State_2 Factor_2 Moderate
Species_2 State_2 Factor_2 Moderate
Species_3 State_2 Factor_2 Moderate
Species_4 State_2 Factor_2 Moderate
Thanks in advance for your help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35366703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: eclipse JSP line wrapping In Eclipse, I've setup the Java formatter to wrap lines only when they exceed 120 characters. I would like the same setting to be used when I format JSP files, but at the moment it wraps them when they exceed 90 characters, is it possible to change this?
A: Note in the latest version of eclipse you won't see the line width option in jsp files editor, instead this is covered by the line with setting in html files - editor menu
A: Window - Preferences - Web - JSP Files - Editor. Click on the link for your kind of JSP (HTML or XML content), and adjust the line width.
A: Window -> Preferences -> type HTML...You'll see "Editor" so in line width, enter the value as you need. Works for me on eclipse 2018-12 version
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6637734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Boost rng vs OpenCV rng vs c++11 std::random? It is just a simple question, I need some opinions.
I am using both boost and OpenCV, and I want to generate a random number. Which is better to use: the boost::random::uniform_int_distribution (boost random integer generator) or cv::RNG?
I have written this:
// OpenCV RNG:
cv::RNG rngCV(cv::getTickCount());
int randInt = rngCV.uniform(0, 100); // generates integer number in [0, 100)
std::cout << "cv::RNG: " << randInt << std::endl;
// Boost RNG:
boost::random::mt19937 gen(static_cast<unsigned int>(std::time(0)));
boost::random::uniform_int_distribution<> rngBoost(0, 99);
int randInt2 = rngBoost(gen);
std::cout << "boost::random: " << randInt2 << std::endl;
// c++11 random
std::random_device rd;
std::default_random_engine el(rd());
std::uniform_int_distribution< int > unif_distr(0, 99);
int randInt3 = unif_distr(el);
std::cout << "std::random: " << randInt3 << std::endl;
Which one do you suggest me to do? Both are working well.
A: The boost interface is much more like what got into the standard. So if you plan to go that route at some point, it might be easier to change if you're using boost.
A: Since C++11, there is a random generator engine that is in the standard library.
Nothing comparable with the old rand() function from C.
There are a bunch of random distributions, you can specify the interval ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25058844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does post-training quantization work? I am currently interested in model quantization, especially that of post-training quantization of neural network models.
I simply want to convert the existing model (i.e., TensorFlow model) using float32 weights into a quantized model with float16 weights.
Simply changing each data type of every weight (i.e., float32 -> float16) would not work, would it?
Then, how can I manually perform this type of quantization?
Suppose i have weight matrix that look like;
[ 0.02894312 -1.8398855 -0.28658497 -1.1626594 -2.3152962 ]
Then simply converting every weight in the matrix into float16 dtype would generate the following matrix;
[ 0.02895 -1.84 -0.2866 -1.163 -2.314 ]
which, i think will not be the way how the off-the-shelf libraries' (e.g., TF Lite) quantization work...
Then how can i manually perform this type of quantization properly?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75529539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CHtmlEditCtrl::PrintDocument() - lines near the page bottom have wrong spacing? I am trying to print document using the method of CHtmlEditCtrl::PrintDocument() as described here (Printing In MFC Application). Below is my test code where I plan to print a pretty big table.
void CMyView::OnFilePrint()
{
CHtmlEditCtrl PrintCtrl;
if (!PrintCtrl.Create(NULL, WS_CHILD, CRect(0, 0, 0, 0), this, 1))
{
ASSERT(FALSE);
return;
}
CComPtr<IHTMLDocument2> document;
PrintCtrl.GetDocument(&document);
WaitForComplete(document);
CString html =
_T("<!doctype html>")
_T("<html lang=\"en\">")
_T(" <head>")
_T(" <meta charset=\"utf-8\">")
_T(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">")
_T(" <title>HTML5 Test Page</title>")
_T(" <style>")
_T(" @media print")
_T(" {")
_T(" td { overflow-x:auto }")
_T(" }")
_T(" </style>")
_T(" <style type=\"text/css\">")
_T(" thead { display:table-header-group }")
_T(" tfoot { display:table-footer-group; page-break-inside:avoid }")
_T(" tbody { display:table-row-group }")
_T(" td > div { display:block; page-break-inside:avoid }")
_T(" </style>")
_T(" </head>")
_T(" <body>")
_T(" <div id=\"top\" class=\"page\" role=\"document\">")
_T(" <header role=\"banner\">")
_T(" <p>This is header.</p>")
_T(" </header>")
_T(" <main role=\"main\">")
_T(" <section id=\"text\">")
_T(" <article id=\"text_tables\">")
_T(" <table>")
_T(" <thead>")
_T(" <tr>")
_T(" <th>")
_T(" header comes here for each page")
_T(" </th>")
_T(" </tr>")
_T(" </thead>")
_T(" <tfoot>")
_T(" <tr>")
_T(" <td>")
_T(" footer comes here for each page")
_T(" </td>")
_T(" </tr>")
_T(" </tfoot>");
_T(" <tbody>");
for (int i = 0; i < 200; ++i)
{
CString str;
str.Format(_T("%d"), i);
html = html + "<tr><td><div>" + str + "</div></td></tr>";
}
html = html + "</tbody></table></article></section></main>";
html = html + "<footer role=\"contentinfo\"><p>This is footer</p></footer></div></body></html>";
PrintCtrl.SetDocumentHTML(html);
WaitForComplete(document);
//PrintCtrl.PrintPreview();
PrintCtrl.PrintDocument();
}
The problem is for every line near the page bottom, there seems to be a mess of spacing. See attached picture below, note that 41 has more spacing from 40 and gets partially cut off. How does it happen and how to fix it?
I try adding repeated header and footer, below is part of the result that displaying error.
I try using "td {overflow-x:auto;}". The table footer of the first page is not shown correctly.
A: This appears to be a bug with IWebBrowser2 interface. It can be fixed with td{overflow-x: auto;}
<style>
@media print
{
td{overflow-x: auto;}
}
</style>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59459495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Git made 3 Gits And Now Not Working At All Help!
I implemented Git to my project and somehow Git has made 3 files for saving my information: (1) Saves all of my view controllers, (2) The same file as (1), (3) my pods only.
The one containing my pods seems to be broken as I can not commit anything to it. First I thought nothing of these 3 Gits and proceeded coding, but now I am trying to branch my master with something I have been spending months coding but it seems to be crashing every time because it does not save my code to the master and makes me update my pods. Now after I tried to branch it, it did not work but now when I try to commit my files to the current branch I'm working on, it is not letting me without committing all 1600 files that are in my Pods. But the Pod file will not commit! I have no clue how to fix this and I am in desperate need of help!!!! Can anyone please help. I just want to have one place that will commit my files like in every Xcode git file. I do not want to lose my months of work.
I get the error: "The working copy “Pods” failed to commit files. - The source control operation failed because no repository could be found."
A: Please trouble shooting you issue with below aspects:
1. Use one git repository
*
*If you mean 3 gits are 3 git repositories, you should keep only one git repo to manage your project. Only keep the repo that can contain all the files you want to manage under it’s directory.
As below example, if you project (the files you want to manage in git repo) is under Dir2 (not contains it’s parent Dir1), then you should remove the other two repos for Dir1 and Dir3 by removing the folders Dir1/.git and Dir1/Dir2/Dir3/.git.
Dir1
|___.git
|___ …
|___Dir2
|___.git
|___ …
|___Dir3
|___.git
|___ …
*If you mean 3 gits are 3 git branches for the same git repo, before switching branches, you should make sure the work directory is clean (save and commit changes before switching branches).
2. Mark sure user.name and user.email has already been set
You can use the command git config -l to check if the output contains:
user.name=<username>
user.email=<email address>
If the output does not contain user.name and user.email, you should set as below:
git config --global user.name yourname
git config --global user.email [email protected]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48046142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How can I iterate through a list and use the values as labels or assigned names when instantiating a variable? If a user inputs a list of strings, I want to be able to iterate through that list and for each string in that list use that as a label for a variable. For example: User enters ["one", "three", "myVar"]. I want to instantiate a variable with name of "one", another one with the name of "three", etc. So I can have something like Integer one = 23; or String three = "hello";
How would I go about doing this in Java?
A: This would be pointless. To use the variables in the code you'd need to know what the user had entered. (Hacks like reflection aside.)
Almost certainly what you want is a Map keyed on the String entered. You still have the problem of the type of the maps value, which will depend upon exactly how you are going to use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60480297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Default page code behind not working when published on hosting server I decided not to redirect a first visitor from default to my "Not Logged In" page and just turn default in the "Not Logged In" page. When i did this, none of the code is working in the codebehind except for the page load. I have a menu that works perfectly fine, but any link button, or login code in the master page is not working. Maybe it has to do with the url rewriting the hosting provider does? My page doesn't have default.aspx in the url it just shows www.mywebsite.com
Here is my page load on default.
if (!IsPostBack)
{
AbuseReport abuse = new AbuseReport();
abuse.Message = "page load clicked";
abuse.ReportingPersonID = 1;
abuse.AbuserPersonID = 1;
abuse.CreateAbuseReport();
SiteViews();
bool stayOnSite = (Session["StayOnMainSite"] != null && !Parser.GetBoolean(Session["StayOnMainSite"]));
string strUserAgent = Request.UserAgent.ToString().ToLower();
if (strUserAgent != null)
{
if (Request.Browser.IsMobileDevice == true || strUserAgent.Contains("iphone") ||
strUserAgent.Contains("blackberry") || strUserAgent.Contains("mobile") ||
strUserAgent.Contains("windows ce") || strUserAgent.Contains("opera mini") ||
strUserAgent.Contains("palm") || strUserAgent.Contains("android") ||
strUserAgent.Contains("ipad") || strUserAgent.Contains("moto") ||
strUserAgent.Contains("htc") || strUserAgent.Contains("sony") ||
strUserAgent.Contains("panasonic") || strUserAgent.Contains("midp") ||
strUserAgent.Contains("cldc") || strUserAgent.Contains("avant") ||
strUserAgent.Contains("windows ce") || strUserAgent.Contains("nokia") ||
strUserAgent.Contains("pda") || strUserAgent.Contains("hand") ||
strUserAgent.Contains("mobi") || strUserAgent.Contains("240x320") ||
strUserAgent.Contains("voda"))
{
if (!stayOnSite)
{
Response.Redirect("~/Mobile/Default.aspx");
return;
}
}
}
if (Session[ApplicationClass.UserSessions.AppUser] != null)
{
ApplicationClass appClass = ((ApplicationClass)Session[ApplicationClass.UserSessions.AppUser]);
if (appClass.User.IsPolitician)
{
UrlParameterPasser urlPasser = new UrlParameterPasser("~/PoliticianView/PoliticianWall.aspx");
urlPasser["PoliticianID"] = Parser.GetString(appClass.User.Politician.PoliticianID);
urlPasser.PassParameters();
}
else
{
Response.Redirect("~/User/UserMain.aspx");
}
}
}
Here is my login click (register is the same, and the abuse is just for logging purpose right now)
protected void lbtnLogin_Click(object sender, EventArgs e)
{
AbuseReport abuse = new AbuseReport();
abuse.Message = "Login clicked";
abuse.ReportingPersonID = 1;
abuse.AbuserPersonID = 1;
abuse.CreateAbuseReport();
Response.Redirect("~/Login/Login.aspx");
AbuseReport abuse2 = new AbuseReport();
abuse2.Message = "Login after click";
abuse2.ReportingPersonID = 1;
abuse2.AbuserPersonID = 1;
abuse2.CreateAbuseReport();
}
here is defualt.aspx
<%@ Page Title="Politic Profiles Main" Language="C#" MasterPageFile="~/TwoColumn.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="PoliticProfiles._Default" %>
<table cellpadding="10px">
<tr>
<td>
<asp:Image ID="Image1" ImageUrl="~/Images/flags.jpg" AlternateText="American Flags"
runat="server" />
</td>
<td valign="top">
<h1>Welcome to Politic Profiles</h1>
<h2>Political information tailored to you.</h2>
<br />
<h3>
<asp:LinkButton ID="lbtnRegister" runat="server" Text="Register"
onclick="lbtnRegister_Click" />
<asp:Label ID="Label1" Text=" or " runat="server" />
<asp:LinkButton ID="lbtnLogin" runat="server" Text="Login"
onclick="lbtnLogin_Click"/>
<asp:Label ID="Label2" runat="server" Text=" to get the most out of your experience." />
</h3>
<ul class="landing">
<li>
<asp:Label ID="Label3" runat="server" Text="Ask your politicians questions." />
<br /><br />
</li>
<li>
<asp:Label ID="Label4" runat="server" Text="Keep up to date with what your politicians are doing." />
<br /><br />
</li>
<li>
<asp:Label ID="Label5" runat="server" Text="Allow your politicians to learn from you." />
<br /><br />
</li>
<li>
<asp:Label ID="Label6" runat="server" Text="Be involved in polls that help inform you politicians what track you want them on." />
<br /><br />
</li>
</ul>
</td>
</tr>
</table>
<uc:Polls id="ucPolls" runat="server" />
<br /><br />
<uc:Donate id="ucDonate" runat="server" />
A: Turned out to be because i had enableCrossAppRedirects="true"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8827056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IOS : passing data between viewController (destination embedded in a NavigationController) I'm just learning IOS development, I would like to pass data between ViewController. I'm using Storyboard and I'm using the "prepareForSegue" method.
My main question is about the pattern I found in many forums and blogs about this "transmission" of information. When the origin controller needs to pass data to a destination controller, the origin controller access the destination controller using the code :
[segue destinationViewController]
This is fine, the origin controller doesn't need to know exactly the destination controller details (I'm using protocols).
But when the destination controller is a NavigationController (a ViewController embedded in a NavigationController), it seems that the recommended practice is :
[[segue destinationViewController] topViewController]
But if I do that, it means that the origin controller must know that the destination controller IS a NavigationController. I would like to avoid that if possible ?
Maybe I'm doing something wrong ? Is there another way to do it ?
The origin controller is a "detail page" (coming from a TableView), the destination controller is the "edit page".
Any help is welcome.
Thanks
A: UINavigationController *navTmp = segue.destinationViewController;
YourController * xx = ((YourController *)[navTmp topViewController]);
xx.param = value;
A: Check to see if the destinationViewController is a UINavigationController, and if it is, then get its topViewController. That way it just automatically handles either case, and it's safe.
A:
But if I do that, it means that the origin controller must know that
the destination controller IS a NavigationController. I would like to
avoid that if possible ?
One possible solution is to subclass UINavigationController such that it can accept whatever data your source controller provides and in turn passes that data on to its root view controller. That might make particular sense if you have a number of segues, some leading to nav controllers and some not, and you want to handle them all the same way.
In other words, create a UINavigationController subclass that acts like a proxy for its root controller.
A: I see two possibilities:
*
*Use -isKindOfClass and check if it's a UINavigationController
*Create a protocol whith a -rootViewController method, create two categories conforming the protocol, one on UIViewController, another on UINavigationController, implement both, the one for UIViewController should return self, the one for UINavigationController should return topViewController. Now you'll be able to drop those categories on any controller, and use [[segue destinationViewController] rootViewController]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21101642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Enter UserForm Data into the next empty cell range I have a UserForm which takes text entry, and an OptionButton Selection, to enter data onto a Worksheet, with a certain classification.
The entries are placed in a specific cell in the sheet using the value from a counter, i, and can be removed to an "archive" worksheet located on the same workbook, via the use of a button. This pheasibly leaves a free entry in the list. i.e.
Job 1 is entered
Job 2 is entered
Job 3 is entered
Job 2 is archived
There now exists a space between job 1 and 3.
What I am trying to do, is create a loop which will check for an empty Cell range, and place the UserForm data, in the next available empty cell. The data is entered every 5 cells, so A5, A10, A15... etc.
The code I currently have is as follows:
If UserForm1.OptionButton1.Value = True Then
If Range("A" & (5 * i)).Value = "" Then
ActiveSheet.Range("A" & (5 * i) & ":" & "O" & (3 + (5 * i))).Select
With Selection.Interior
.Color = RGB(239, 231, 121)
End With
With Worksheets("Active Jobs")
.Range("A" & (5 * i)) = UserForm1.TextBox1 'Place job 5 cells apart
.Range("B" & (5 * i) & ":" & "E" & (3 + (5 * i))).Merge
.Range("B" & (5 * i)) = UserForm1.TextBox2
.Range("B" & (5 * i) & ":" & "E" & (3 + (5 * i))).VerticalAlignment = xlTop
.Range("G" & (5 * i) & ":" & "O" & (3 + (5 * i))).Merge
Set t = .Range("T" & (5 * i))
Set btn = .Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.Name = "RemovetoArchive" & i1
.Caption = "Archive"
.OnAction = "RemovetoArchive"
End With
End With
i = i + 1
ElseIf Range("A" & (5 * i)).Value <> "" Then
For i = 1 To 25
'I can't figure out how to implement the for loop here.
Next i
End If
A: So guess I had a brain fart, left this a few days and came back and solved it almost immediately.
Creating a While loop with a new variable C for the range
While Range("A" & (5 * c)).Value <> ""
c = c + 1
Wend
This located the nearest empty Cell every 5 cells.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43871977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to hide hover and click event of UniformGrid? I try to create a list of buttons with two columns using a ListBox and UniformGrid. Everything seemed to be okay until I faced the following issue. The margin space of the button was shown with light blue color when I click it or hover over it. How to remove this effect?
This is my code:
<ListBox Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Name="uniformGrid1" Margin="50" ItemsSource="{Binding SomeItemsList}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="2" Background="Transparent" Name="uniformGrid1"></UniformGrid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Margin="50" Height="70" Click="keyword_Click" Width="250"
Foreground="Black" FontSize="16" FontFamily="Helvetica Neue" FontWeight="Bold"
BorderBrush="SlateGray" Content="{Binding Name}">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="White" Offset="0.073" />
<GradientStop Color="White" Offset="1" />
<GradientStop Color="#FFE9E9F9" Offset="0.571" />
<GradientStop Color="#FFD7D7EC" Offset="0.243" />
</LinearGradientBrush>
</Button.Background>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
A: The problem here is that the ListBox has a selection, and selected items get highlighted. You need to disable this highlighting to get the desired result, for example by setting ListBox.ItemContainerStyle as described in this answer. This will remove the (lightblue) selection color.
A: Each item in the ItemsSource is wrapped in a ListBoxItem inside the ListBox. A ListBox is a control derived from Selector, which is a base type for items controls that allow selection of items.
Represents a control that allows a user to select items from among its child elements.
What you specified as DataTemplate will be placed in a ListBoxItem at runtime, which is the container for the content. This container has a default style and control template that defines its appearance and visual states. What you see is the MouseOver state and the Selected state. You can change this by extracting the default style for ListBoxItem and adapting it or by writing your own.
*
*How to create a template for a control (WPF.NET)
However, it seems that your intention is different. What you probably wanted was to simply display buttons in a UniformGrid depending on a bound collection, without any selection. You can achieve this by using an ItemsControl instead. It does not offer any selection capabilities, but lets you bind a collection with the UniformGrid as items panel.
<ItemsControl Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Margin="50" ItemsSource="{Binding SomeItemsList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="2" Background="Transparent" Name="uniformGrid1"></UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="50" Height="70" Click="keyword_Click" Width="250"
Foreground="Black" FontSize="16" FontFamily="Helvetica Neue" FontWeight="Bold"
BorderBrush="SlateGray" Content="{Binding Name}">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="White" Offset="0.073" />
<GradientStop Color="White" Offset="1" />
<GradientStop Color="#FFE9E9F9" Offset="0.571" />
<GradientStop Color="#FFD7D7EC" Offset="0.243" />
</LinearGradientBrush>
</Button.Background>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Please note that I have removed one of two Name="uniformGrid1" as duplicate names lead to a compilation error. If your content exceeds the viewport and you need scrollbars, you have to add a ScrollViewer, since this is built into the ListBox, but not the ItemsControl.
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<ItemsControl Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Margin="50" ItemsSource="{Binding SomeItemsList}">
<!-- ...other code. -->
</ItemsControl>
</ScrollViewer>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70167279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error in your SQL syntax for INNER JOINS I have been trying to run this mysql query through rstudio, but I keep getting an error. Any idea why?
Here is my query:
SELECT host.key AS 'uid',
daily_summary.date AS 'date'
FROM host INNER JOIN daily_summary
USING(weekly_id);
This is the error I get.
42000 1064 [MySQL][ODBC 5.1 Driver][mysqld-5.5.40-
0ubuntu0.14.04.1]You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server
version for the right syntax to use near 'FROM host INNER
JOIN daily_summary USING(weekly_id)' at line 1
A: This is the query as it would better be written:
SELECT host.key AS uid, daily_summary.date
FROM host INNER JOIN
daily_summary
USING(weekly_id);
In addition to removing the spurious commas, this also removes the unneeded quotes around the column aliases. Only use single quotes for string and date constants. Otherwise, they are likely to cause confusion in queries. If you need to escape aliases in MySQL, then use backticks.
A: Check version simplified without typos:
SELECT host.key, daily_summary.date
FROM host INNER JOIN daily_summary
USING(weekly_id);
I also prefer to use word ON instead of USING:
SELECT host.key, daily_summary.date
FROM host INNER JOIN daily_summary
ON host.weekly_id = daily_summary.weekly_id
A: The MySQL syntax error message shows you part of your statement starting with the first character it can't understand. In your case the first characters it can't understand are FROM. It's looking for another column name after the comma.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28976001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: using handler for every single task(method) in android Hello i am new to android and android thread so want to know that
How could we use more number of thread in order to perform every single task or method so that while user click on any UI component it does effect the performance ,having little knowledge of how the handler thread and asynctask work.But how can we run every method inside the asynctask so to do the operation and mean while user can do the other operation also.
In the application
*
*i have voice recording from mic.
*next showing progress bar.
*next showing gallery with some image and with that setting effect to the picture.
A: The recommended way is to use AsyncTasks for long running tasks. So, not everything needs to be run with AsyncTasks, as you can get a performance hit due to the context switching.
As for how AsyncTasks work, read the documentation.
A: Use an AsyncTask and make sure to implement these as needed. You mention the idea of doing something in the background while a user is doing something so I'm guessing you'll want to alter the UI.
Take a look at these links for an more details from Android. They cover Runnable, AsyncTask and Handler
*
*Overview of them all http://developer.android.com/guide/components/processes-and-threads.html
*AsyncTask example http://developer.android.com/reference/android/os/AsyncTask.html
*Old but relevant, Painless Threading http://android-developers.blogspot.com/2009/05/painless-threading.html
*Another, more complex example http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
I don't generally paste full examples in here but I had a lot of trouble finding an example I was happy with for a long time and to help you and others, here is my preferred method. I generally use an AsyncTask with a callback to the Activity that started the task.
In this example, I'm pretending that a user has triggered onClick(...) such as with a button, but could be anything that triggers a call into the Activity.
// Within your Activity, call a custom AsyncTask such as MyTask
public class MyActivity extends Activity implements View.OnClickListener, MyTask.OnTaskComplete {
//...
public void onClick(View v) {
// For example, thet user clicked a button
// get data via your task
// using `this` will tell the MyTask object to use this Activty
// for the listener
MyTask task = new MyTask(this);
task.execute(); // data returned in callback below
}
public void onTaskComplete(MyObject obj) {
// After the AsyncTask completes, it calls this callback.
// use your data here
mTextBox.setText(obj.getName);
}
}
Getting the data out of a task can be done many ways, but I prefer an interface such as OnTaskComplete that is implemented above and triggered below.
The main idea here is that I often want to keep away from inner classes as they become more complex. Mostly a personal preference, but it allows me to separate reusable tasks outside of one class.
public class MyTask extends AsyncTask<Void, Void, MyObject> {
public static interface OnTaskComplete {
public abstract void onTaskComplete(MyObject obj);
}
static final String TAG = "MyTask";
private OnTaskComplete mListener;
public MyTask(OnTaskComplete listener) {
Log.d(TAG, "new MyTask");
if (listener == null)
throw new NullPointerException("Listener may not be null");
this.mListener = listener;
}
@Override
protected MyObject doInBackground(Void... unused) {
Log.d(TAG, "doInBackground");
// do background tasks
MyObbject obj = new MyObject();
// Do long running tasks here to not block the UI
obj.populateData();
return
}
@Override
protected void onPostExecute(MyObject obj) {
Log.d(TAG, "onPostExecute");
this.mListener.onTaskComplete(obj);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14960695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Running Program from Call Doesn't Seg Fault My program writenotes keeps seg faulting when I try to write a note that is too long.
./writenotes lolololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololo
[ * ] Writing notes
Segmentation fault
Anyways, I was trying to write a python script that calls the program and curiously enough, calling it from a python script doesn't bring a seg fault, which I thought was rather peculiar.
Heres this code:
#!/usr/bin/python
from subprocess import call
call(["./writenotes", "lolololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololo"])
Which returns
[ * ] Writing notes
Is this because of parent processing or something like such? How would calling a program through subprocess save a program from a segfault though? Are there other ways to call programs from a script that suffer seg faults?
As a note, the writenotes program was written in C. The other script is python.
A: You'll almost certainly find your C program is crashing but that Python is hiding that from you. Try instead with:
print call(["./writenotes", "lolololol..."])
and see what you get as a return value.
For example, this program tries to modify a string literal and, when run normally dumps core:
int main (void) {
*"xyzzy" = 'X';
return 0;
}
However, when run from the following script:
from subprocess import call
print call(["./testprog"])
I get the output -11, indicating that signal 11 (usually SIGSEGV) was raised, as per the documentation discussing Popen.returncode which subprocess.call() uses under the covers:
A negative value -N indicates that the child was terminated by signal N (Unix only).
An alternative to checking the return code is to import check_call and CalledProcessError instead of call and then use that function. It will raise an exception if the return code is non-zero.
That's probably not so important if you're only calling one executable (just get the return value in that case) but, if you're doing a lot in sequence, catching an exception from the entire group may be more readable.
Changing the C program to only crash when the first argument is 3:
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]) {
if (argc > 1) {
printf ("hello there %s\n", argv[1]);
if (strcmp (argv[1], "3") == 0)
*"xyzzy" = 'X';
}
return 0;
}
and the script to call it with several different arguments:
from subprocess import check_call, CalledProcessError
try:
check_call(["./testprog", "0"])
check_call(["./testprog", "1"])
check_call(["./testprog", "2"])
check_call(["./testprog", "3"])
check_call(["./testprog", "4"])
check_call(["./testprog", "5"])
check_call(["./testprog", "6"])
check_call(["./testprog", "7"])
check_call(["./testprog", "8"])
check_call(["./testprog", "9"])
except CalledProcessError as e:
print e.cmd, "failed with", e.returncode
else:
print "Everything went well"
shows that in action:
hello there 0
hello there 1
hello there 2
hello there 3
['./testprog', '3'] failed with -11
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29786041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to recuperate data entered by user in a dynamic table I have created a dynamic table using html+php with input like a form (this is a matrix in reality) and
I want to know if it is possible to recuperate data entered by user in a dynamic table? This is my code:
<?php
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
echo "<th> E".$tr." </th>";
for($td=1;$td<=$rows;$td++){
echo '<td><input type="number" name="etat" placeholder="nb d etat" /></td>';
}
echo "</tr>";
}
echo "</table>";
echo '<input type="submit" value="Create Table">';
echo '</form>'
?>
A: Yes it is possible but you have to create form by giving row and column number because you want to create matrix:
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
echo "<th> E".$tr." </th>";
for($td=1;$td<=$rows;$td++){
echo '<td><input type="number" name="etat_'.$tr.'_'.$td.'" placeholder="nb d etat" /></td>';
}
echo "</tr>";
}
echo "</table>";
echo '<input type="submit" name="submit" value="Create Table">';
echo '</form>';
in f.php fetch data :
if(isset($_POST['submit'])) {
print_r($_POST);
}
It gives you output:
Array
(
[etat_1_1] => 1 //means 1st row 1st column
[etat_1_2] => 2 //means 1st row 2nd column
[etat_1_3] => 3 //means 1st row 3rd column
[etat_2_1] => 4 //means 2nd row 1st column and so on...
[etat_2_2] => 5
[etat_2_3] => 6
[etat_3_1] => 7
[etat_3_2] => 8
[etat_3_3] => 9
[submit] => Create Table
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44403092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Daemon java process - is there such a thing? My java program creates a process in the following manner:
ProcessBuilder builder = new ProcessBuilder("phantomjs.exe crawl.js");
Process proc = builder.start();
In case the java program terminates abruptly (could always happen), the phantomjs process (which is not a java process) could stay alive and there would be no way to terminate it.
I want the phantomjs process to be terminated when the enclosing java process terminates (whether abruptly or not).
Is there a way to define the Process instance as a "daemon" object that terminates automatically when its super process (which is the java process executing the code above) terminates?
A: The API documentation seems pretty definite, no qualifications or weasel-wording:
The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously.
So the parent has to kill it, it won't go away when the parent terminates.
A: Not a great solution, but you could always check periodically the PID of the parent from the children.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35920139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: c++ mysql connection bad_alloc using c++ connector Trying to build a simple mysql connection, but getting a bad_alloc and I can't figure out how to solve this, even looking at similar posts
here is my code
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>
#include "mysql_connection.h"
#include "cppconn\driver.h"
#include "cppconn\statement.h"
#include "cppconn\connection.h"
#include "cppconn\exception.h"
#include "cppconn\prepared_statement.h"
#include "cppconn\statement.h"
using namespace std;
using namespace sql;
int main()
{
Driver *driver;
Connection *conn;
Statement *stmt;
driver = get_driver_instance();
conn = driver->connect("127.0.0.1:3306", "root", "root"); // breaks here
stmt = conn->createStatement();
stmt->execute("USE mydb");
return 0;
}
I'm using mysql-connector-c++-1.1.7
mysqlcppconn.lib is used as a dependencies
mysqlcppconn.dll is located in the same dir as the .exe is.
Here is the error Exception thrown at 0x000007FEFD39A06D in MysqlConn.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x000000000014F5D0.
Thanks
A: I also had this error. In my case I am compiling using VS2015 in Windows.
First time I choose compile static version of the MySQL lib. Then later I decided to compile the dynamic version. This time the error bad_alloc at memory went off.
The solution is rolling back the CPPCONN_PUBLIC_FUNC= configuration.
Go to project Property Pages, under C++ > Preprocessor > Preprocessor Definitions and remove the item CPPCONN_PUBLIC_FUNC=".
A: I had the same error on linux.
The error was : I was using g++-4.8 to build the project
The issue lies on the version of the build tools (gcc,msvs,clang) used to build the project
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39101671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Combine table and matrix with R I am performing an analysis in R. I want to fill the first row of an matrix with the content of a table. The problem I have is that the content of the table is variable depending on the data so sometimes certain identifiers that appear in the matrix do not appear in the table.
> random.evaluate
DNA LINE LTR/ERV1 LTR/ERVK LTR/ERVL LTR/ERVL-MaLR other SINE
[1,] NA NA NA NA NA NA NA NA
> y
DNA LINE LTR/ERVK LTR/ERVL LTR/ERVL-MaLR SINE
1 1 1 1 1 4
Due to this, when I try to join the data of the matrix with the data of the table, I get the following error
random.evaluate[1,] <- y
Error in random.evaluate[1, ] <- y :
number of items to replace is not a multiple of replacement length
Could someone help me fix this bug? I have found solutions to this error but in my case they do not work for me.
A: First check if the column names of the table exist in the matrix
Check this link
If it exists, just set the value as usual.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69815818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make a iOS WebView behave like a ebook reader Normally within a webview, when your page is too long, you can scroll vertically like a browser, that is the default.
I want to make this webview behave like a ebook reader, say when you need 3 pages to display the whole content, instead of scrolling vertically, you can slide to the next page which like a ebook reader (e.g. iOS Kindle app).
Any thoughts on how to implement this? Or any existing components I can use?
Cheer.
A: Very much depends on how much control you (want to) have on the html...
For complete layout control (magazine like) there's baker framework.
Or if you need a quick and dirty script auto generate html file with pagination (instapaper like), I'd use css3 multi-column layout, with some js to calculate the column needed. And use something like SwipeView to manage the scrolling.
A: This is not trivial, and there are a couple of HTML projects having to do with pagination. The ubiquitous jQuery also includes support for paginating HTML content.
Have look at this S.O. post for more details.
A: You can use UISwipeGestureRecognizer on UIWebView and move to the Page programmatically
Good Luck
A: To do this, you could start with a UIPageViewController and populate each page with a UIWebView, each scrolled down to a certain offset and disable scrolling of the underlying scroll view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11708451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Spring Boot Security: Why Strict-Transport-Security header is not including preload; when preload set to true I have a spring boot application where i have added WebSecurityConfigurerAdapter.
I want to have the response header strict-transport-security: max-age=16000000; includeSubDomains; preload;
I have added the below code to the SecurityConfig as:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers(headers ->
headers.httpStrictTransportSecurity(hstsConfig -> {
hstsConfig.preload(true);
hstsConfig.includeSubDomains(true);
hstsConfig.maxAgeInSeconds(31536000);
})
.contentSecurityPolicy(contentSecurityPolicy ->
contentSecurityPolicy
.policyDirectives("script-src 'self'")
)
.addHeaderWriter(new StaticHeadersWriter("X-My-Custom-Header","myvalue"))
);
http.csrf().disable();
}
The response header is not adding the "preload;" instead it looks like:
Strict-Transport-Security: max-age=31536000; includeSubDomains
Can someone please help me to understand what am I missing here?
Spring Security Config: v5.4.6
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68952339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In android, what can I use for a root element (View, ViewGroup, etc.) of my custom control which only allows a single child? Trying to write better-encapsulated custom views and composite controls.
The old way I would do this was to subclass a ViewGroup such as LinearLayout, like so...
public class RadioButton extends LinearLayout
{
private RadioButtonView radioButtonView;
private TextView textView;
public RadioButton(Context context)
{
super(context);
commonInit(context, null, 0);
}
public RadioButton(Context context, AttributeSet attrs)
{
super(context, attrs);
commonInit(context, attrs, 0);
}
public RadioButton(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
commonInit(context, attrs, defStyle);
}
private void commonInit(Context context, AttributeSet attrs, int defStyle)
{
View.inflate(context, R.layout.part_radio_button, this);
radioButtonView = (RadioButtonView) findViewById(R.id.radioButtonView);
textView = (TextView) findViewById(R.id.textView);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RadioButton, defStyle, 0);
String text = a.getString(R.styleable.RadioButton_text);
setText(text != null ? text : "Unset");
boolean isSelected = a.getBoolean(R.styleable.RadioButton_isSelected, false);
setIsSelected(isSelected);
a.recycle();
}
public String getText()
{
return textView.getText().toString();
}
public void setText(String newValue) { textView.setText(newValue); }
public boolean getIsSelected()
{
return radioButtonView.getIsSelected();
}
public void setIsSelected(boolean newValue){ radioButtonView.setIsSelected(newValue);}
}
The layout R.layout.part_radio_button would look like this (note the Merge tag)...
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<com.citi.mobile.reusable.ui.RadioButtonView
android:id="@+id/radioButtonView"
style="@style/DefaultRadioButtonView" />
<TextView
android:id="@+id/textView"
style="@style/DefaultRadioButtonText" />
</merge>
This worked really well ...at first! It looked like it properly handled automatic loading the layout so the user could simply 'new-up' the control, or just reference it in a layout file themselves.
But soon it became evident that there were issues with this approach.
*
*DataBinding which requires a root <layout /> tag.
*The <merge /> tag cannot be a child of the tag nor vice-versa.
*I couldn't define the default properties for the root control in the XML and had to do it programmatically in the constructor.
*Since I was setting them in the constructor, I also couldn't style them since the constructor was overriding their values. I couldn't simply set the constructor-set values first, because until they were loaded from the layout, there was nothing to set.
*I also realized by subclassing LinearLayout (or any other such control) I was also exposing that LinearLayout to whomever was using this, meaning they could change the orientation, etc.
Because of the above, especially #5, I realized I should do the following instead:
*
*Don't subclass LinearLayout directly as you're exposing it to the outside world when you do. Instead find a different root control to subclass.
*Because of the change in #1, you can now move LinearLayout back as the root of the layout portion of the layout.xml file (either directly, or under a <layout /> tag when data-binding
*Make the control you've chosen in #1 expose only the bare essentials (i.e. width, height, and whatever attributes you specifically want to expose.)
At this point, I'm starting to think what I need to do is subclass ViewGroup, or perhaps even View (as ViewGroup itself does) and enforce the one-child policy, but I'm not 100% sure, hence this question.
Note: In C#/WPF, they have a Panel class, which is similar to a ViewGroup, but they also have a ContentPresenter class which does exactly what I want... presents a single piece of content.
It's actually pretty slick in that not only can it present a UI component directly, but if you attempt to present something that isn't a UI component, like a (view)model object, it will actually apply a data-bound data template to that object based on its data type, which converts it to something for the UI. Even if there's no defined template for that specific data type, it will call toString() on it and spit out the equivalent of a TextView.
As cool as that automatic data-presentation capability is though, I'm really only after the first part... the ability to display a single child view(group) which is somewhat protected from the outside world.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45330741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Run Multiple timer simultaneously in datagrid wpf I am new to the Window Presentation Foundation (WPF). I have a Data grid showing data very well but I now want to show time in Time column dynamic like call time which is changed every second for every row of data.
here is my class
public class UserTab
{
public int Id { get; set; }
public string AgentName { get; set; }
public string Extension { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public string RowDetail { get; set; }
public int ActiveParticipants { get; set; }
public int HeldParticipants { get; set; }
public int Duration { get; set; }
public string CallStatus { get; set; }
public string QueueName { get; set; }
public string Time { get; set; }
public string CallStatusColor { get; set; }
public bool isRowDetail { get; set; }
public List<UserTab> GetUsers()
{
List<UserTab> users = new List<UserTab>();
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:40:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42033", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#d70d0d", Time = "00:05:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Not Ready - Lunch", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "John Doe", Extension = "42034", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:30", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42035", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:06:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "AJohn Doe", Extension = "42036", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:05:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "BJohn Doe", Extension = "42037", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:55", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "CJohn Doe", Extension = "42038", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:40", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "DJohn Doe", Extension = "42039", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:55:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "EJohn Doe", Extension = "42003", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:06:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "EJohn Doe", Extension = "42053", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:10:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "FJohn Doe", Extension = "42073", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:20", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "GJohn", Extension = "42078", Name = "Sammy", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:41", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "HJohn Doe", Extension = "42083", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:25:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "IJohn Doe", Extension = "42093", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "JJohn Doe", Extension = "42013", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
return users;
}
}
public partial class Tabs : Window
{
InitializeComponent();
List<UserTab> us = new List<UserTab>();
UserTab user = new UserTab();
us = user.GetUsers();
dgSimple.ItemsSource = us
}
here is DataGrid
<DataGrid Name="dgSimple" VerticalAlignment="Center" VerticalContentAlignment="Center" CellStyle="{StaticResource Body_Content_DataGrid_Centering}" Height="350" EnableRowVirtualization="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Agent Name" Binding="{Binding AgentName}" IsReadOnly="True" />
<DataGridTemplateColumn SortMemberPath="CallStatus" CanUserSort="True" Header="Status" CellTemplate="{StaticResource StatusTemplate}"/>
<DataGridTextColumn Header="Time" Binding="{Binding Time}" IsReadOnly="True"/>
<DataGridTextColumn Header="Extension" Binding="{Binding Extension}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
A: A simple sample based on your code, it refresh the DataGrid every 1 second.
*
*In class Tabs, start a new thread by StartMockValue to mock Time value.
*In StartRefreshDataGrid, start a new thread to determine whether to update the DataGrid
*If the Time is different from DisplayTime, then set UserTab -> DisplayTime to notify property changed.
*Finally, the DataGrid updated by new data.
Tabs.xaml
<Window x:Class="TestWpfApp.Tabs"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<StackPanel>
<DataGrid Name="dgSimple" VerticalAlignment="Center" VerticalContentAlignment="Center" Height="350"
EnableRowVirtualization="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Agent Name" Binding="{Binding AgentName}" IsReadOnly="True" />
<DataGridTemplateColumn SortMemberPath="CallStatus" CanUserSort="True" Header="Status"/>
<!--NOTE: bind 'DisplayTime' instead of 'Time'-->
<DataGridTextColumn Header="Time" Binding="{Binding DisplayTimeString}" IsReadOnly="True"/>
<DataGridTextColumn Header="Extension" Binding="{Binding Extension}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Window>
Tabs.xaml.cs
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace TestWpfApp
{
public partial class Tabs : Window
{
public Tabs()
{
InitializeComponent();
this.Users = new List<UserTab>();
UserTab user = new UserTab();
this.Users = user.GetUsers();
dgSimple.ItemsSource = this.Users;
this.StartMockValue();
this.StartRefreshDataGrid();
}
private List<UserTab> Users;
private void StartMockValue()
{
// NOTE: this is a thread to mock the business logic, it change 'Time' value.
Task.Run(() =>
{
var rando = new Random();
while (true)
{
foreach (var user in this.Users)
{
if (rando.Next(0, 3) == 1)
{
user.Time = user.Time + 1;
}
}
Thread.Sleep(1000);
}
});
}
public void StartRefreshDataGrid()
{
// NOTE: this is a thread to update data grid.
Task.Run(() =>
{
while (true)
{
foreach (var user in this.Users)
{
// NOTE: update if the time changed.
if (user.DisplayTime != user.Time)
{
user.DisplayTime = user.Time;
}
}
// NOTE: refresh the grid every seconds.
Thread.Sleep(1000);
}
});
}
}
}
UserTab.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace TestWpfApp
{
public class UserTab : INotifyPropertyChanged
{
public int Id { get; set; }
public string AgentName { get; set; }
public string Extension { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public string RowDetail { get; set; }
public int ActiveParticipants { get; set; }
public int HeldParticipants { get; set; }
public int Duration { get; set; }
public string CallStatus { get; set; }
public string QueueName { get; set; }
// NOTE: this is the 'real time', some business thread will update the value.
public int Time { get; set; }
private int displayTime;
// NOTE: this is the 'displayed time' in the DataGrid.
public int DisplayTime
{
get => displayTime;
set
{
displayTime = value;
this.OnPropertyChange(nameof(this.DisplayTimeString));
}
}
public string DisplayTimeString => $"{displayTime / 60 / 60}:{displayTime / 60 % 60}:{displayTime % 60}";
public string CallStatusColor { get; set; }
public bool isRowDetail { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public List<UserTab> GetUsers()
{
var maxSeconds = 24 * 60 * 60;
var random = new Random();
List<UserTab> users = new List<UserTab>();
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42033", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#d70d0d", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Not Ready - Lunch", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "John Doe", Extension = "42034", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42035", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "AJohn Doe", Extension = "42036", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "BJohn Doe", Extension = "42037", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "CJohn Doe", Extension = "42038", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "DJohn Doe", Extension = "42039", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "EJohn Doe", Extension = "42003", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "EJohn Doe", Extension = "42053", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "FJohn Doe", Extension = "42073", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "GJohn", Extension = "42078", Name = "Sammy", Birthday = new DateTime(1991, 9, 2) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "HJohn Doe", Extension = "42083", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "IJohn Doe", Extension = "42093", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "JJohn Doe", Extension = "42013", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
return users;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70445744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTTPD ReverseProxy ProxyPass directive ending in wrong Location header HTTPD is configure as following:
#redirectder edit Location "(^http[s]?://)([^/]+)" "" port 80 to secure
<VirtualHost *:80>
ServerName mitestui02.sn.test.net
#ServerAlias server server2.domain.com server2
ServerAdmin [email protected]
ErrorLog /var/log/test/iiq/appserver/apache-error.log
CustomLog /var/log/test/iiq/appserver/apache-access.log common
Redirect /identityiq/ https://mitestui02.sn.test.net/identityiq/
Redirect / https://mitestui02.sn.test.net/identityiq/
</VirtualHost>
#redirect to port 8080 on localhost
<VirtualHost *:443>
ServerName mitestui02.sn.test.net
# ServerAlias mitestui02 mitestui02.sn.test.net
ServerAdmin [email protected]
SSLProxyEngine On
SSLEngine On
#allow only tls
SSLProtocol -all +TLSv1.2
SSLHonorCipherOrder on
SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...
SSLCertificateFile /etc/opt/test/iiq/appserver/secure/ssl/web-iiq.crt
SSLCertificateKeyFile /etc/opt/test/iiq/appserver/secure/ssl/apache-iiq.key
Redirect /identityiq/ https://mitestui02.sn.test.net/
Redirect / https://mitestui02.sn.test.net/identityiq/
ProxyRequests Off
ProxyPreserveHost On
ProxyPass /identityiq/ http://localhost:8080/identityiq/
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^OPTIONS
RewriteRule .* - [F]
<If "%{THE_REQUEST} =~ m#.jsf/?[?\s]#">
Header add X-UI-Source "mitestui02"
Header add X-UA-Compatible "IE=edge"
Header add Referrer-Policy "strict-origin-when-cross-origin"
Header add Feature-Policy "microphone 'none'; geolocation 'none'; usb 'none'; payment 'none'; document-domain 'none'; camera 'none'; display-capture 'none'; ambient-light-sensor 'none'"
Header add Permissions-Policy "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()"
Header add Strict-Transport-Security "max-age=63072000; includeSubDomains"
Header add Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval'"
Header add X-Content-Type-Options "nosniff"
Header always edit Set-Cookie (.*) "$1; Secure; SameSite=Strict"
Header onsuccess edit Set-Cookie (.*) "$1; Secure; SameSite=Strict"
</If>
</VirtualHost>
When I connect to the front-end URL, https://mitest.sn.test.net/ I get redirected with a response code 302 and Location header pointing to https://mitestui02.sn.test.net/identityiq/ instead of https://mitest.sn.test.net/identityiq/ .
This doesn't happen when connecting to https://mitest.sn.test.net/identity/ directly.
I have tried with different ProxyPass and ProxyPassReverse directives and also rewriting the Location header, nothing seems to help.
Thanks
A: So the issue seemed to be related to the Redirect directives.
We removed them and added the following for 443:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301,NE]
# Redirect / to /identiyiq
RedirectMatch ^/$ /identityiq
We removed them and added the following for 80:
Redirect permanent / https://mitestui02.sn.test.net/
Now it is working as expected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69894703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using std::size in a function i have written the following code. The std::size() function ist executing properly in the main() function but not in the getMin() function. Why?
#include <iostream>
int getMin(int numbers[]) {
int temp = numbers[0];
int sizeA = std::size(numbers);
for (int i = 1; i < sizeA; i++) {
if (temp > numbers[i])
temp = numbers[i];
}
return temp;
}
int main()
{
int numbers[5] = { 5, 5, -2, 29, 6 };
std::cout << getMin(numbers) << " with Size of "<< std::size(numbers) << std::endl;
std::cin.get();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67990671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Maps API Solid State Borders When creating a map, the state borders keep coming up as dashed lines. Is there any way to make them solid? I am working with the province settings in the json but I cannot seem to find a directive for solid line, perhaps in .stroke?
A: If you can't do it with Styled Maps (and I don't see how you can right now), you could use Styled Maps to hide the state boundaries:
{
featureType: 'administrative.province',
elementType: 'geometry.stroke',
stylers: [{visibility: '#off'}]
},
Then add your own (note that you need a source of the boundaries somewhat consistent with the map tiles).
Example of using borders from a FusionTable
proof of concept fiddle
proof of concept fiddle with styled borders
code snippet:
function initMap() {
// Styles a map in night mode.
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 40.674,
lng: -73.945
},
zoom: 7,
styles: [{
featureType: 'administrative.province',
elementType: 'geometry.stroke',
stylers: [{
visibility: '#off'
}]
}, ]
});
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'kml_4326',
from: '19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA'
},
map: map
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53337405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jquery form plugin does not work I am a newbie programmer. I have been stuck for two days with a simple coding problem.I try to use jquery form plugin for submitting a form to another page and get feedback from that page.The problem is the plugin is not working, the form is submitted normally without feedback. Here is the code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<div id='preview'></div>
<form action='ajaxcall.php' id='upload_pic' enctype='multipart/form-data' method='post'>
<input type='file' id='pic' name='picture'>
<input type='submit' id='sub'>
</form>
var options=
{
target:'#preview',
url:'ajaxcall.php'
};
$(document).ready(function(){
$("#sub").click(function(){
$('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>");
$('#upload_pic').ajaxForm(options).submit();
});
});
Here is my ajaxcall.php page code
if(!empty($_FILES['picture']['size']))
{
echo "<img src='images/197.jpg'>";
}
Expectation was the echoed image would feedback but the page is simply redirected to ajaxcall.php page.I understand that ajaxForm() function is not working. The same question I am asking two times in SO, but still no satisfactory solution. But why? Please help.Thanks in advance.
A: Use adeneo's answer, because I also do not see why you would use this plugin, but here could be a few reasons why what you have isn't working:
In the examples from the plugin's website, you should
*
*bind to the form, not the button
*use the beforeSubmit option
*Remove the submit() from the end of your call, not sure why it is
there
*Watch console for any errors
var options=
{
target:'#preview',
url:'ajaxcall.php',
beforeSubmit: showLoading,
error: function(e){
alert("Error: " + e);
}
};
function showLoading(){
$('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>");
}
$(document).ready(function(){
$("#upload_pic").ajaxForm(options);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15598535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FileDialog does not work in some excel versions VBA I have a code that works in the excel version 2010 normally, but in the 2013 version does not. Take a look.
Sub select_strategy()
'Subroutine that lets the user select a strategy table
'
'Declare local variables
Dim strategyFileDialog As Office.FileDialog
'Declare local variables
Dim intStrategySelection As Integer
'Initialize global variables
Call initialize_global_variables
' Allows the user to select the strategy table to use
Set strategyFileDialog = Application.FileDialog(msoFileDialogFilePicker)
With strategyFileDialog
.Title = "Select Strategy Table"
.InitialFileName = ActiveWorkbook.Path
.AllowMultiSelect = False
End With
intStrategySelection = strategyFileDialog.Show 'updates cell only if a file is selected
If intStrategySelection <> 0 Then
wsMain.Cells(2, 3) = strategyFileDialog.SelectedItems(1)
Else
wsMain.Cells(2, 3) = ""
End If
End Sub
The error for the 2013 version is Compile error: Cant find project or library.
Any ideas how to solve it?
A: To use late binding use the FileDialog() function from the Excel.Application Object. Excel.Application.FileDialog() Is a function that returns a FileDialog Object for an open Workbook. If you declare a variable as a specific object such as Office.FileDialog it will create the object of the version that is used in the VBA reference the code was written with and at runtime on a different pc will ignore other version references and look for the specific version that the variable was declared with.
You can use the reference to the active workbook but is not explicitly needed in Excel
Dim strategyFileDialog As Object
Set strategyFileDialog = ActiveWorkbook.Application.FileDialog(3)
'Filedialog Enumerations:
'msoFileDialogFilePicker = 3 File picker dialog box.
'msoFileDialogFolderPicker = 4 Folder picker dialog box.
'msoFileDialogOpen = 1 Open dialog box.
'msoFileDialogSaveAs = 2 Save As dialog box
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40889976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GoCD - Task Plugins not adding tasks I have setup a GoCD server and agent (on a Windows machine if that matters). I am using it to build a .NET application. I have installed a few Task plugins (Powershell, Xunit-converter) and when I restart the server I see those as loaded and installed without issue in the plugin admin screen.
However, when I go to create or edit a job, I do not see these new tasks in the "Add Task" dropdown. I can get around the powershell one by using a Custom command, but I need to be able to convert my MsTest ouptut to Xunit so that it can display the results in the Test Results Tab.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43212589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to get the value in the shell variable #!/bin/ksh
for i in 1 2 3 4 5
do
echo "hello world"> $i
done
v = echo $?
if [ $v -eq 0 ]; then
echo " Completed"
else
echo "Not completed"
fi
Unable to get the value in v = echo s?, due to this if condition always fails
A: Wrong logic use just this (direct assignation):
v=$?
A: Instead of v = echo $?
Either write
v=`echo $?`
OR
v=$?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25602133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Xcode 9.2 - Can't see "iOS Simulator" within run destination I'm trying to run my application with a Xcode simulator but I can't select any simulator since my only options are the one showed in this screenshot
As per apple guide, I should see the section "iOS Simulator" below "Build Only Device", but within my Xcode that section is missing.
What I've already tried to solve the issue:
*
*Set iOS Deployment Target under Project > Info > Deployment Target and restart Xcode.
*Check if there are simulators installed within Xcode>Preferences>Components. There are Simulator 11.0 and 11.1
*Check if there are simulator within Window > Device and Simulator > Simulators. There are around 30 simulators.
*Restart Xcode
*Reinstall Xcode
I am using Xcode 9.2 and macOS version 10.12.6.
Does anyone knows what could be the problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49301814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Start and Stop indicatorView and put it in centre tableView in swift I am using a spinner in bottom of tableView to show the spinner when data is reloading.
var sneakers: [sneakerModel] = []
I stored all my data in sneakers and returning the count on numberOfRowsInSection method.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sneakers.count
}
And now I am using willDisplay method to show the spinner in bottom.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
if indexPath.row == self.sneakers.count - 1 && !didPageEnd {
pageNo += 1
getSneakerSearch()
}
if (indexPath.row == self.sneakers.count) {
self.tableView.tableFooterView?.isHidden = true
} else {
if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex {
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.activityIndicatorViewStyle = .whiteLarge
spinner.color = .red
spinner.startAnimating()
spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(5), width: tableView.bounds.width, height: CGFloat(44))
self.tableView.tableFooterView = spinner
self.tableView.tableFooterView?.isHidden = false
}
}
}
But it is not working. How can I stop spinner when no more data is loading. Please help?
Getting the data from api.
func getSneakerSearch() {
let param: [String:Any] = [ "search_term" : searchText ?? "","page": pageNo, "token": commonClass.sharedInstance.userToken ?? ""]
if self.pageNo == 0{
commonClass.sharedInstance.startLoading()
}
Alamofire.request(Constants.API.url("search"), method: .post, parameters: param, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
(response:DataResponse<Any>) in
commonClass.sharedInstance.stopLoading()
guard let json = response.result.value as? [String:Any] else {return}
printD(json)
guard let status = json["status"] as? Int else {return}
printD(status)
if status == 1 {
guard let data = json["data"] as? [[String:Any]] else { return}
printD(data)
if self.pageNo == 0 {
self.sneakers.removeAll()
}
for item in data {
guard let description = item["description"] as? String else { return}
printD(description)
self.sneakers.append(sneakerModel(response: item))
}
self.didPageEnd = data.count < limitPerPage
}
DispatchQueue.main.async {
self.reloadData()
}
}
}
A: Create loadingview in viewdidload
override func viewDidLoad() {
super.viewDidLoad()
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.activityIndicatorViewStyle = .whiteLarge
spinner.color = .red
spinner.startAnimating()
spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(5), width: tableView.bounds.width, height: CGFloat(44))
self.tableView.tableFooterView = spinner
self.tableView.tableFooterView?.isHidden = true
}
and update willDisplay cell
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
if indexPath.row == self.sneakers.count - 1 && !didPageEnd {
pageNo += 1
getSneakerSearch()
}
}
Update getSnackerSearch func:
...
if self.pageNo == 0{
commonClass.sharedInstance.startLoading()
}else{
self.tableView.tableFooterView?.isHidden = false
}
Alamofire.request(Constants.API.url("search"), method: .post, parameters: param, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
(response:DataResponse<Any>) in
if self.pageNo == 0{
commonClass.sharedInstance.stopLoading()
}else{
self.tableView.tableFooterView?.isHidden = true
}
}
...
A: For center of you spinner to tableview you can follow these steps to do it. You don't need to provide height and width for spinner.
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.activityIndicatorViewStyle = .whiteLarge
spinner.color = .red
spinner.startAnimating()
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
spinner.center=CGPointMake(self.tableView.center.x, self.tableView.center.y- topBarHeight);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53442594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Incoming IP addresses for webhooks? What IP Address range do your webhooks come from? We need to white list them to receive your Copyleaks results to our web server.
Thank You,
A: As of now, Copyleaks API not arriving from fixed list of IP addresses. But, you have other alternatives to securing your endpoints. The options described here:
https://api.copyleaks.com/documentation/v3/webhooks/security
Another option you have to secure your endpoints is to add "Authentication" header to the webhook request with a private secret in its value. With Copyleaks API you have the ability to specify the headers that will arrive to your endpoints.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75597132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP - Refactoring / improving Ifs I have the following data structure;
Array ( [0] => Array ([suit] => c [rank] => A )
[1] => Array ( [suit] => d [rank] => A ) )
I want to test if these cards are certain values and display an appropriate message;
if (
(($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "A"))
|| (($hand[0]['rank'] == "K") && ($hand[1]['rank'] == "K"))
|| (($hand[0]['rank'] == "Q") && ($hand[1]['rank'] == "Q"))
|| (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "K"))
|| (($hand[0]['rank'] == "K") && ($hand[1]['rank'] == "A"))
) {
echo "Action: Raise pre-flop. Re-raise if already raised.<br />\n";
}
if (
(($hand[0]['rank'] == "7") && ($hand[1]['rank'] == "7"))
|| (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "J") && ($hand[0]['suit'] == $hand[1]['suit']))
|| (($hand[0]['rank'] == "J") && ($hand[1]['rank'] == "Q") && ($hand[0]['suit'] == $hand[1]['suit']))
|| (($hand[0]['rank'] == "10") && ($hand[1]['rank'] == "J") && ($hand[0]['suit'] == $hand[1]['suit']))
) {
echo "Action: Worth a call pre-flop (provided no-one has raised).<br />\n";
}
I have simplified the IFs by removing some of the conditions.
Can anyone suggest a better way of doing this?
A: Maybe try to use in_array() method
php.net in_array()
A: Try to use references like this:
$rank0 =& $hand[0]['rank'];
$rank1 =& $hand[1]['rank'];
if (
($rank0 == "A" && $rank1 == "A")
|| (...)
Just, as the first step to code minimization
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19425606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UserDefine Runtime Attributes doesn't work in Xcode8.0 It seems like xcode8.0 does not set the value of user runtime attributes when set from storyboard.What am trying to do is simple,set the label inside a cell as corneRadius of 10 which has width/height of 20. When i try to debug the views i got the following output which has weird width height(1000/1000..?)
_UILabelLayer:0x600000283750; position = CGPoint (500 500); bounds = CGRect (0 0; 1000 1000); delegate = >; opaque = YES; allowsGroupOpacity = YES; cornerRadius = 10; contentsMultiplyColor = (null); rasterizationScale = 2; contentsScale = 2>
A: i think it's helpful for you.
and also check the clipToBounds
Checking "Clip Subviews" is equal to the code addMessageLabel.clipsToBounds = YES;
A: You can use this code and method on your controller
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourLabel.clipsToBounds = true
yourLabel.layoutIfNeeded()
print("Frame ------> ",yourLabel.frame)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40506568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rails "where" statement: How do i ignore blank params I am pretty new to Rails and I have a feeling I'm approaching this from the wrong angle but here it goes... I have a list page that displays vehicles and i am trying to add filter functionality where the user can filter the results by vehicle_size, manufacturer and/or payment_options.
Using three select form fields the user can set the values of :vehicle_size, :manufacturer and/or :payment_options parameters and submit these values to the controller where i'm using a
@vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, :vehicle_size => params[:vehicle_size] )
kind of query. this works fine for individual params (the above returns results for the correct vehicle size) but I want to be able to pass in all 3 params without getting no results if one of the parameters is left blank..
Is there a way of doing this without going through the process of writing if statements that define different where statements depending on what params are set? This could become very tedious if I add more filter options.. perhaps some sort of inline if has_key solution to the effect of:
@vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, if(params.has_key?(:vehicle_size):vehicle_size => params[:vehicle_size], end if(params.has_key?(:manufacturer):manufacturer => params[:manufacturer] end )
A: You can do:
@vehicles = Vehicle.order('vehicles.id ASC')
if params[:vehicle_size].present?
@vehicles = @vehicles.where(vehicle_size: params[:vehicle_size])
end
Or, you can create scope in your model:
scope :vehicle_size, ->(vehicle_size) { where(vehicle_size: vehicle_size) if vehicle_size.present? }
Or, according to this answer, you can create class method:
def self.vehicle_size(vehicle_size)
if vehicle_size.present?
where(vehicle_size: vehicle_size)
else
scoped # `all` if you use Rails 4
end
end
You call both scope and class method in your controller with, for example:
@vehicles = Vehicle.order('vehicles.id ASC').vehicle_size(params[:vehicle_size])
You can do same thing with remaining parameters respectively.
A: The has_scope gem applies scope methods to your search queries, and by default it ignores when parameters are empty, it might be worth checking
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18184965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XText - get content (compiled value) of XExpression I have a certain part of my XText grammer that defines a block for classes that shall print all its expressions. The XText grammar part for this looks as follows:
Print:
{Print}
'print' '{'
print += PrintLine*
'}';
PrintLine:
obj += XExpression;
Now I use the following inferrer code to create a print() method:
Print: {
members += feature.toMethod('print', typeRef(void)) [
body = '''
«FOR printline : feature.print»
System.out.println(«printline.obj»);
«ENDFOR»
'''
]
}
Ok, I go ahead and test it with the following code in a class:
print {
"hallo"
4
6 + 7
}
And the result is the following:
public void print() {
System.out.println([org.eclipse.xtext.xbase.impl.XStringLiteralImpl@20196ba8 (value: hallo)]);
System.out.println([org.eclipse.xtext.xbase.impl.XNumberLiteralImpl@7d0b0f7d (value: 4)]);
System.out.println([<XNumberLiteralImpl> + <XNumberLiteralImpl>]);}
Of course, I was hoping for:
public void print() {
System.out.println("hallo");
System.out.println(4);
System.out.println(6+7);
}
I understand that I might have to call the compiler somehow in the inferrer for «printline.obj», but I am really not sure how.
A: i think you are doing this on a wrong basis. this sounds to me like an extension of xbase, not only a simple use.
import "http://www.eclipse.org/xtext/xbase/Xbase" as xbase
Print:
{Print}
'print'
print=XPrintBlock
;
XPrintBlock returns xbase::XBlockExpression:
{xbase::XBlockExpression}'{'
expressions+=XPrintLine*
'}'
;
XPrintLine returns xbase::XExpression:
{PrintLine} obj=XExpression
;
Type Computer
class MyDslTypeComputer extends XbaseTypeComputer {
def dispatch computeTypes(XPrintLine literal, ITypeComputationState state) {
state.withNonVoidExpectation.computeTypes(literal.obj)
state.acceptActualType(getPrimitiveVoid(state))
}
}
Compiler
class MyDslXbaseCompiler extends XbaseCompiler {
override protected doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) {
if (obj instanceof XPrintLine) {
appendable.trace(obj)
appendable.append("System.out.println(")
internalToJavaExpression(obj.obj,appendable);
appendable.append(");")
appendable.newLine
return
}
super.doInternalToJavaStatement(obj, appendable, isReferenced)
}
}
XExpressionHelper
class MyDslXExpressionHelper extends XExpressionHelper {
override hasSideEffects(XExpression expr) {
if (expr instanceof XPrintLine || expr.eContainer instanceof XPrintLine) {
return true
}
super.hasSideEffects(expr)
}
}
JvmModelInferrer
def dispatch void infer(Print print, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
acceptor.accept(
print.toClass("a.b.C") [
members+=print.toMethod("demo", Void.TYPE.typeRef) [
body = print.print
]
]
)
}
Bindings
class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {
def Class<? extends ITypeComputer> bindITypeComputer() {
MyDslTypeComputer
}
def Class<? extends XbaseCompiler> bindXbaseCompiler() {
MyDslXbaseCompiler
}
def Class<? extends XExpressionHelper> bindXExpressionHelper() {
MyDslXExpressionHelper
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34434562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode Could not determine the dependencies of task :app:compileDebugJavaWithJavac.
> Could not resolve all task dependencies for configuration ':app:debugAnnotationProcessorClasspath'.
> Could not resolve androidx.databinding:databinding-compiler:3.4.2.
Required by:
project :app
> No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.
> No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.
> No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.
A: Uncheck "Offline work" in Android Studio:
File -> Settings -> Gradle -> Global Gradle Settings
or in OSX:
Preferences -> Gradle -> Global Gradle Setting
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60808458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UNMET PEER DEPENDENCY ISSUE I have been trying to install the ngx bootstrap from [https://ng-bootstrap.github.io/#/getting-started]
by entering the command: npm install ngx-bootstrap --save
but the result is this:
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY [email protected] - 3
+-- [email protected]
+-- UNMET PEER DEPENDENCY popper.js@^1.12.3
`-- UNMET PEER DEPENDENCY [email protected]
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN @ng-bootstrap/[email protected] requires a peer of @angular/core@^4.0.3 but none was installed.
npm WARN @ng-bootstrap/[email protected] requires a peer of @angular/common@^4.0.3 but none was installed.
npm WARN @ng-bootstrap/[email protected] requires a peer of @angular/forms@^4.0.3 but none was installed.
npm WARN [email protected] requires a peer of [email protected] - 3 but none was installed.
npm WARN [email protected] requires a peer of popper.js@^1.12.3 but none was installed.
npm WARN [email protected] requires a peer of @angular/common@>=4.3.0 || >5.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/compiler@>=4.3.0 || >5.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/core@>=4.3.0 || >5.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/forms@>=4.3.0 || >5.0.0 but none was installed.
npm WARN [email protected] requires a peer of typescript@>=2.3.0 but none was installed.
I do not understand what's happening.
I am fairly new to Angular 2 and the relevant technologies. Would appreciate your help ! Thank you.
A: hello you need to install your perDependencies, if you install a package that depends on specific versions of other packages, If it didn't find the correct version of package then "Peer dependency" is unmet, try this:
npm install -g npm-install-peers
npm-install-peers
this will install peerDependencies
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47485983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wraping text within a table's td I am working on trying to clean up a customers evaluation software. In this example, the text doesn't wrap within the box. Adding a fixed size to the table doesn't help, as the information called from the SQL database just places it on top with no warping.
<tr>
<td valign="bottom" align="center"><br />
<table style="background-color: #EFEFEF; box-shadow: 5px 5px 5px #999; table-layout:fixed; width:400px" border=1 rules=none frame=box cellpadding="5">
![enter image description here][1]<tr><td width=250px height="90px" valign="top"><pre>' . base64_decode($eval['note']) . '</pre></td></tr>
</table>
</td>
</tr>
What steps should I look at doing or code should I add to fix this formatting error? Attached is a screen shot of the UI.
Thank you,
Paul
A: You are inserting your data inside a <pre> block, effectively telling the browser not to wrap the text. I assume you do this so that literal newlines in the 'note' data are indeed printed.
To alter wrapping space-characters and newline functionality of an element, you can use the CSS white-space property. So, to get what you want (both wrapping AND literal newlines), you can set white-space to either pre-line or pre-wrap, depending on your need. Eg. change the <pre> to
...<pre style="white-space:pre-wrap;">' . base64_decode($eval['note']) . '</pre>...
See the reference for more details
Good luck,
bob
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27195309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android JSON Get via HttpURLConnection error 405 so I'm trying to do a GET Request to my web service, and since I saw that the HttpGet class is being deprecated, I try to use the HttpURLConnection class instead, and I used it successfully with a 'POST' method... however when I try to do a simple 'GET' request - I get a 405 error (bad method).
I tested the link in DHC, and the link is fine.
Here's my method:
public JSONObject getClientByDeviceId (String link) {
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setAllowUserInteraction(false);
// conn.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
if (conn.getResponseCode() != 200) {
Log.e("conn", "Error code: " + conn.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
if (returnedObject != null) {
Log.e("conn", "If 400, this is the object gained: " + returnedObject.getString("Message"));
} else {
Log.e("conn", "didn't get any JSON object");
}
conn.disconnect();
return returnedObject;
}
else {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Log.e("conn", "GREAT SUCCESS !!: " + conn.getResponseCode());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
return returnedObject;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Normally I would say that this problem is caused by trying to do a 'GET' request in a 'POST' URL. But without the two HttpGet and HttpPost classes I don't really know where to turn, all the properties that are commented out are like that because I tried them in the POST request and now I deleted one by one to try to get the method to work.
Any ideas ? or reference to an updated guide on how to properly use that HttpURLConnection class, since I couldn't find one.
Thanks in advance !
A: Solved it, apparently this code needed to be removed:
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
I guess it was because I gave a GET URL and put that outputStream in my code and that caused the issues.
I still however don't understand why I got the "405: method GET not allowed" whereas I think I should have gotten the opposite: "POST" not allowed...
Anyway that is my solution, thanks a lot for your help guys !
A: HTTP 405 is caused by bad method call (Method not Allowed). That means you called GET method on POST request or vice-versa. You should add handling for you GET method on your Web-Service to get it working.
A: For anyone still reaching here from a search engine, my solution was similar -
I removed the line "conn.setDoOutput(true);" (or set it to false)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29206860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Angular 2 : How to keep two methods from repeating How can I implement my if/else statement only once so that I don't repeat this fragment of code in my header component as shown below:
export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts
@ViewChild('navTrigger') navTrigger: ElementRef;
isMenuShown: false;
constructor(private layoutService: LayoutService, private renderer: Renderer) { }
menuToggle(event: any) {
if (this.navTrigger.nativeElement.classList.contains('opened')) {
this.navTrigger.nativeElement.classList.remove('opened');
} else {
this.navTrigger.nativeElement.classList.add('opened');
}
}
onMenuSelect(event: any) {
this.isMenuShown = false;
if (this.navTrigger.nativeElement.classList.contains('opened')) {
this.navTrigger.nativeElement.classList.remove('opened');
} else {
this.navTrigger.nativeElement.classList.add('opened');
}
}
}
A: souldn't you just do this?
export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts
@ViewChild('navTrigger') navTrigger: ElementRef;
isMenuShown: false;
constructor(private layoutService: LayoutService, private renderer: Renderer) { }
menuToggle(event: any) {
if (this.navTrigger.nativeElement.classList.contains('opened')) {
this.navTrigger.nativeElement.classList.remove('opened');
} else {
this.navTrigger.nativeElement.classList.add('opened');
}
}
onMenuSelect(event: any) {
this.isMenuShown = false;
this.menuToggle(event); // Must apply the event binding as well
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43048682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Viewing Equirectangular Map I'm writing an equirectangular map viewer, all the stuff I have found so far are about the projection, conversions and inverse ones, which is the easiest part.
I don't want to use OpenGL or DirectX sphere texture solutions, I want to draw the image pixel by pixel. The only problem I have is in transformation of the viewer's camera rectangle.
I mean, I have a rectangle through which the viewer shows the equivalent pixels on the map. When viewer looks up or down, or left or right, this view changes, but the changes are not linear, even in a spherical coordination system. As the rectangle's dimensions should kept constant in a Cartesian sense, otherwise we will have a deformation.
Can anyone tell me how to solve this problem? A link to a good document, or a hint to where I start is all that I need. Thanks in advance.
A: Ok, nobody answered it, and I figured it out. There are two "practical" solutions, first one is using the Quaternions. You can define a 3d rectangle as a view and then rotate it using quaternions. After that you can sweep on the resulting rectangle, and use the reverse transforms to get the map coordinates. The other solution, which seems faster to me, is using Euler's rotation matrices. Just pay attention to use ArcTan2 instead of ArcTan function, because you need 2*PI coverage. That's all I wanted!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9743017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jQueryUI add click function for multiple buttons I have a page with some number of info dialog boxes (5 in this example). The objective is to have a variable number of info boxes on a page each called by a unique button. When the button is clicked, any other box is closed and the current box appears. Instead of trying to keep track of which box was opened or about to open, I thought I'd simply close all the boxes and open the current info box.
The code below works: the first for loop initializes all of the dialog boxes and the closeBoxes() function closes any dialog that's open before opening the assigned dialog box. However it seems like I should be able to loop through the .click(function()..) and add any number of info boxes. I've tried $("#btn"+i)...("#info"+i) in a loop, but that simply doesn't work.
var TotalInfoBoxes=5;
for ( var i=1; i<=TotalInfoBoxes; i++) {
$("#info"+i).dialog({ autoOpen: false });
}
$("#btn1").click(function() { closeBoxes(); $("#info1").dialog( "open" ); });
$("#btn2").click(function() { closeBoxes(); $("#info2").dialog( "open" ); });
$("#btn3").click(function() { closeBoxes(); $("#info3").dialog( "open" ); });
$("#btn4").click(function() { closeBoxes(); $("#info4").dialog( "open" ); });
$("#btn5").click(function() { closeBoxes(); $("#info5").dialog( "open" ); });
function closeBoxes() {
for (var i=1; i<=TotalInfoBoxes; i++){
$("#info"+i).dialog("close");
}
}
The dialog box is an elegant solution, but I need some more generic code as I may have 20 or 30 info boxes on a given page. Greatly appreciate your input.
A: for close dialog box simple use by this all dialog box close
they all inherit the same class, this is the best way to select all and close by:
$(".ui-dialog-content").dialog("close");
A: make sure that the buttons and dialogs have a common class say btn for buttons & info for your dialogs
$(".btn").on('click',function(e){
closeBoxes();
var index=$(this).index();
$(".info:eq("+index+")").dialog("open");
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18566190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to cleanly stub out REST client when in test environment I have a basic model like the following
class MyModel
def initialize(attrs)
@attrs = attrs
@rest_client = Some::REST::Client.new
end
def do_a_rest_call(some_str)
@rest_client.create_thing(some_str)
end
end
For testing purposes, I don't want @rest_client to make remote calls. Instead, in a test environment, I just want to make sure that @rest_client gets called with a specific some_str when it goes through certain branches of code.
In an ideal world, I'd have an assertion similar to:
expect(my_model_instance).to.receive(do_a_rest_call).with(some_str) where in the test I will pass some_str to make sure it's the right one.
What's the best way to do this using RSpec 3.8 and Rails 5.2.2?
A: A solution that should work without any additional gems:
let(:rest_client_double) { instance_double(Some::REST::Client, create_thing: response) }
it 'sends get request to the RestClient' do
allow(Some::REST::Client).to receive(:new).and_return(rest_client_double)
MyModel.new(attrs).do_a_rest_call(some_str)
expect(rest_client_duble).to have_received(:create_thing).with(some_str).once
end
Basically, you are creating a double for REST client.
Then, you make sure that when calling Some::REST::Client.new the double will be used (instead of real REST client instance).
Finally, you call a method on your model and check if double received given message.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55123380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update databindings when a TextBox changes rather than loses focus I'm learning to develop for compact framework and I've come across an issue that's bugging me.
I've bound a couple of textboxes to some properties (firstname & lastname of a person class) and have a menuitem which just does a showmessage of the full name, and it works fairly well except that the properties only get updated once the textbox losses focus. This means that if I change the firstname and press the show name menuitem, I get the old value of firstname.
Is there a way I can force an update of the databindings, or make it so that every time a character is changed in one of the textboxes the corresponding property is updated?
A: If you do this, you risk putting bad data into your data object, but here is how to do this:
In your MyTextBox.DataBinding.Add() method, use the this overload with OnPropertyChanged for the DataSourceUpdateMode param instead of the default OnValidate
I again say that this is one of those things that sounds really easy, but will likely cause issues in the long run as you are 'binding' to data that has never been validated.
A: Just call form's ValidateChildren() in the code on the button doing the save
| {
"language": "en",
"url": "https://stackoverflow.com/questions/929216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Fullscreen Frame Borders in Java LWJGL I want to make a game with Java and LWJGL. In many videogames you can see the black fields at the top and the bottom of the display, which is used to size the display in the resolution the game can work with.
I searched for this two days, but maybe I used wrong keywords.
So is there any possibility I can make this with LWJGL. Maybe a method I can use?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32153210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Second date Picker should show dates after the date selected in first date picker I have two date pickers. In first I'm selecting a date, and I want second date picker to show the dates after that particular date. Previous dates should be disabled.
A: Use minimum date property of the date picker to disable the all date before the minimum date. The date picker would also allow you to define range as minimum and maximum date so that it can show the date from minimum to maximum date range and remaining all other date will be disabled in picker view.
A: swift 3
datePickerEndDate.minimumDate = datePickerStartDate.date
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35955151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I apply MVVM and Commands in this specific WPF situation? I am having trouble with the MVVM pattern and Commands in my WPF app. The problem is not so much the MVVM pattern, but more the stuff that is going on on my GUI. I'll explain the situation:
My app can DoStuff to some files. I have a class with a function DoStuff(int limit). My user user interface has the following items:
*
*A Button DoStuffBtn to start parsing.
*A TextBox LimitTxt to fill in a limit.
*A CheckBox LimitChk to enabled or disable the limit.
When you would "uncheck" LimitChk, then LimitTxt.Text = "" and LimitTxt.IsEnabled = false. When you would "check" LimitChk, then LimitTxt.IsEnabled = false again, but the text remains empty until you fill something in.
I have read many tutorials on Commands in WPF and MVVM but I just can't seem to pour my case into that mold. The example I gave is actually just a small part of my UI, but I can't seem to do this nicely either.
I keep running into questions like:
*
*Do I need two Commands for LimitChk (enable and disable) or just one (toggle)?
*If I bind an int to LimitTxt, what happens if I make it empty and disable it?
*Is it a clean way to just use DoStuff(Int32.Parse(LimitTxt.Text)) when DoStuffBtn is pressed?
*If I use two commands on LimitChk, what happens with the CanExecute() function of ICommand that determines whether LimitChk is enabled?
So the main question is: How would the situation I described fit into a nice pattern using Commands in WPF?
Some links on WPF, Commands and MVVM i've looked at:
*
*http://www.devx.com/DevX/Article/37893/0/page/1
*http://msdn.microsoft.com/en-us/magazine/cc785480.aspx?pr=blog
*http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/432/MVVM-for-Tarded-Folks-Like-Me-or-MVVM-and-What-it-Means-to-Me.aspx
*http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
What I understand so far is that I have to keep as much as possible out of the UI. Even stuff like UI influencing the UI. I.e. unchecking LimitChk disables LimitText. Still, I think I should keep a difference between UI related information and actions and stuff that actually has to do with the actual work that has to be done.
A: I think you're getting confused... you don't need any commands here, you can just use bindings.
*
*Do I need two Commands for LimitChk (enable and disable) or just one (toggle)?
You need none. Just create a LimitEnabled property in your ViewModel, and bind the CheckBox to it (IsChecked="{Binding LimitEnabled}")
*
*If I bind an int to LimitTxt, what happens if I make it empty and disable it?
Disabling it has no effect. If you make the TextBox empty, the binding will fail because an empty string can't be converted to an int (at least not with the default converter)
*
*Is it a clean way to just use Parse(Int32.Parse(LimitTxt.Text)) when ParseBtn is pressed?
You don't need to. Just create a Limit property in your ViewModel, and bind the TextBox to it. You might want to add an ExceptionValidationRule to the Binding so that it highlights invalid input.
The button is not necessary, the parsing will be done automatically when the TextBox loses focus (if you use the default UpdateSourceTrigger). If you want to customize the way it's parsed, you can create a custom converter to use in the binding.
A: Just some high level thoughts, leaving out superfluous stuff like Color and alignment attributes, WrapPanels, etc.
Your ViewModel has a a couple properties:
public bool? LimitIsChecked { get; set; }
public bool LimitTextIsEnabled { get; set; } //to be expanded, below
public ICommand ParseCommand { get; private set; } // to be expanded, below
public string LimitValue { get; set; } // further explanation, below
Your XAML has CheckBox and TextBox definitions something like:
<CheckBox Content="Limit Enabled" IsChecked="{Binding LimitIsChecked}" />
<TextBox Text="{Binding LimitValue}" IsEnabled="{Binding LimitIsEnabled}" />
<Button Content="Parse" Command="{Binding ParseCommand}" />
You'll want to initialize ParseCommand something like this:
this.ParseCommand = new DelegateCommand<object>(parseFile);
Now, let's fill in that LimitTextIsEnabled property too:
public bool LimitTextIsEnabled {
// Explicit comparison because CheckBox.IsChecked is nullable.
get { return this.LimitIsChecked == true; }
private set { }
}
Your parseFile method would then pass the value of the LimitValue property to the logic doing the actual parsing.
I declared the LimitValue property as string here to avoid cluttering up the code with an explicit converter, or other validation code. You could choose to handle that "LimitValue is a valid int" verification/conversion in several different ways.
Of course, I haven't implemented this in its entirety, but I wanted to outline a pattern where you are not using Commands to update the state of the other widgets. Instead, bind those attributes to properties that are managed in your ViewModel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2118632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular component as the Mapbox control Does anybody know: can I use an angular component as the Mapbox custom control? I need to add a few buttons on the map, but I see I have to pass an HTML element.
A: I did this using https://stackoverflow.com/a/54561421/12302484. I've made the class that implements the IControl interface. Then returned the component from the onAdd method resolved by dynamic component service.
map.component.ts:
private configureControls(): void {
this.map.dragRotate.disable();
this.map.touchZoomRotate.disableRotation();
this.map.addControl(new mapboxgl.NavigationControl({ showCompass: false }));
this.map.addControl(new CustomMapControls(this.dynamicComponentService));
}
custom-map-controls.ts:
export class CustomMapControls {
private _container: HTMLElement;
private _switchColorButton: HTMLElement;
private map: mapboxgl.Map;
private dynamicComponentService: DynamicComponentService;
constructor(dynamicComponentService: DynamicComponentService) {
this.dynamicComponentService = dynamicComponentService;
this._container = document.createElement('div');
this._container.classList.add('mapboxgl-ctrl', 'mapboxgl-ctrl-group');
}
getDefaultPosition(): any {
return undefined;
}
onAdd(map: mapboxgl.Map): HTMLElement {
this.map = map;
this._container.appendChild(this.dynamicComponentService.injectComponent(MapColorSwitcherComponent));
return this._container;
}
onRemove(map: mapboxgl.Map): any {
}
}
result:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63961330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to fix segfault caused by a realloc going out of bounds? Hello and TIA for your help. As I am new to to posting questions, I welcome any feedback on how this quesiton has been asked. I have researched much in SO without finding what I thought I was looking for.
I'm still working on it, and I'm not really good at C.
My purpose is extracting data from certain specific tags from a given XML and writing it to file. My issue arises because as I try to fill up the data struct I created for this purpose, at a certain point the realloc() function gives me a pointer to an address that's out of bounds.
If you look at this example
#include <stdio.h>
int main() {
char **arrayString = NULL;
char *testString;
testString = malloc(sizeof("1234567890123456789012345678901234567890123456789"));
strcpy(testString, "1234567890123456789012345678901234567890123456789");
int numElem = 0;
while (numElem < 50) {
numElem++;
arrayString = realloc(arrayString, numElem * sizeof(char**));
arrayString[numElem-1] = malloc(strlen(testString)+1);
strcpy(arrayString[numElem-1], testString);
}
printf("done\n");
return 0;
}
it does a similar, but simplified thing to my code. Basically tries to fill up the char** with c strings but it goes to segfault. (Yes I understand I am using strcpy and not its safer alternatives, but as far as I understand it copies until the '\0', which is automatically included when you write a string between "", and that's all I need)
I'll explain more in dephth below.
In this code i make use of the libxml2, but you don't need to know it to help me.
I have a custom struct declared this way:
struct List {
char key[24][15];
char **value[15];
int size[15];
};
struct List *list; //i've tried to make this static after reading that it could make a difference but to no avail
Which is filled up with the necessary key values. list->size[] is initialized with zeros, to keep track of how many values i've inserted in value.
value is delcared this way because for each key, i need an array of char* to store each and every value associated with it. (I thought this through, but it could be a wrong approach and am welcome to suggestions - but that's not the purpose of the question)
I loop through the xml file, and for each node I do a strcmp between the name of the node and each of my keys. When there is a match, the index of that key is used as an index in the value matrix. I then try to extend the allocated memory for the c string matrix and then afterwards for the single char*.
The "broken" code, follows, where
*
*read is the index of the key abovementioned.
*reader is the xmlNode
*string contained the name of the xmlNode but is then freed so consider it as if its a new char*
*list is the above declared struct
if (xmlTextReaderNodeType(reader) == 3 && read >= 0)
{
/* pull out the node value */
xmlChar *value;
value = xmlTextReaderValue(reader);
if (value != NULL) {
free(string);
string=strdup(value);
/*increment array size */
list->size[read]++;
/* allocate char** */ list->value[read]=realloc(list->value[read],list->size[read] * sizeof(char**));
if (list->value[read] == NULL)
return 16;
/*allocate string (char*) memory */
list->value[read][list->size[read]-1] = realloc(list->value[read][list->size[read]-1], sizeof(char*)*sizeof(string));
if (list->value[read][list->size[read]-1] == NULL)
return 16;
/*write string in list */
strcpy(list->value[read][list->size[read]-1], string);
}
/*free memory*/
xmlFree(value);
}
xmlFree(name);
free(string);
I'd expect this to allocate the char**, and then the char*, but after a few iteration of this code (which is a function wrapped in a while loop) i get a segfault.
Analyzing this with gdb (not an expert with it, just learned it on the fly) I noticed that indeed the code seems to work as expected for 15 iteration. At the 16th iteration, the list->value[read][list->size[read]-1] after the size is incremented, list->value[read][list->size[read]-1] points to a 0x51, marked as address out of bounds. The realloc only brings it to a 0x3730006c6d782e31, still marked as out of bounds. I would expect it to point at the last allocated value.
Here is an image of that: https://imgur.com/a/FAHoidp
How can I properly allocate the needed memory without going out of bounds?
A: Your code has quite a few problems:
*
*You are not including all the appropriate headers. How did you get this to compile? If you are using malloc and realloc, you need to #include <stdlib.h>. If you are using strlen and strcpy, you need to #include <string.h>.
*Not really a mistake, but unless you are applying sizeof to a type itself you don't have to use enclosing brackets.
*Stop using sizeof str to get the length of a string. The correct and safe approach is strlen(str)+1. If you apply sizeof to a pointer someday you will run into trouble.
*Don't use sizeof(type) as argument to malloc, calloc or realloc. Instead, use sizeof *ptr. This will avoid your incorrect numElem * sizeof(char**) and instead replace it with numElem * sizeof *arrayString, which correctly translates to numElem * sizeof(char*). This time, though, you were saved by the pure coincidence that sizeof(char**) == sizeof(char*), at least on GCC.
*If you are dynamically allocating memory, you must also deallocate it manually when you no longer need it. Use free for this purpose: free(testString);, free(arrayString);.
*Not really a mistake, but if you want to cycle through elements, use a for loop, not a while loop. This way your intention is known by every reader.
This code compiles fine on GCC:
#include <stdio.h> //NULL, printf
#include <stdlib.h> //malloc, realloc, free
#include <string.h> //strlen, strcpy
int main()
{
char** arrayString = NULL;
char* testString;
testString = malloc(strlen("1234567890123456789012345678901234567890123456789") + 1);
strcpy(testString, "1234567890123456789012345678901234567890123456789");
for (int numElem = 1; numElem < 50; numElem++)
{
arrayString = realloc(arrayString, numElem * sizeof *arrayString);
arrayString[numElem - 1] = malloc(strlen(testString) + 1);
strcpy(arrayString[numElem - 1], testString);
}
free(arrayString);
free(testString);
printf("done\n");
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57924738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Displaying images and their accompanying information from a database with codeigniter Ok so im uploading images to a folder on my server, and then trying to re-display them with their information.
This is the function in my model that i am using to pull the info:
public function pull_all(){
$this->db->select('file_name, file_type, full_path, image_type');
$query = $this->db->get('img');
$dbInfo = $query->result_array();
return $dbInfo;
}
The controller implements the function like so:
function show_all(){
$this->load->model('image_work');
$data = array('dbInfo' => $this->image_work->pull_all());
$data['title'] = "Uploads";
$this->load->view('templates/header', $data);
$this->load->view('show_all',$data);
$this->load->view('templates/footer', $data);
}
The problem iv been having is in the view. I want each image to be shown with its info in this format:
<ul class="thumbnails">
<li class="span3">
<div class="thumbnail">
<img src="$location_stored_in_database"/>
<h3>$image_name</h3>
<p>$image_type</p>
<p>$image_size</p>
<p>$image_dimensions</p>
</div>
</li>
Iv tried many different ways to do it for example nested foreach statements, but I just cant seem to get it right. Any help would be appreciated.
thanks
A: You can do like this:
<?php foreach($dbInfo as $image): ?>
<ul class="thumbnails">
<li class="span3">
<div class="thumbnail">
<img src="<?php echo $image['full_path']; ?>"/>
<h3><?php echo $image['image_name']; ?></h3>
<p><?php echo $image['image_type']; ?></p>
<p><?php echo $image['image_size']; ?></p>
<p><?php echo $image['image_dimensions']; ?></p>
</div>
</li>
<?php endforeach; ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17820218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits