id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23528300
|
The goal of the query is to round these 2 timestamps to the nearest 30 minutes interval, which I manage using this: TIMESTAMP_TRUNC(TIMESTAMP_SUB(start_at, INTERVAL MOD(EXTRACT(MINUTE FROM start_at), 30) MINUTE),MINUTE) and the same goes for end_at.
Events occur (net_lost_orders) at each rounded timestamp.
The 2 problems that I encounter are:
First, as long as start_at and end_at are in the same 30 min. interval, things work well but when it is not the case (for example when start_at: 19:15 (nearest 30 min interval is 19:00) / end_at: 21:15 (nearest 30 min interval is 21:00), the results are not as expected. Additionally, I do not only need the 2 extreme intervals but all 30 minutes interval between start_at and end_at(19:00/19:30/20:00/20:30/21:00 in the example).
Secondly, I don't manage to create a condition that allows to show each interval on a separate row. I have tried to CAST, TRUNCATE,EXTRACTthe timestamps and to use CASE WHEN and to GROUP BY without success.
Here's the final part of the query (timestamps rounded excluded):
...
-------LOST ORDERS--------
a AS (SELECT created_date, closure, zone_id, city_id, l.interval_start,
l.net as net_lost_orders, l.starts_at, CAST(DATETIME(l.starts_at, timezone)AS TIMESTAMP) as start_local_time
FROM `XXX`, UNNEST(lost_orders) as l),
b AS (SELECT city_id, city_name, zone_id, zone_name FROM `YYY`),
lost AS (SELECT DISTINCT created_date, closure, zone_name, city_name, start_local_time,
TIMESTAMP_TRUNC(TIMESTAMP_SUB(start_local_time, INTERVAL MOD(EXTRACT(MINUTE FROM start_local_time), 30) MINUTE),MINUTE) AS lost_order_30_interval,
net_lost_orders
FROM a LEFT JOIN b ON a.city_id=b.city_id AND a.zone_id=b.zone_id AND a.city_id=b.city_id
WHERE zone_name='Atlanta' AND created_date='2021-09-09'
ORDER BY rt ASC),
------PREPARATION CLOSURE START AND END INTERVALS------
f AS (SELECT
DISTINCT TIMESTAMP_TRUNC(TIMESTAMP_SUB(start_at, INTERVAL MOD(EXTRACT(MINUTE FROM start_at), 30) MINUTE),MINUTE) AS start_closure_30_interval,
TIMESTAMP_TRUNC(TIMESTAMP_SUB(end_at, INTERVAL MOD(EXTRACT(MINUTE FROM end_at), 30) MINUTE),MINUTE) AS end_closure_30_interval,
country_code,
report_date,
Day,
CASE
WHEN Day="Monday" THEN 1
WHEN Day="Tuesday" THEN 2
WHEN Day="Wednesday" THEN 3
WHEN Day="Thursday" THEN 4
WHEN Day="Friday" THEN 5
WHEN Day="Saturday" THEN 6
WHEN Day="Sunday" THEN 7
END AS Weekday_order,
report_week,
city_name,
events_mod.zone_name,
closure,
start_at,
end_at,
activation_threshold,
deactivation_threshold,
shrinkage_drive_time,
ROUND(duration/60,2) AS duration,
FROM events_mod
WHERE report_date="2021-09-09"
AND events_mod.zone_name="Atlanta"
GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
ORDER BY report_date, start_at ASC)
------FINAL TABLE------
SELECT DISTINCT
start_closure_30_interval,end_closure_30_interval, report_date, Day, Weekday_order, report_week, f.city_name, f.zone_name, closure,
start_at, end_at, start_time,end_time, activation_threshold, deactivation_threshold, duration, net_lost_orders
FROM f
LEFT JOIN lost ON f.city_name=lost.city_name
AND f.zone_name=lost.zone_name
AND f.report_date=lost.created_date
AND f.start_closure_30_interval=lost.lost_order_30_interval
AND f.end_closure_30_interval=lost.lost_order_30_interval
GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
Results:
Expected results:
I would be really grateful if you could help and explain me how to get all the rounded timestamps between start_at and end_aton separate rows. Thank you in advance. Best, Fabien
Spreadsheet here
A: Consider below approach
select intervals, any_value(t).*, sum(Nb_lost_orders) as Nb_lost_orders
from table1 t,
unnest(generate_timestamp_array(
timestamp_seconds(div(unix_seconds(starts_at), 1800) * 1800),
timestamp_seconds(div(unix_seconds(ends_at), 1800) * 1800),
interval 30 minute
)) intervals
left join (
select Nb_lost_orders,
timestamp_seconds(div(unix_seconds(Time_when_the_lost_order_occurred), 1800) * 1800) as intervals
from Table2
)
using(intervals)
group by intervals
if applied to sample data in your question
with Table1 as (
select 'Closure' Event, timestamp '2021-09-09 11:00:00' starts_at, timestamp '2021-09-09 11:45:00' ends_at union all
select 'Closure', '2021-09-09 12:05:00', '2021-09-09 14:10:00'
), Table2 as (
select 5 Nb_lost_orders, timestamp '2021-09-09 11:38:00' Time_when_the_lost_order_occurred
)
output is
| |
doc_23528301
|
however always getting the error that my field is not defined .
My Model has several calculated columns and I want to get only the records where values of field A are greater than field B.
So this is my model
class Material(models.Model):
version = IntegerVersionField( )
code = models.CharField(max_length=30)
name = models.CharField(max_length=30)
min_quantity = models.DecimalField(max_digits=19, decimal_places=10)
max_quantity = models.DecimalField(max_digits=19, decimal_places=10)
is_active = models.BooleanField(default=True)
def _get_totalinventory(self):
from inventory.models import Inventory
return Inventory.objects.filter(warehouse_Bin__material_UOM__UOM__material=self.id, is_active = true ).aggregate(Sum('quantity'))
totalinventory = property(_get_totalinventory)
def _get_totalpo(self):
from purchase.models import POmaterial
return POmaterial.objects.filter(material=self.id, is_active = true).aggregate(Sum('quantity'))
totalpo = property(_get_totalpo)
def _get_totalso(self):
from sales.models import SOproduct
return SOproduct.objects.filter(product__material=self.id , is_active=true ).aggregate(Sum('quantity'))
totalso = property(_get_totalpo)
@property
def _get_total(self):
return (totalinventory + totalpo - totalso)
total = property(_get_total)
And this is line in my view where I try to get the conditional queryset
po_list = MaterialFilter(request.GET, queryset=Material.objects.filter( total__lte = min_quantity ))
But I am getting the error that min_quantity is not defined
What could be the problem ?
EDIT:
My problem got solved thank you @Moses Koledoye but in the same code I have different issue now
Cannot resolve keyword 'total' into field.Choices are: am, author, author_id, bom, bomversion, code, creation_time, description, id, inventory, is_active, is_production, itemgroup, itemgroup_id, keywords, materialuom, max_quantity, min_quantity, name, pomaterial, produce, product, slug, trigger_quantity, uom, updated_by, updated_by_id, valid_from, valid_to, version, warehousebin
Basically it doesn't show any of my calculated fields I have in my model.
A: Django cannot write a query which is conditioned on a field whose value is unknown. You need to use a F expression for this:
from django.db.models import F
queryset = Material.objects.filter(total__lte = F('min_quantity'))
And your FilterSet becomes:
po_list = MaterialFilter(request.GET, queryset = Material.objects.filter(total__lte=F('min_quantity')))
From the docs:
An F() object represents the value of a model field or annotated
column. It makes it possible to refer to model field values and
perform database operations using them without actually having to pull
them out of the database into Python memory
| |
doc_23528302
|
//console.log(JSON.stringify(data.voucher.validity));
var allData = { "id":data.id,
"user_id": data.customerId,
"code":data.voucher.code,
"validity":data.voucher.validity
}
console.log('all',allData);
console.log(JSON.stringify(allData));
output += '<a href="javascript:;" data-toggle="modal" data-target="#edit_voucher" data-all='+JSON.stringify(allData)+' class="btn btn-brand btn-sm btn-icon update-voucher-modal" data-skin="dark" title="{{"Edit this Voucher"|__}}"><i class="la la-pencil"></i></button>';
the above two console.log generates the following two lines:
all {id: 1, user_id: 1, code: "FEAST50", validity: "2020-11-24 23:59:59"}
{"id":1,"user_id":1,"code":"FEAST50","validity":"2020-11-24 23:59:59"}
but the data attribute is generated as follows:
data-all="{"id":1,"user_id":1,"code":"FEAST50","validity":"2020-11-24"
It should look like:
data-all="{"id":1,"user_id":1,"code":"FEAST50","validity":"2020-11-24 23:59:59"}"
Why 23:59:59"}" is being truncated? Any idea?
| |
doc_23528303
|
The text wrapping works ok in all browsers except from Safari 5.1, where instead of example@gmai... the div displays ....
This doesn't happen if the font is, for example, of the woff type, but I prefer to use svg for its better font smoothing in webkit browsers (including Safari).
I've tested on Safari 5.1 on both Windows and OS X (later Safari versions on Mac works just fine).
Are there any workarounds to this problem?
Here is a fiddle, and the complete code:
@font-face {
font-family: 'AsapRegular';
font-style: normal;
font-weight: 400;
src: url('url_to_my_svg_font') format('svg');
}
.wrap {
font-family: 'AsapRegular', sans-serif;
width: 6em;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
<div class="wrap">example@gmail.com</div>
A: This issue also occurs on chrome windows. My issue was solved by turning off text-rendering:optimizelegibility.
| |
doc_23528304
|
here is a code snippit:
public static void main(String[] args) {
int i = 0;
Scanner input = new Scanner(System.in);
while(input.hasNext() && i<1){
System.out.println(input.nextLine());
if(input.nextLine() == "exit"){
i++;
}
}
input.close();
}
A: This works
public static void main(String[] args) {
int i = 0;
Scanner input = new Scanner(System.in);
while(input.hasNext() && i<1){
String nextLine = input.nextLine();
System.out.println(nextLine);
if(nextLine.equals("exit")){
i++;
}
}
input.close();
}
The problem was you first did System.out.println(input.nextLIne()) and then did it again in your if statement (hence reading the 2 next lines instead of one).
When inputting "exit" the loop did not stopped because you were comparing a string with ==, you have to compare strings with equals method.
A: I would say use break instead of i++ so it will not wait till for next input after you have entered exit.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s;
while (input.hasNext()) {
s = input.nextLine(); // input.nextLine(); read single line once.
// So you need to assign it to some variable so that you can use it in your if condition.
System.out.println(s);
if (s.equals("exit")) { // use equals instead of == also use variable
break; // so it will not wait for next input to check in while condition hasNext.
}
}
input.close();
}
| |
doc_23528305
|
HTML
<a href="#" class="btn">Image Borders</a>
CSS
a {
text-decoration: none;
color: #fff;
}
.btn {
float: left;
display: block;
padding: 10px 30px;
background-color: #67b8de;
background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Small-city-symbol.svg/348px-Small-city-symbol.svg.png") no-repeat right bottom;
}
A: Your background-image rule also contains values for background-repeat and background-position. Separate them (or you can put the colour in too and use the background shorthand):
background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Small-city-symbol.svg/348px-Small-city-symbol.svg.png");
background-repeat: no-repeat;
background-position: right bottom;
A: Okay I went over the documentation on https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds
The new CSS
.btn {
float: left;
display: block;
padding: 10px 30px;
/* Notice that I list all the images */
background: url("../img/border-top-left.png"), url("../img/border-top-right.png"),
url("../img/border-bottom-left.png"), url("../img/border-bottom-right.png");
background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;
background-position: top left, top right, bottom left, bottom right;
background-color: #67b8de;
}
You will notice that I use the background: property, you can also use the background-image property, thanks for the tip minitech. You also should notice that you can't just specify individual image is you want to target all the corners of the button. Example:
background-image: url("../img/border-blah-blah.png");
background-repeat: no-repeat;
background-position: top right;
This will not target all of your corners, but only one corner will be targeted this is because of the cascade it will overwrite the previous rule, that's why you have to input the sources for all your images at once and then target them. Also you should put the background-color property last, because the color won't be applied if it is the first rule. I don't know why that happens.
A: You background image is too large:
it's working with a background image at 10%..: Link JSFiddle
background: #ff8844 url("https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Small-city-symbol.svg/348px-Small-city-symbol.svg.png") 10%
| |
doc_23528306
|
<MyView>
<Style TargetType="Border" x:Key="Module">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Gray" />
<Setter Property="Padding" Value="10" />
<Setter Property="Margin" Value="10" />
</Style>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border Name="Border1" Style="{StaticResource Module}">
<!--some controls with non-fixed width-->
</Border>
<Border Grid.Row="1" Name="Border2" Style="{StaticResource Module}">
<!--some controls with non-fixed width-->
</Border>
<Border Grid.Column="1" Grid.RowSpan="2" Style="{StaticResource Module}" Name="Border3">
<!--some controls with non-fixed width-->
</Border>
</Grid>
</MyView>
The controls inside Border1 and Border2 might have different width, so their borders will also have different width, which doesn't look good. How do I force Border1 and Border2 border to have same width so it would look better?
The solution of setting same width manually doesn't count because the width of child controls of Border1 and Border2 may vary.
And the content of Border3 just eats up all available space, and this is fine.
A: Add <Setter Property="HorizontalAlignment" Value="Stretch" /> to your Border Style
| |
doc_23528307
|
x = [5, 6, 3, 1, 2]
def missing_integer():
for i in range(1, 100):
if i not in x:
return i
print(missing_integer())
The instructions include some examples:
given x = [1, 3, 6, 4, 1, 2], the function should return 5,
given x = [1, 2, 3], the function should return 4 and
given x = [−1, −3], the function should return 1.
A: You did not ask for the most efficient way to solve the problem, just if there is a more efficient way than yours. The answer to that is yes.
If the missing integer is near the top of the range of the integers and the list is long, your algorithm as a run-time efficiency of O(N**2)--your loop goes through all possible values, and the not in operator searches through the entire list if a match is not found. (Your code searches only up to the value 100--I assume that is just a mistake on your part and you want to handle sequences of any length.)
Here is a simple algorithm that is merely order O(N*log(N)). (Note that quicker algorithms exist--I show this one since it is simple and thus answers your question easily.) Sort the sequence (which has the order I stated) then run through it starting at the smallest value. This linear search will easily find the missing positive integer. This algorithm also has the advantage that the sequence could involve negative numbers, non-integer numbers, and repeated numbers, and the code could easily handle those. This also handles sequences of any size and with numbers of any size, though of course it runs longer for longer sequences. If a good sort routine is used, the memory usage is quite small.
A: I think the O(n) algorithm goes like this: initialise an array record of length n + 2 (list in Python) to None, and iterate over the input. If the element is one of the array indexes, set the element in the record to True. Now iterate over the new list record starting from index 1. Return the first None encountered.
A: Another solution is creating an array with a size of Max value, and traverse the array and marking each location of the array when that value is seen. Then, iterate from the start of the array and report the first finding unlabeled location as the smallest missing value. This is done in O(n) (Fill the array and finding the smallest unlabeled location).
Also, for negative values you can add all values the Min value to find all values positive. Then, apply the above method.
The space complexity of this method is \Theta(n).
To know more, see this post about the implementation and scrutinize more about this method.
A: The slow step in your algorithm is that line:
if i not in x:
That step takes linear time, which makes the entire algorithm O(N*N). If you first turn the list into a set, the lookup is much faster:
def missing_integer():
sx = set(x)
for i in range(1, 100):
if i not in sx:
return i
Lookup in a set is fast, in fact it takes constant time, and the algorithm now runs in linear time O(N).
A: Can be done in O(n) time with a bit of maths. initialise a minimum_value and maximum_value, and sum_value names then loop once through the numbers to find the minimum and maximum and the sum of all the numbers (mn, mx, sm).
Now the sum of integers 0..n = n*(n-1)/2 = s(n)
Therefore: missing_number = (s(mx) - s(mn)) - sm
All done with traversing the numbers only once!
A: My answer using list comprehension:
def solution(A):
max_val = max(A);
min_val = min(A);
if max_val<0: val = 1;
elif max_val > 0:
li = [];
[li.append(X) for X in range(min_val,max_val) if X not in A];
if len(li)>0:
if min(li)<0: val = 1;
else: val = min(li);
if len(li)==0: val=max_val+1;
return val;
L = [-1, -3];
res = solution(L);
print(res);
| |
doc_23528308
|
int display_width = display.getCurrent().getWidth();
When I start my midlet, I see this error: Exception. Application has unexpectedly quit. contact the application provider to resolve the issue. 0.
Why?
A: It's possible that something here is throwing an exception, but the library is hiding it behind that user friendly error message.
My guess is that display.getCurrent() is returning null, so the getWidth() causes a NullPointerException.
Try this:
Display myDisplay = display.getCurrent();
System.out.println(myDisplay);
int display_width = myDisplay.getWidth();
Note that you'll need to replace the Display class may whatever the type of display.getCurrent()'s return value is.
Or, better yet, you could try to catch the exception:
try {
int display_width = display.getCurrent().getWidth();
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
| |
doc_23528309
|
Also, is it possible to control the period before the camera turns off ?
My idea is to be able to switch between two cameras and it seems that if I don't connect to one for a while, it will turning off automatically (My test on playMemories app gives me four minutes before it turns off).
Is there a way to avoid that ?
Thanks
A: *
*Controlling the power state is not possible programatically.
*This is not controllable either.
A:
(My test on playMemories app gives me four minutes before it turns
off). Is there a way to avoid that ?
On some models it is possible to programmatically change autoPowerOff time or to deactivate it. Look for setAutoPowerOff.
| |
doc_23528310
|
A: If you are sharing a configuration value, there are several ways: the simplest would be a file that both systems can reach via the file-system, or a database.
If you are sharing active state (e.g. web sessions) between the two systems you could use a database or a shared cache.
Alternatively, you could have the two systems communicate with each other via some kind of API (e.g. via HTTP calls).
A: Using Webservice we can easily communicate.
| |
doc_23528311
|
A: It doesn't have unit because it depends on the type of joint it is attached to.
For hinge-joints, hinge-2-joints and ball-joints the units are radians and for slider-joints the units are meters.
| |
doc_23528312
|
i need a php snippet code for checking the user is login or not when he click a button of proceed to checkout on cart page
A: You have to use simple wordpress function to check is a user logged in or not.
is_user_logged_in()
Checks if the current visitor is a logged in user.
it returns (bool) True if user is logged in, false if not logged in.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?>
A: First you need to check user in on checkout page or not, if so then do the checking; or if you have your own function then you can simply wordpress is_user_logged_in() function.
add_action('wp', 'xyz_checkLoggedIn');
function xyz_checkLoggedIn() {
if (is_checkout()) {
if (is_user_logged_in()) {
//user is logged in
} else {
//user is not logged in
}
}
}
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
The code is tested and fully functional.
Hope this helps!
A: add_action('woocommerce_checkout_process', 'check_if_user_loggedin');
function check_if_user_loggedin() {
if ( is_user_logged_in() ) {
echo 'Logged user';
} else {
echo 'Guest user!';
}
}
| |
doc_23528313
|
I want to add round layer of a mask and to impose it on this image.
Should I use CIFilter?
A: To do it entirely with CoreImage you can follow this recipe:
let image = CIImage(contentsOf: URL(string: "https://s3.amazonaws.com/uploads.hipchat.com/27364/1957261/bJERqq8O2V3NVok/upload.jpg")!)
// Construct a circle
let circle = CIFilter(name: "CIRadialGradient", withInputParameters:[
"inputRadius0":100,
"inputRadius1":100,
"inputColor0":CIColor(red: 1, green: 1, blue: 1, alpha:1),
"inputColor1":CIColor(red: 0, green: 0, blue: 0, alpha:0)
])?.outputImage
// Turn the circle into an alpha mask
let mask = CIFilter(name: "CIMaskToAlpha", withInputParameters: [kCIInputImageKey:circle!])?.outputImage
// Apply the mask to the input image
let combine = CIFilter(name: "CIBlendWithAlphaMask", withInputParameters:[
kCIInputMaskImageKey:mask!,
kCIInputImageKey:image!
])
let output = combine?.outputImage
Although this only works for circles
A: Use like this , For round image with border
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
self.profileImageView.clipsToBounds = YES;
self.profileImageView.layer.borderWidth = 3.0f;
self.profileImageView.layer.borderColor = UIColor.whiteColor.CGColor
A: maybe this can help to create a round image using core graphic.. they create a round blur image using core graphic.
Blur specific part of an image (rectangular, circular)?
A: I solve my problem :).
I use extension.
override var outputImage : CIImage!
{
if let inputImage = inputImage {
//making UIImage from CIImage
let uiImage = UIImage(ciImage: inputImage)
//use extension
let roundImage = uiImage.roundedRectImageFromImage(image:uiImage, imageSize: CGSize.init(width: uiImage.size.width/2, height: uiImage.size.width/2), cornerRadius: uiImage.size.width/2)
//get back CIImage
let ciImage = CIImage(image: roundImage)
///There other code.....
}
extension UIImage {
func roundedRectImageFromImage(image:UIImage,imageSize:CGSize,cornerRadius:CGFloat)->UIImage{
UIGraphicsBeginImageContextWithOptions(imageSize,false,0.0)
let bounds=CGRect(origin: CGPoint.zero, size: imageSize)
UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()
image.draw(in: bounds)
let finalImage=UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage!
}
}
| |
doc_23528314
|
I am trying to some changes in muc_room which uses this hook.
A: muc_filter_message and muc_filter_presence are new API used to filter / transform message or presence packet send to MUC before they are broadcasted to other users.
| |
doc_23528315
|
Controller:
public async Task<IActionResult> Login()
{
if (await IsValidUser())
{
return RedirectToAction("Index");
}
else
{
return new UnauthorizedResult();
}
}
Startup
app.UseStatusCodePages(async context =>
{
var response = context.HttpContext.Response;
await context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
response.Redirect("~/Account/AccessDenied");
});
A: Even though you are targeting chrome, internet security settings are still in effect. There doesn't seem to be any problem with your code in regards to your question (Was there a question, btw?) Please review this link and understand it doesn't tell you what the consequences of that change may be. This is better suited for SuperUser, not stack overflow.
A: The first question is whether user is authenticated with AD in .net core application . If not authenticated(wrong credential) ,
IMO the prompt is a browser behavior , when Window Authentication Enabled, Anonymous Disabled, this authentication happens by the web server before your application code is ever reached , so that IIS takes care of the authentication before the request is passed to ASP.NET, so the request will never reach the error page.
The workaround maybe is using Forms Authentication with AD Membership Providers . Below thread provides the code samples but i haven't test that :
.net Core Authentication
If user is authenticated and you want to do authorize , you could can click here for code sample and of course you can redirect user to error page if authorization failed .
| |
doc_23528316
|
A: i had the same message of error and it resulted to be this annoying litle mistake in the color resource file: the double angle bracket, which by the way the compliler doesn't highlights
>@color/gris_oscuro
A: This is likely a problem in some resource file. I think it's very frustrating, the error message says "Check logs for more details" but I am not sure how to get the logs.
I had a similar problem and after many attempts I exited Studio, manually removed the build directory, and tried again. This time I did see a log, and they pointed at my strings.xml file, which I was able to fix.
By the way, I realized that if you run "Compile some_file.xml" from the Build menu, you'll get the error even if the error is somewhere else. So this is not helpful.
(FWIW, my error had to do with a single quote inside a [[CDATA]] block. I thought that Xml allows any text inside CDATA, but maybe Studio is less forgiving. Anyway, your error is probably something else, you'll just have to find it.)
I see here that people discuss how to get grade logs. I was not able to run gradlew from the terminal (I am on macOS) but that seems to be the official way to get lgs.
A: Check colors.xml and strings.xml file. I had error in colors.xml. I had written wrong color code of two colors. That is why I was getting this error.
| |
doc_23528317
|
ID
Quantity1
Quantity2
Quantity3
Quantity4
Date
101
100
0
200
300
3/1/2020
101
300
80
2200
400
3/1/2020
101
100
0
200
300
1/1/2020
101
20
0
6
50
1/1/2020
102
1000
0
200
300
3/1/2020
102
600
80
2200
400
3/1/2020
102
900
0
200
300
1/1/2020
102
400
30
65
90
1/1/2020
I want to write an SQL query that will give me the sums of the quantity columns by ID but taking only the entries from the most recent date. My expected output is:
ID
Quantity1
Quantity2
Quantity3
Quantity4
Date
101
400
80
2400
700
3/1/2020
102
1600
80
2400
700
3/1/2020
I know how to sum entire columns by ID, but not with the added wrinkle of needing to do it by max date. Help would be greatly appreciated!
A: One method is a correlated subquery:
select id, sum(quantity1), sum(quantity2), sum(quantity3), sum(quantity4),
date
from t
where t.date = (select max(t2.date)
from t t2
where t2.id = t.id
)
group by id, date;
A: You need to group by both Id and Date(if you expect 2 or more records for a single date).
Along with below examples, you could also use Row_number().
with temp as(
select 12 as id,45 as quantity1, '2021-02-19' as date
union all
select 22 as id, 88 as quantity1 , '2019-12-12' as date
union all
select 12 as id , 10 as quantity1,'2021-02-19' as date )
approach 1: select id,sum(quantity1), date from temp
group by id, date
order by date desc
limit 1 (-- or top 1 )
approach 2:
select id,sum(quantity1), date from temp
where date=(select max(date) from temp)
group by id, date
| |
doc_23528318
|
FILE: application.properties (inside resource folder)
spring.mongo.host=127.0.0.1
spring.mongo.port=27017
spring.mongo.databaseName=spring
FILE: person.java
@Document (collection = "person")
public class Person {
@Id
String id;
int age;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
FILE: MyRepo.java
@Repository
public interface MyRepo extends PagingAndSortingRepository<Person, String> {
public List<Person> findAllByName(String name);
}
FILE: Config.java
@Configuration
@EnableMongoRepositories(basePackages = {"mongo.customQueries"})
public class Config {
}
FILE: Main.java
public class Main {
@Autowired
public static MyRepo myRepo;
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
MyRepo myRepo = context.getBean(MyRepo.class);
System.out.println(myRepo.findAllByName("Avishek"));
}
}
When I run the project, I get an error
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [mongo.customQueries.MyRepo] is defined
What is it that I am missing here? Why is my MyRepo bean not created as most of the examples in net are doing so.
A: The problem is you want to annotation the MyRepo in the Main class, please remove it as below:
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
MyRepo myRepo = context.getBean(MyRepo.class);
System.out.println(myRepo.findAllByName("Avishek"));
}
}
A:
If someone could just give me a simple example to run Dynamic Queries
in Spring boot with mongo. Some examples similar to that of above. Or
how can I make the above example correct.
You can see working example here. And find explanations here.
| |
doc_23528319
|
This is on WAS 8.5.5.9,IBM Http Server.
A: However you are setting that 422 status, you need to make sure a word follows the status code. In my test, if you use HTTPServletResponse#setStatus and an unknown status code for example, WAS adds the word "Undefined" at least.
The safest way is to use HTTPServletResponse#sendError which requires a status code and a reason string.
| |
doc_23528320
|
So what I am trying to do to prevent the too many connection issue is to set up a connection pool. I have tried dbcp and bonecp also but both have the same behaviour. When I reload my page it just keeps loading in the browser and after some debugging it seems it hangs after the 9th or 10th select.
My scenario looks like this:
1: "select * from maincategory"
This query returns around 15 categories. I map the resultset into a List containing MainCategory elements.
Then what I do is I walk through the MainCategory List and get the IDs from each MainCategory and then I do an other select to get their sub categories:
2: "select * from subcategories where id = ${id_from_main_category_actual_row}"
And it seems it hangs after the 9th or 10th subcategory selection.
Here is my transaction manager and sqlsessionfactory configuration:
<beans:bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="configLocation" value="WEB-INF/spring/myBatis/mybatis.xml" />
<beans:property name="mapperLocations" value="WEB-INF/spring/myBatis/mbmapper-*.xml" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
And here is the configuration for a datasource with dbcp:
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
</beans:bean>
And my other try was with the bonecp:
<beans:bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<beans:property name="driverClass" value="com.mysql.jdbc.Driver" />
<beans:property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
<beans:property name="idleConnectionTestPeriodInSeconds" value="30"/>
<beans:property name="idleMaxAgeInMinutes" value="1"/>
<beans:property name="maxConnectionsPerPartition" value="7"/>
<beans:property name="minConnectionsPerPartition" value="7"/>
<beans:property name="partitionCount" value="1"/>
<beans:property name="acquireIncrement" value="1"/>
<beans:property name="acquireRetryAttempts" value="1"/>
<beans:property name="acquireRetryDelayInMs" value="5000"/>
<beans:property name="maxConnectionAgeInSeconds" value="0"/>
<beans:property name="connectionTestStatement" value="SELECT 1"/>
<beans:property name="statementsCacheSize" value="100"/>
<beans:property name="disableConnectionTracking" value="true"/>
</beans:bean>
As you can see I tried many optimization on this with the properties. I think regardless if the method querying for main and their subcategories is a good or wrong practise, its only 10 small queries with some data returned so it should work.
If I use the "org.springframework.jdbc.datasource.DriverManagerDataSource" as the datasource, the db says the "too many connection" after some page refresh, while the tried connection pools just hang after the mentioned amount of query.
UPDATE based on comments:
Here is my detailed code as requested:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/appServlet/ApplicationContext.xml
/WEB-INF/spring/appServlet/ApplicationContext-security.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
ApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<beans:bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<context:annotation-config />
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<!--
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
-->
<context:component-scan base-package="com.test.packit" />
<!-- Thymeleaf Template & View Resolver configurations -->
<beans:bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<beans:property name="prefix" value="/WEB-INF/templates/" />
<beans:property name="suffix" value=".html" />
<beans:property name="templateMode" value="HTML5" />
<beans:property name="cacheable" value="false" />
</beans:bean>
<beans:bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<beans:property name="templateResolver" ref="templateResolver" />
<beans:property name="additionalDialects">
<beans:set>
<beans:bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect" />
</beans:set>
</beans:property>
</beans:bean>
<beans:bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<beans:property name="templateEngine" ref="templateEngine" />
</beans:bean>
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="localization/general/messages" />
</beans:bean>
<beans:bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<beans:property name="driverClass" value="com.mysql.jdbc.Driver" />
<beans:property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
<beans:property name="idleConnectionTestPeriodInSeconds" value="30"/>
<beans:property name="idleMaxAgeInMinutes" value="1"/>
<beans:property name="maxConnectionsPerPartition" value="7"/>
<beans:property name="minConnectionsPerPartition" value="7"/>
<beans:property name="partitionCount" value="1"/>
<beans:property name="acquireIncrement" value="1"/>
<beans:property name="acquireRetryAttempts" value="1"/>
<beans:property name="acquireRetryDelayInMs" value="5000"/>
<beans:property name="maxConnectionAgeInSeconds" value="0"/>
<beans:property name="connectionTestStatement" value="SELECT 1"/>
<beans:property name="statementsCacheSize" value="100"/>
<beans:property name="disableConnectionTracking" value="true"/>
</beans:bean>
<!--
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
</beans:bean>
-->
<!-- Original data source without connection pooling -->
<!--
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
-->
<beans:bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="configLocation" value="WEB-INF/spring/myBatis/mybatis.xml" />
<beans:property name="mapperLocations" value="WEB-INF/spring/myBatis/mbmapper-*.xml" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<!-- MAPPER: ACCOUNT -->
<beans:bean id="accountDao" class="com.test.packit.dao.AccountDao">
<beans:property name="sessionFactory" ref="sqlSessionFactory" />
</beans:bean>
<beans:bean id="accountService" class="com.test.packit.service.AccountService">
<beans:property name="accountDao" ref="accountDao" />
</beans:bean>
<!-- MAPPER: MAIN_CATEGORY -->
<beans:bean id="mainCategoryDao" class="com.test.packit.dao.MainCategoryDao">
<beans:property name="sessionFactory" ref="sqlSessionFactory" />
</beans:bean>
<beans:bean id="mainCategoryService" class="com.test.packit.service.MainCategoryService">
<beans:property name="mainCategoryDao" ref="mainCategoryDao" />
</beans:bean>
<!-- MAPPER: SUB_CATEGORY -->
<beans:bean id="subCategoryDao" class="com.test.packit.dao.SubCategoryDao">
<beans:property name="sessionFactory" ref="sqlSessionFactory" />
</beans:bean>
<beans:bean id="subCategoryService" class="com.test.packit.service.SubCategoryService">
<beans:property name="subCategoryDao" ref="subCategoryDao" />
</beans:bean>
</beans:beans>
ApplicationContext-security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
<intercept-url pattern="/user.jsp" access="ROLE_USER" />
<session-management session-fixation-protection="none">
<concurrency-control />
</session-management>
<form-login
login-page="/login"
login-processing-url="/letmein"
default-target-url="/"
authentication-failure-url="/login-error"
username-parameter="bm_username"
password-parameter="bm_password" />
<logout logout-url="/logout"/>
<!-- enable csrf protection -->
<csrf/>
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT username, password, enabled
FROM bm_users
WHERE username=?"
authorities-by-username-query="SELECT username, role
FROM bm_roles
WHERE username=?" />
<password-encoder hash="bcrypt"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
mbmapper-mainCategory-mapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="maincategory">
<cache type="org.mybatis.caches.hazelcast.LoggingHazelcastCache"/>
<select id="getAllMainCategories" resultType="list" resultMap="mainCategoryMap.mainCategoryResultMap">
SELECT * FROM packit.bm_maincategory;
</select>
</mapper>
mbmapper-mainCategory-resultMap.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mainCategoryMap">
<resultMap type="com.test.packit.model.MainCategory" id="mainCategoryResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
</mapper>
mbmapper-subCategory-mapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="subcategory">
<cache type="org.mybatis.caches.hazelcast.LoggingHazelcastCache"/>
<select id="getAllSubCategoriesForMainCategory" parameterType="int" resultType="list" resultMap="subCategoryMap.subCategoryResultMap">
SELECT * FROM packit.bm_subcategory WHERE maincategory_id = #{id};
</select>
</mapper>
mbmapper-subCategory-resultMap.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="subCategoryMap">
<resultMap type="com.test.packit.model.SubCategory" id="subCategoryResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
</mapper>
MainCategory.java:
package com.test.packit.model;
import java.io.Serializable;
import java.util.List;
public class MainCategory implements Serializable {
private static final long serialVersionUID = -7970848646314840509L;
private Integer id;
private String name;
private List<SubCategory> subCategories;
public List<SubCategory> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
}
public MainCategory() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MainCategoryDao.java:
package com.test.packit.dao;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;
import com.test.packit.model.MainCategory;
@Repository
public class MainCategoryDao {
@Resource
private SqlSessionFactory sessionFactory;
public SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("unchecked")
public List<MainCategory> getAllMainCategories(){
SqlSession session = sessionFactory.openSession();
List<MainCategory> mainCategoriesFromDb = (List<MainCategory>)(List<?>) session.selectList("maincategory.getAllMainCategories");
return mainCategoriesFromDb;
}
}
MainCategoryService.java:
package com.test.packit.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.test.packit.dao.MainCategoryDao;
import com.test.packit.model.MainCategory;
@Repository
public class MainCategoryService {
@Resource
private MainCategoryDao mainCategoryDao;
public List<MainCategory> getAllCategories() {
return mainCategoryDao.getAllMainCategories();
}
public MainCategoryDao getMainCategoryDao() {
return mainCategoryDao;
}
public void setMainCategoryDao(MainCategoryDao mainCategoryDao) {
this.mainCategoryDao = mainCategoryDao;
}
}
SubCategory.java:
package com.test.packit.model;
import java.io.Serializable;
public class SubCategory implements Serializable {
private static final long serialVersionUID = -7970848646314840509L;
private Integer id;
private Integer mainCategoryId;
private String name;
public Integer getMainCategoryId() {
return mainCategoryId;
}
public void setMainCategoryId(Integer mainCategoryId) {
this.mainCategoryId = mainCategoryId;
}
public SubCategory() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
SubCategoryDao.java:
package com.test.packit.dao;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;
import com.test.packit.model.SubCategory;
@Repository
public class SubCategoryDao {
@Resource
private SqlSessionFactory sessionFactory;
public SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("unchecked")
public List<SubCategory> getAllSubCategoriesForMainCategory(int id){
SqlSession session = sessionFactory.openSession();
List<SubCategory> subCategoriesFromDb = (List<SubCategory>)(List<?>) session.selectList("subcategory.getAllSubCategoriesForMainCategory", id);
return subCategoriesFromDb;
}
}
SubCategoryService.java:
package com.test.packit.dao;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;
import com.test.packit.model.SubCategory;
@Repository
public class SubCategoryDao {
@Resource
private SqlSessionFactory sessionFactory;
public SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("unchecked")
public List<SubCategory> getAllSubCategoriesForMainCategory(int id){
SqlSession session = sessionFactory.openSession();
List<SubCategory> subCategoriesFromDb = (List<SubCategory>)(List<?>) session.selectList("subcategory.getAllSubCategoriesForMainCategory", id);
return subCategoriesFromDb;
}
}
HomeController.java:
package com.test.packit;
import com.test.packit.authentication.AuthenticatorController;
import com.test.packit.model.MainCategory;
import com.test.packit.model.SubCategory;
import com.test.packit.service.MainCategoryService;
import com.test.packit.service.SubCategoryService;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HomeController {
@Resource
private MainCategoryService mainCategoryService;
private List<MainCategory> mainCategories;
@Resource
private SubCategoryService subCategoryService;
private List<SubCategory> subCategories;
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Locale locale, Model model) {
// Get all main categories
mainCategories = mainCategoryService.getAllCategories();
for(MainCategory mainCategory : mainCategories) {
logger.info("Main Category: {}", mainCategory.getName());
// Get all sub categories
subCategories = subCategoryService.getAllSubCategoriesForMainCategory(mainCategory.getId());
mainCategory.setSubCategories(subCategories);
for(SubCategory subCategory : subCategories) {
logger.info("\t\t- {}", subCategory.getName());
}
}
model.addAttribute("mainCategories", mainCategories);
return "index";
}
}
Any suggestion are very welcomed.
A: 1. When creating SqlSessions manually you have to make sure that you close them after use.
Look for all places where you are opening a SqlSession:
SqlSession session = sessionFactory.openSession();
Make sure that you're closing the session after use. You should do that in try-finally block, like below:
SqlSession session = sqlSessionFactory.openSession();
try {
// following 3 lines pseudocode for "doing some work"
session.insert(...);
session.update(...);
session.delete(...);
session.commit();
} finally {
session.close();
}
More information on how to handle MyBatis SqlSessions can be found here: http://mybatis.github.io/mybatis-3/java-api.html#sqlSessions
2. You can use MyBatis-Spring to create and manage the lifecycle of SqlSessions.
Instead of injecting DAO's with SqlSessionFactory, you can ask spring to inject the SqlSessions directly. When you do this, Spring will manage the SqlSessions for you, so you will not have to open/close sessions by yourself.
More information how to do this is here: http://mybatis.github.io/spring/sqlsession.html
| |
doc_23528321
|
$mech->get($someurl, ":content_file" => "$i.flv");
So I'm getting the contents of a url and saving it as an flv file. I'd like to print out every second or so how much of the download is remaining. Is there any way to accomplish this in WWW::Mechanize?
A: WWW::Mechanize says that the get method is a "well-behaved" overload of LWP::UserAgent get. Looking at the docs for LWP::UserAgent, you can provide a content_cb key which is called with each chunk of the downloaded file:
$mech->get( $someurl, ":content_cb" => \&callback );
sub callback
{
my( $data, $response, $proto ) = @_;
# save $data to $i.flv
# print download notification
}
A: Many thanks to Peter Kovacs' answer for leading me to the correct answer. It turned out to be a bit more elaborate than I'd expected though so I decided to (horror) answer my own question.
As Peter showed, I can set a callback like so:
$m->get($u, ":content_cb" => \&callback);
But now I can't save the content using the :content_file value, because I can only choose one of the two. The callback function gets passed the data, and I ended up writing that to a file instead.
I also get a response object which contains the total size of the content as friedo pointed out. So by keeping a running total of content received so far and dividing it by the total content I can find out what percent of the content has been downloaded. Here's the full callback function:
open (VID,">$i.flv") or die "$!";
$total = 0;
sub callback
{
my( $data, $response, $proto ) = @_;
print VID "$data"; # write data to file
$total+= length($data);
$size = $response->header('Content-Length');
print floor(($total/$size)*100),"% downloaded\n"; # print percent downloaded
}
I hope that helps someone.
| |
doc_23528322
|
Example:
B,L,D = 2,4,2
M = torch.rand(B,L,D)
>
tensor([[[0.0612, 0.7385],
[0.7675, 0.3444],
[0.9129, 0.7601],
[0.0567, 0.5602]],
[[0.5450, 0.3749],
[0.4212, 0.9243],
[0.1965, 0.9654],
[0.7230, 0.6295]]])
idx = torch.randint(0, L, size = (B,))
>
tensor([3, 0])
N = get_N(M, idx)
Expected output:
>
tensor([[0.0567, 0.5602],
[0.5450, 0.3749]])
Thanks.
A: import torch
B,L,D = 2,4,2
def get_N(M, idx):
return M[torch.arange(B), idx, :].squeeze()
M = torch.tensor([[[0.0612, 0.7385],
[0.7675, 0.3444],
[0.9129, 0.7601],
[0.0567, 0.5602]],
[[0.5450, 0.3749],
[0.4212, 0.9243],
[0.1965, 0.9654],
[0.7230, 0.6295]]])
idx = torch.tensor([3,0])
N = get_N(M, idx)
print(N)
result:
tensor([[0.0567, 0.5602],
[0.5450, 0.3749]])
slice along two dimensions.
| |
doc_23528323
|
flume agent is as follows:
agent1.sources = tail
agent1.channels = memoryChannel
agent1.sinks = loggerSink sink1
agent1.sources.tail.type = exec
agent1.sources.tail.command = tail -f /usr/local/jarsfortest/LogsForTest/generatingLogs-app.logs
agent1.sources.tail.channels = memoryChannel
agent1.sinks.loggerSink.channel = memoryChannel
agent1.sinks.loggerSink.type = logger
agent1.sinks.sink1.type = org.apache.flume.sink.hbase.HBaseSink
agent1.sinks.sink1.channel = memoryChannel
agent1.sinks.sink1.table = testFlume
agent1.sinks.sink1.columnFamily = log
agent1.sinks.sink1.serializer = org.apache.flume.sink.hbase.RegexHbaseEventSerializer
#agent1.sinks.sink1.serializer.regex = [a-zA-Z0-9]*[^C][a-zA-Z0-9]*[^C][a-zA-Z0-9]*
agent1.sinks.sink1.serializer.regex =[a-zA-Z0-9]*^C[a-zA-Z0-9]*^C[a-zA-Z0-9]*
agent1.sinks.sink1.serializer.colNames = id, no_fill_reason, bid
agent1.channels.memoryChannel.type = memory
agent1.channels.memoryChannel.capacity = 1000
above agent is started successfully..but log file data does not inserted into hbase.
log file data is as below:
id0^COK^C10
i.e. data is control char seperated.
Please help me.
Thanks in advance.
A: reason may be regexpression is not matching
to debug this follow the below steps
1) use to start only one agent with this option
flume-ng agent -n $1 -c ../../config/conf/ -f ../../config/conf/$1.conf -Xmx3g **-Xdebug -Xrunjdwp:transport=dt_socket, address=1044,server=y,suspend=y**
--classpath ../lib/*:../../config/conf/zoo.cfg:../.
once you start the script
listening to 1044...
message will come.
2) create eclipse remote application to connect to your server name and port as 1044
3) getActions method is responsible for putting the rows in to hbase..
Put a break point in getActions method of EventSerializer
public List<Row> getActions() throws FlumeException {
List actions = Lists.newArrayList();
Matcher m = this.inputPattern.matcher(new String(this.payload, this.charset));
if (!(m.matches())) {
return Lists.newArrayList();
}
if (m.groupCount() != this.colNames.size())
return Lists.newArrayList();
try {
byte[] rowKey;
byte[] rowKey;
if (this.rowKeyIndex < 0)
rowKey = getRowKey();
else {
rowKey = m.group(this.rowKeyIndex + 1).getBytes(Charsets.UTF_8);
}
Put put = new Put(rowKey);
for (int i = 0; i < this.colNames.size(); ++i) {
if (i != this.rowKeyIndex) {
put.add(this.cf, (byte[]) this.colNames.get(i), m.group(i + 1).getBytes(Charsets.UTF_8));
}
}
if (this.depositHeaders) {
for (Map.Entry entry : this.headers.entrySet()) {
put.add(this.cf, ((String) entry.getKey()).getBytes(this.charset),
((String) entry.getValue()).getBytes(this.charset));
}
}
actions.add(put);
} catch (Exception e) {
throw new FlumeException("Could not get row key!", e);
}
return actions;
}
A: I can help on the analysis of root cause.
Using CTRL+C to terminate this flume-ng process.
Watch the output carefully.
There will be three type of Metrics:
*
*Shutdown Metric for type: SOURCE
*Shutdown Metric for type: CHANNEL
*Shutdown Metric for type: SINK
For example:
Shutdown Metric for type: SOURCE, name: r1. source.start.time == 1483838106878
Shutdown Metric for type: SOURCE, name: r1. source.stop.time == 1483838118766
Shutdown Metric for type: SOURCE, name: r1. src.append-batch.accepted == 0
Shutdown Metric for type: SOURCE, name: r1. src.append-batch.received == 0
Shutdown Metric for type: SOURCE, name: r1. src.append.accepted == 0
Shutdown Metric for type: SOURCE, name: r1. src.append.received == 0
Shutdown Metric for type: SOURCE, name: r1. src.events.accepted == 141
Shutdown Metric for type: SOURCE, name: r1. src.events.received == 147
Shutdown Metric for type: SOURCE, name: r1. src.open-connection.count == 0
Shutdown Metric for type: CHANNEL, name: c1. channel.start.time == 1483838106874
Shutdown Metric for type: CHANNEL, name: c1. channel.stop.time == 1483838118789
Shutdown Metric for type: CHANNEL, name: c1. channel.capacity == 1000000
Shutdown Metric for type: CHANNEL, name: c1. channel.current.size == 141
Shutdown Metric for type: CHANNEL, name: c1. channel.event.put.attempt == 147
Shutdown Metric for type: CHANNEL, name: c1. channel.event.put.success == 141
Shutdown Metric for type: CHANNEL, name: c1. channel.event.take.attempt == 31
Shutdown Metric for type: CHANNEL, name: c1. channel.event.take.success == 26
Shutdown Metric for type: SINK, name: k1. sink.start.time == 1483838108891
Shutdown Metric for type: SINK, name: k1. sink.stop.time == 1483838118758
Shutdown Metric for type: SINK, name: k1. sink.batch.complete == 0
Shutdown Metric for type: SINK, name: k1. sink.batch.empty == 4
Shutdown Metric for type: SINK, name: k1. sink.batch.underflow == 1
Shutdown Metric for type: SINK, name: k1. sink.connection.closed.count == 1
Shutdown Metric for type: SINK, name: k1. sink.connection.creation.count == 0
Shutdown Metric for type: SINK, name: k1. sink.connection.failed.count == 0
Shutdown Metric for type: SINK, name: k1. sink.event.drain.attempt == 26
Shutdown Metric for type: SINK, name: k1. sink.event.drain.sucess == 0
In the above example, the issue is during the sink stage because of the drain.success is equal to 0.
| |
doc_23528324
|
<SOAP-ENV:Body>
<ns0:DataResponse xmlns:ns0="http://somenamspace/v1.0">
<ns0:ResponseId>
<ns0:RequestID>12345</ns0:RequestID>
</ns0:ResponseId>
<ns0:Payload>
<ns1:Product xmlns:ns1="http://anothernamespace/v1.x">
<ns1:ProductName>productName</ns1:ProductName>
<ns1:ProductIdentifier>12222</ns1:ProductIdentifier>
<ns1:ProdInst>
<ns1:Type>Conv</ns1:Type>
<ns1:Descr>Conventional Loan</ns1:Descr>
<ns1:AllowedTypes>
<ns1:ScheduleSchedule>true</ns1:ScheduleSchedule>
</ns1:AllowedTypes>
<ns1:prdExist>false</ns1:prdExist>
<ns1:AdditionalAttributes>
<ns1:AdditionalAttribute name="gura" value="C"/>
</ns1:AdditionalAttributes>
</ns1:ProdInst>
<ns1:ProductGroups>
<ns1:ProductGroupName>1111</ns1:ProductGroupName>
<ns1:ProductGroupName>2222</ns1:ProductGroupName>
</ns1:ProductGroups>
</ns1:Product>
<ns1:Product>
.......
</ns1:Product>
</ns0:Payload>
</ns0:DataResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
------------------------------------
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns0="http://somenamespace/v1.0"
xmlns:ns1="http://anothernamespace/v1.x"
exclude-result-prefixes="ns1">
<xsl:output omit-xml-declaration="yes" indent="no" method="text"/>
<xsl:template match="ns1:Products">
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>
----------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://namespace/v1.x"
exclude-result-prefixes="ns1">
<xsl:output omit-xml-declaration="yes" indent="no" method="text"/>
<xsl:template match="/">
<xsl:for-each select="ns1:Product">
<xsl:value-of select="ns1:ProductName" />
<xsl:text>,</xsl:text>
<xsl:value-of select="ns1:ProdInst/ns1:Type" />
<xsl:text>,</xsl:text>
<xsl:value-of select="ns1:ProdInst/ns1:Descr" />
<xsl:text>,</xsl:text>
<xsl:value-of select="ns1:ProdInst/ns1:AdditionalAttributes/@gura" />
<xsl:text>,</xsl:text>
<xsl:for-each select="ns1:ProductGroups">
<xsl:value-of select="."/>
</xsl:for-each>,
</xsl:for-each>
</xsl:template>
Basically I am trying to write the XSL to convert all these "Product" inner attribute values to the CSV format. I already struggled with overcome using the namespaces but still could not write up in the perfect format, sometimes the styles going on next line , and if I tried the generic one then the problem as could not read the additionalAtrributes values.
any help on this would be great.
Expecting output as
all the tag inner attributes lined up in the CSV format with "," in order .
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns0="http://somenamspace/v1.0"
xmlns:ns1="http://anothernamespace/v1.x"
exclude-result-prefixes="ns1">
<xsl:output method="text" indent="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:apply-templates select="ns1:Product"/>
</xsl:template>
<xsl:template match="ns1:Product">
<xsl:value-of select="*"/>
<xsl:apply-templates select="ns1:ProdInst"/>
<xsl:apply-templates select="ns1:ProductGroups"/>
</xsl:template>
<xsl:template match="ns1:ProdInst">
<xsl:value-of select="."/>
<xsl:apply-templates select="ns1:AllowedTypes"/>
<xsl:apply-templates select="ns1:AdditionalAttributes"/>
</xsl:template>
<xsl:template match="ns1:AllowedTypes">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="ns1:AdditionalAttributes">
<xsl:for-each select="@*">
<xsl:copy-of select="." />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
I have tried as above and got atleast all in the same line, but still its not comma seperated also the "AdditionalAttributes" are not included. can anybody help on this?
A: Please have a look this solution:
XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns0="http://somenamspace/v1.0" xmlns:ns1="http://anothernamespace/v1.x"
exclude-result-prefixes="ns1">
<xsl:output method="text" indent="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:for-each select="//ns1:Product">
<xsl:call-template name="getProduct">
<xsl:with-param name="Product" select="self::*"/>
</xsl:call-template>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
<xsl:template name="getProduct">
<xsl:param name="Product"/>
<xsl:variable name="ProductContent">
<xsl:for-each select="$Product/*">
<xsl:choose>
<xsl:when test="*">
<xsl:call-template name="getChild">
<xsl:with-param name="Child" select="*"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:if test="@*">
<xsl:for-each select="@*">
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:for-each>
<xsl:text>,</xsl:text>
</xsl:if>
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
<xsl:value-of select="substring($ProductContent,0,string-length($ProductContent))"/>
</xsl:template>
<xsl:template name="getChild">
<xsl:param name="Child"/>
<xsl:for-each select="$Child/node()">
<xsl:choose>
<xsl:when test="* and not(@*)">
<xsl:call-template name="getChild">
<xsl:with-param name="Child" select="*"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="text()">
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:when>
<xsl:when test="*">
<xsl:for-each select="@*">
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:for-each>
<xsl:call-template name="getChild">
<xsl:with-param name="Child" select="*"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="not(*) and @*">
<xsl:for-each select="@*">
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:if test="@*">
<xsl:for-each select="@*">
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:for-each>
<xsl:text>,</xsl:text>
</xsl:if>
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
<xsl:if test="$Child/@* and not($Child/node())">
<xsl:for-each select="$Child/@*">
<xsl:value-of select="."/>
<xsl:text>,</xsl:text>
</xsl:for-each>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
OUTPUT:
productName,12222,Conv,Conventional Loan,true,false,gura,C,1111,2222
produ222222222ctName,12222,Conv,Conventional Loan,true,false,gura,C,1111,2222
| |
doc_23528325
|
My sf object was originally in the Alaska Albers projection (espg:2964). I would like for the polygon object to be projected into that coordinate system. I think you are supposed to use coord_map() to deal with it, but I'm not sure how to get coord_map to do the Alaska albers projection, because coord_map() doesn't seem to take espg codes or proj4 strings.
Thanks in advance for your help.
This code works, but puts both things into wgs84:
results.transform = results %>% st_transform(4326)
ggplot(ak, aes(long, lat, group=group))+
geom_polygon(fill="grey", color="black")+
geom_sf(data=results.transform, aes(color=doy),inherit.aes = FALSE, size=2)
This code does not throw an error, but the polygon and sf layers do not plot on top of each other:
#results is the original sf object in espg 2964
ggplot(ak, aes(long, lat, group=group))+
geom_polygon(fill="grey", color="black")+
coord_map("albers", lat0 =50, lat1=55)+
geom_sf(data=results, aes(color=doy),inherit.aes = FALSE, size=2)
Sample of inputs (using dput):
results:
results =structure(list(id = c("1", "2", "3"), doy = c(152, 158, 142),
doy_meanthresh = c(156, 160, 140), threshold = c(0.173556868958583,
0.109912373062543, 0.074946580423674), smooth.series = list(
c(0.356716711457841, 0.370050893258325, 0.383236999766461,
0.396376974233949, 0.40957275991249, 0.422784291482468,
0.435895856103075, 0.448895925744217, 0.461772972375802,
0.474515467967738, 0.48722268616777, 0.499933470515835,
0.512545647820125, 0.524957044888832, 0.537065488530148,
0.549189274496968, 0.561532939869938, 0.573823673448877,
0.5857886640336, 0.597155100423927, 0.608751798005646,
0.621116663488914, 0.633540522660091, 0.645314201305544,
0.655728525211634, 0.665571086939856, 0.675708836320647,
0.685551635043781, 0.694509344799033, 0.701991827276177,
0.70938842013153, 0.717660871422796, 0.725577658441836,
0.731907258480512, 0.735418148830686, 0.737609381488737,
0.740068708326791, 0.741697656450321, 0.741397752964802,
0.738070524975708, 0.730787113459408, 0.720275348839784,
0.707921792393576, 0.695113005397529, 0.683235549128384,
0.66854065601544, 0.648565682783239, 0.626626377151392,
0.606038486839507, 0.590117759567193, 0.575248354822936,
0.557183338977548, 0.538291820074129, 0.520942906155777,
0.507505705265592, 0.497170423227522, 0.487542218972326,
0.478612630203321, 0.470373194623822, 0.462815449937146,
0.458831683827816, 0.459466542404155, 0.461940101005184,
0.463472434969922, 0.461283619637389, 0.458826926942516,
0.459760482491641, 0.461611642130895, 0.461907761706409,
0.458176197064313, 0.45041527548862, 0.440794234319326,
0.430096794486539, 0.419106676920368, 0.408607602550923,
0.396242242656226, 0.380503346606902, 0.363449752471964,
0.347140298320423, 0.333633822221291, 0.321253095838767,
0.307606088569194, 0.293679435079791, 0.28045977003778,
0.268933728110384, 0.258699817638372, 0.248739536036072,
0.239114001581039, 0.22988433255083, 0.221111647222998,
0.213576575535607, 0.207511807976447, 0.202156553647666,
0.196750021651411, 0.19053142108983, 0.183900129705502,
0.177683584689661, 0.17176308431744, 0.166019926863971,
0.160335410604389, 0.153743267353215, 0.146014563103421,
0.138136597397814, 0.131096669779199, 0.125882079790385,
0.121448622919517, 0.116554575980903, 0.111890960506595,
0.10814879802864, 0.106019110079089, 0.105661169696536,
0.106498694582266, 0.108119373262358, 0.110110894262892,
0.11206094610995, 0.11540233539241, 0.120997725074791,
0.127579588246629, 0.133880397997461, 0.138632627416822,
0.143475963087052, 0.150098990228934, 0.157307529889666,
0.163907403116449, 0.168704430956481, 0.172368187413333,
0.176173416587563, 0.179833694671856, 0.183062597858895,
0.185573702341366, 0.187052218702838, 0.187638597324987,
0.187729274097655, 0.187720684910687, 0.188009265653923,
0.188094043051569, 0.187473296399738, 0.186542340446139,
0.185696489938482, 0.185331059624476, 0.18519846898834,
0.184852749545972, 0.184391634092598, 0.183912855423446,
0.183514146333744, 0.183117312589153, 0.182606699408324,
0.182023848765966, 0.181410302636787, 0.180807602995498,
0.180212334083628, 0.179591966640683, 0.178944372388341,
0.178267423048277, 0.177558990342169, 0.176816945991692,
0.176039161718523, 0.175223509244339, 0.174367860290815
), c(0.774610362619149, 0.746412269781788, 0.719913789191898,
0.695420287796062, 0.673237132540861, 0.653273968452586,
0.635200894750251, 0.618963959669522, 0.604509211446066,
0.59178269831555, 0.581143108860635, 0.572741206185169,
0.566211150306591, 0.561187101242345, 0.557303219009872,
0.555232501533965, 0.555534753213423, 0.557674343776691,
0.561115642952215, 0.565323020468442, 0.573372729704498,
0.586895414376992, 0.603187029720595, 0.619543530969977,
0.63326087335981, 0.649100787927623, 0.670935206211495,
0.694725384196925, 0.716432577869408, 0.732018043214443,
0.745048344614319, 0.760240534670835, 0.775281601698759,
0.787858534012854, 0.795658319927888, 0.799986340749408,
0.803308852568436, 0.805054155877942, 0.804650551170897,
0.801526338940272, 0.794278541385548, 0.783000246619136,
0.769363854003397, 0.755041762900692, 0.741706372673384,
0.725475019829043, 0.703589930868272, 0.679410840142977,
0.656297482005064, 0.637609590806439, 0.619522671663228,
0.59768917697572, 0.574684262022063, 0.553083082080407,
0.535460792428901, 0.520724989583801, 0.506208924554847,
0.492126234360422, 0.478690556018906, 0.466115526548682,
0.456163205377972, 0.449307080301381, 0.443827930886861,
0.438006536702364, 0.430123677315843, 0.422161025148951,
0.416341337462143, 0.411307021081574, 0.405700482833399,
0.398164129543771, 0.388509330252805, 0.377833000710694,
0.366705867808713, 0.355698658438137, 0.34538209949024,
0.334476225402477, 0.322019919293152, 0.309062181074817,
0.296652010660021, 0.285838407961315, 0.276447235011443,
0.267512949813937, 0.258897446237528, 0.250462618150946,
0.242070359422922, 0.234129641095434, 0.226902750204945,
0.220031554611916, 0.21315792217681, 0.205923720760086,
0.19852372751621, 0.191343478746417, 0.184310981031329,
0.177354240951568, 0.170401265087756, 0.163192040497278,
0.155702671847874, 0.148215342135701, 0.141012234356916,
0.134375531507676, 0.127758694427545, 0.120727232121655,
0.113731399834516, 0.107221452810637, 0.101647646294526,
0.0965005694542742, 0.091209569652388, 0.0861330394250022,
0.0816293713082512, 0.0780569578382695, 0.075371315752509,
0.0732346851768886, 0.0715655437302434, 0.0702823690314086,
0.0693036386992192, 0.0691863250953481, 0.0701883842483067,
0.0717797692771877, 0.073430433301084, 0.0746103294390886,
0.0761784204310707, 0.0788956524181342, 0.0820849536212236,
0.0850692522612836, 0.0871714765592586, 0.0890972731947091,
0.0916871981841642, 0.094466543754022, 0.0969606021306803,
0.0986946655405372, 0.0998521594454551, 0.100914181761071,
0.101852533394445, 0.102639015252636, 0.103245428242704,
0.103462264899288, 0.103250578499722, 0.102838011065113,
0.102452204616565, 0.102320801175184, 0.102287042959656,
0.102088178523127, 0.101792859388387, 0.10146973707823,
0.101187463115447, 0.100889974984667, 0.100495657145597,
0.100034831583652, 0.0995378202842451, 0.0990349452327908,
0.0985243275768939, 0.097982837008049, 0.0974089183275044,
0.0968010163365085, 0.0961575758363094, 0.0954770416281557,
0.0947578585132956, 0.0939984712929773, 0.0931973247684494
), c(0.754994105046569, 0.759262980856892, 0.763248462599852,
0.767062652758686, 0.77081765381663, 0.774472838830307,
0.777902459086919, 0.781090934415562, 0.784022684645335,
0.786682129605334, 0.789179136777192, 0.791558707699299,
0.793707963285894, 0.795514024451214, 0.796864012109498,
0.798059444416928, 0.799307737538445, 0.800354859401417,
0.800946777933214, 0.800829461061205, 0.800535183022801,
0.800489794522664, 0.800279628189041, 0.799491016650182,
0.797710292534332, 0.793727807721641, 0.787531875152631,
0.780505769046113, 0.774032763620899, 0.7694961330958,
0.766814565429895, 0.764644322900798, 0.76247504120512,
0.759796356039472, 0.756097903100465, 0.753105409945246,
0.751812834849642, 0.750612159588286, 0.747895365935809,
0.742054435666847, 0.734349211270437, 0.726724708968583,
0.718600671135361, 0.709396840144846, 0.698532958371117,
0.685958066059214, 0.672217339551, 0.657624725365782,
0.642494170022865, 0.627139620041553, 0.608952937377657,
0.586693889874402, 0.562728282882226, 0.539421921751564,
0.519140611832852, 0.498827185487661, 0.475313450129851,
0.450798673688293, 0.427482124091856, 0.40756306926941,
0.391594783774196, 0.377888811456193, 0.365281824189383,
0.352610493847746, 0.338711492305265, 0.324742577633052,
0.312133619351959, 0.300129456510569, 0.287974928157469,
0.274914873341241, 0.260271155053797, 0.244483391182105,
0.228473053117332, 0.21316161225065, 0.199470539973226,
0.18615371420193, 0.171962954821233, 0.157816646173702,
0.144633172601908, 0.13333091844842, 0.12330701757161,
0.113524600030087, 0.104251044466771, 0.0957537295245833,
0.0883000338464436, 0.0824702507214148, 0.0782344478172879,
0.0749446653450757, 0.0719529435157916, 0.0686113225404485,
0.0661995394292459, 0.0657367472597934, 0.0661841103442199,
0.0665027929946539, 0.0656539595232242, 0.0644681965998428,
0.0641406846621584, 0.0641794786739045, 0.0640926335988149,
0.0633882044006231, 0.0619833956742033, 0.0602788637336122,
0.058507841121357, 0.0569035603799449, 0.0556992540518834,
0.0546528395507013, 0.0534742168963767, 0.0523245925410911,
0.0513651729370255, 0.0507571645363614, 0.0504376622860656,
0.050241048436331, 0.0501744603941783, 0.0502450355666279,
0.0504599113607003, 0.0510283221178971, 0.052012828131863,
0.0532005557378333, 0.0543786312710432, 0.055334181066728,
0.0564245098836434, 0.057962991953209, 0.0596708578196554,
0.0612693380272137, 0.0624796631201147, 0.0635479377810315,
0.0648035693895804, 0.0660927425354069, 0.0672616418081562,
0.0681564517974736, 0.0687850088878122, 0.0692835297177245,
0.0696907692580061, 0.0700454824794523, 0.0703864243528584,
0.0706277104270338, 0.0707098566767007, 0.0707112187115236,
0.0707101521411668, 0.0707850125752948, 0.0708833573425856,
0.0709155836751044, 0.0709043070375961, 0.0708721428948058,
0.0708417067114787, 0.070795102344694, 0.0707055967085618,
0.0705825498533734, 0.0704353218294197, 0.0702732726869918,
0.0700959115439309, 0.0698961835839182, 0.069673602956005,
0.0694276838092427, 0.0691579402926828, 0.0688638865553766,
0.0685450367463756, 0.0682009050147312, 0.0678310055094947
)), doy.series = list(c(55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201,
202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213
), c(55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,
146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181,
182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
206, 207, 208, 209, 210, 211, 212, 213), c(55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150,
151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162,
163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186,
187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212, 213)), year = c("2000", "2000", "2000"), geometry = structure(list(
structure(c(-1661436.84461341, -1661115.05202279, -1661228.76098043,
-1660425.2592279, -1659056.23818505, -1658307.31829931,
-1656634.51866674, -1656620.45332118, -1656912.32303615,
-1658398.86388024, -1659675.83584702, 4861078.89101535,
4860325.10237897, 4859645.11439113, 4857608.78556975,
4855675.65967803, 4850643.61215932, 4846958.71327386,
4845855.03478051, 4845305.91718129, 4844752.81259044,
4843366.85928571), .Dim = c(11L, 2L), class = c("XY",
"LINESTRING", "sfg")), structure(c(-1658241.19039753,
-1654712.75990038, -1651942.38784669, -1650404.98329246,
-1648988.60261601, -1645978.84503211, -1643222.00421422,
-1639781.08711522, -1638602.99625793, -1637902.54559266,
-1639311.78216295, -1639248.9245045, -1638107.13443693,
-1637058.59090575, 4774391.6371314, 4774653.20892703,
4775738.21754787, 4774227.59717794, 4771389.21271209,
4770934.19458225, 4769568.55276305, 4771094.02869766,
4770996.1462525, 4769827.51755788, 4767060.08312911,
4765949.41565321, 4763854.76024583, 4763305.58844374), .Dim = c(14L,
2L), class = c("XY", "LINESTRING", "sfg")), structure(c(-1637058.59090575,
-1634446.33873168, -1631719.63870714, -1629361.15811325,
-1628116.65633233, -1627013.82581023, -1626189.71570171,
-1625551.50211327, -1624075.99821849, -1622805.13871411,
-1622273.7980277, -1620254.94375451, -1618394.36936387,
-1616289.48293551, -1615299.3539038, -1613130.11112742,
4763305.58844374, 4761938.07374864, 4761581.34917333,
4761984.29842838, 4762878.85905119, 4765596.31389399,
4766660.74696295, 4766903.7237966, 4766207.39483074,
4763687.87083808, 4763298.06222046, 4763460.09645817,
4765651.28116598, 4765148.87541194, 4763932.07676722,
4759749.97915703), .Dim = c(16L, 2L), class = c("XY",
"LINESTRING", "sfg"))), class = c("sfc_LINESTRING", "sfc"
), precision = 0, bbox = structure(c(-1661436.84461341, 4759749.97915703,
-1613130.11112742, 4861078.89101535), .Names = c("xmin",
"ymin", "xmax", "ymax"), class = "bbox"), crs = structure(list(
epsg = 2964L, proj4string = "+proj=aea +lat_1=55 +lat_2=65 +lat_0=50 +lon_0=-154 +x_0=0 +y_0=0 +datum=NAD27 +units=us-ft +no_defs"), .Names = c("epsg",
"proj4string"), class = "crs"), n_empty = 0L)), .Names = c("id",
"doy", "doy_meanthresh", "threshold", "smooth.series", "doy.series",
"year", "geometry"), row.names = c(NA, 3L), class = c("sf", "data.frame"
), sf_column = "geometry", agr = structure(c(NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), .Names = c("id", "doy", "doy_meanthresh", "threshold", "smooth.series",
"doy.series", "year"), .Label = c("constant", "aggregate", "identity"
), class = "factor"))
ak:
ak=structure(list(long = c(-130.013061523438, -130.01530456543,
-130.015808105469, -130.015014648438, -130.015808105469, -130.014724731445,
-130.014434814453, -130.014434814453, -130.01416015625, -130.014724731445,
-130.027786254883, -130.041656494141, -130.053924560547, -130.066925048828,
-130.080841064453, -130.088623046875, -130.117797851562, -130.146667480469,
-130.175262451172, -130.204147338867, -130.229187011719, -130.235260009766,
-130.242767333984, -130.249176025391, -130.25749206543, -130.264984130859,
-130.275527954102, -130.285278320312, -130.296676635742, -130.307220458984,
-130.318328857422, -130.329742431641, -130.341934204102, -130.354141235352,
-130.365249633789, -130.375564575195, -130.387496948242, -130.397811889648,
-130.409713745117, -130.414184570312), lat = c(55.9116859436035,
55.9241752624512, 55.9383277893066, 55.952766418457, 55.9669189453125,
55.9814147949219, 55.9952812194824, 56.0100021362305, 56.0238723754883,
56.0258178710938, 56.0422058105469, 56.05859375, 56.075553894043,
56.0919380187988, 56.1086120605469, 56.1180648803711, 56.1122207641602,
56.1066627502441, 56.1008186340332, 56.0949745178223, 56.090274810791,
56.0925102233887, 56.0961227416992, 56.0994453430176, 56.1021919250488,
56.1058616638184, 56.1083221435547, 56.1111297607422, 56.11279296875,
56.1150283813477, 56.1166915893555, 56.118350982666, 56.1203002929688,
56.1222457885742, 56.123908996582, 56.1252822875977, 56.1263732910156,
56.1278038024902, 56.1288948059082, 56.1288948059082), group = c(1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), order = 1:40,
region = c("USA", "USA", "USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA", "USA", "USA"), subregion = c("Alaska",
"Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska",
"Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska",
"Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska",
"Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska",
"Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska",
"Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska",
"Alaska", "Alaska", "Alaska")), .Names = c("long", "lat",
"group", "order", "region", "subregion"), row.names = c(NA, 40L
), class = "data.frame")
A: Convert ak to EPSG:2964 instead then use coord_sf(datum = st_crs(2964)) inside ggplot call
library(sp)
library(sf)
library(tidyverse)
# Convert ak to EPSG:2964
ak_sf <- sf::st_as_sf(ak, coords = c("long", "lat"), crs = 4326)
ak_sf_tp <- st_transform(ak_sf, crs = 2964)
str(ak_sf_tp)
# Plot everything under EPSG:2964
ggplot() +
geom_sf(data = ak_sf_tp) +
geom_sf(data = results, aes(color = doy), inherit.aes = FALSE, size = 2) +
coord_sf(datum = st_crs(2964))
Edit: If we want to plot ak as a polygon
# Get lat/long from sf object
ak_poly <- as(ak_sf_tp, 'Spatial') %>%
as.data.frame() %>%
rename(long = "coords.x1", lat = "coords.x2")
ggplot(ak_poly, aes(long, lat, group = group)) +
geom_polygon(fill = "grey", color = "black") +
geom_sf(data = results, aes(color = doy), inherit.aes = FALSE, size = 2) +
coord_sf(datum = st_crs(2964))
| |
doc_23528326
|
I want to use TypeConverter or its child ArrayConverter. Its contain method ConvertFromString.
But if I call this method I catch an exception ArrayConverter cannot convert from System.String.
I know about Split, don't suggest me this solution.
----SOLUTION---
using advice @Marc Gravell and answer of this topic by @Patrick Hofman I wrote CustumTypeDescriptorProvider
public class CustumTypeDescriptorProvider:TypeDescriptionProvider
{
public override ICustomTypeDescriptor GetTypeDescriptor(System.Type objectType, object instance)
{
if (objectType.Name == "String[]") return new StringArrayDescriptor();
return base.GetTypeDescriptor(objectType, instance);
}
}
public class StringArrayDescriptor : CustomTypeDescriptor
{
public override TypeConverter GetConverter()
{
return new StringArrayConverter();
}
}
where StringArrayConverter is implemented in answer below this post.
To use it I added CustumTypeDescriptorProvider to collection of providers
TypeDescriptor.AddProvider(new CustumTypeDescriptorProvider(), typeof(string[]));
To use it in TestClass you need to write a few lines:
TypeConverter typeConverter = TypeDescriptor.GetConverter(prop.PropertyType);
cValue = typeConverter.ConvertFromString(Value);
I believe that this can help somebody and save him from angry downvoiters.
A: It is quite simple: You can't.
new ArrayConverter().CanConvertFrom(typeof(string));
returns false.
Your best option is the option you mentioned yourself: string.Split, or derive from ArrayConverter and implement your own:
public class StringArrayConverter : ArrayConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string s = value as string;
if (!string.IsNullOrEmpty(s))
{
return ((string)value).Split(',');
}
return base.ConvertFrom(context, culture, value);
}
}
In the end, I still use string.Split. You can come up with our own implementation of course.
A: You can use Regex.Matches:
string[] result =
Regex.Matches("foo1,foo2,foo3", @",").Cast<Match>().Select(m => m.Value).ToArray();
Edit: I didn't get the regex right, but the main point still stands.
| |
doc_23528327
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ArrayList.h"
void initArray(Array *a, size_t initialSize) {
a->array = (int *)malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
void insertIntoArray(Array *a, int element) {
if (a->used == a->size) {
a->size *= 2;
a->array = (int *)realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}
void removeLast(Array *a)
{
if (a->used == 0) {}
else{
a->used--;
}
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
int main(){
Array a;
initArray(&a,10); // initially 10 elements
int i;
for(i=0;i<100;i++)
insertIntoArray(&a,i);
printf("%d\n",a.array[9]);
printf("%d\n", a.used);
freeArray(&a);
}
Now I need to modify this data structure to store char *’s in the resizeable array instead of integers.So I need to modify the functions for making a set empty, inserting and removing an element into the set, and checking whether an element is in the set. Also set does not include duplicate copies of the same string (char * with the same contents, We can use strcmp to compare strings).
So Please help to modify it.
Example :
MySet *s;
initSet(s);
insert(s, “Hello”);
insert(s, “world”);
insert(s, “Hello”);
del(s, “world”);
isInSet(s, “Hello”);
emptySet(s);
My ArrayList.h is something like this :
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
typedef struct {
int *array;
size_t used;
size_t size;
} Array;
void insertIntoArray(Array *a, int element);
void removeLast(Array *a);
void freeArray(Array *a);
void initArray(Array *a, size_t initialSize);
#endif
| |
doc_23528328
|
SELECT x FROM (
SELECT x,count(x) cnt FROM very_big_table WHERE (conditions) GROUP BY x
) sub
WHERE cnt > 10
Indexes to all WHERE conditions and x is obvios. Any other suggestions?
A: Try using the HAVING() clause which is used exactly for this purposes (filters on aggregated columns) :
SELECT t.x,count(t.x) as cnt
FROM YourTable t
WHERE < >
GROUP BY t.x
HAVING count(t.x) > 10
A: Well, there is no way to speed up this query but to work on WHERE expression
| |
doc_23528329
|
array 1: Array ( [0] => Merc [1] => # [2] => BM [3] => & [4] => Lotus )
array 2: Array ( [0] => 6740 [1] => 4565 [2] => 3423 )
The goal is to combine the 2 arrays and end up with:
$result = ['Merc' => 6740, 'BM' => 4565, 'Lotus' => 3423];
There is a fair amount of guidance on this already, I know, and I have read up on it but array manipulation is new to me and somehow I just cannot get my head around the logic and syntax.
Please could someone with an experienced eye tell me where I am going wrong.
I have tried:
...
//// lets echo the arrays to make sure they are correct
print_r($car);?><br><?php
print_r($part);?><br><?php
//// lets combine the 2 arrays to get an associative array
$result = [];
for($i = 0; $i < count($car); $i++){
if (($car[$i] == "&")||($car[$i] == "#")){
$i = ($i + 1);
}
foreach($car as $car) {
foreach($part as $part) {
$result[] = array(
$car => $part,
);
}
}
}
print_r($result);
The output for this is:
Array ( [0] => Array ( [Merc] => 6740 ) [1] => Array ( [BM] => 4565 ) [2] => Array ( [Lotus] => 3423 ))
The special characters to be stripped will only ever be # or &
A: Filter out the unwanted elements and combine them.
Code: (Demo)
$cars=['Merc','#','BM','&','Lotus'];
$parts=[6740,4565,3423];
$cars=array_diff($cars,['#','&']);
var_export(array_combine($cars,$parts));
Output:
array (
'Merc' => 6740,
'BM' => 4565,
'Lotus' => 3423,
)
p.s. You could also filter with ctype_alpha() like this: (Demo)
$cars=array_filter($cars,'ctype_alpha'); // only retain elements that are fully comprised of letters
| |
doc_23528330
|
For example, if user A has friend B, and has sent a message to friend B in the past, I'd like the app to remember friend B. Is it possible to directly invoke and send message "hello" to friend B from Android app?
A: As far as I know, this is not possible.
According to Facebook policy, it is not allowed to auto-post / send / or pre-fill messages to friends.
| |
doc_23528331
|
What I wanna achieve is, that
if my Anpassung (adjustment) isn't 0, 0,00 or [empty], the next Begründung (reason) should be a mandatory-field.
I tried it with many attempts already, but I'm not getting into it: Here is my current approach:
$('.anpassung').keyup(function() {
//check if there are values which need a reason before validating
$('.anpassung').each(function(k, v) {
if($(this).value != '' && $(this).value != 0 && $(this).value != "0,00") {
console.log($(this).parent().find(".bemerkung").val());
//$(this).next(".bemerkung").css("border", "1px solid red");
}
});
});^
Everytime I adjust the values from Anpassung, I have to re-validate the "mandatory"-field. Adding a constraint / selector a la required true shouldn't be the problem.
Right now however, I simply cannot get the field Begründung.
For complete code, this here is the HTML of the two fields:
<input type="text" class="anpassung" name="anpassung_<%=count%>" size="15" maxlength="15">
<textarea class="bemerkung" name="bemerkung_<%=count%>" cols="50" height="20"
rows="3" maxlength="250"></textarea>
I also tried to use next() and closest(), but without success.
Thanks in advance
A: If your inputs are wrapped in a table you will need to do something like this
$('.anpassung').keyup(function() {
if($(this).val() != '' && $(this).val() != 0 && $(this).val() != "0,00") {
$(this).closest("td").next().find(".bemerkung").css("border", "1px solid red");
}
});
A: Assuming your elements are in a table, You get the Begründung like this -
$(this).closest('tr').find(".bemerkung").val();
If not using a table, you can replace the tr with any other element that is a parent of both of the elements.
By the way, you should do the validation check also when the user edits the Begründung field.
A: Try this :
$('.anpassung').keyup(function() {
var value = $(this).val().trim();
value = parseFloat(value) || 0.0;
if(value==0.0) {
$(this).closest("tr").find".bemerkung").css("border", "1px solid red");
}
});
| |
doc_23528332
|
__weak Foo *_weakFoo = [object foo];
Why would I want to do that for a local, temporary variable? __weak is a zeroing reference which will set the _weakFoo pointer automatically to nil as soon as the referenced object gets deallocated. Also, __weak is only available in iOS >= 5.
When would I run into trouble when I simply do this?:
Foo *_weakFoo = [object foo];
This is always expected to return an object or nil. My guess is this:
Foo *_weakFoo = [object foo];
[self doSomethingStupid]; // does something bad so foo gets deallocated
[_weakFoo doIt]; // CRASH! msg sent to deallocated instance 0x123456
One thing that still bugs me with ARC is: When does it know that I don't need an object anymore? I'd argue that when I set a pointer to nil or to something else it figures out that the previously referenced object isn't needed by this owner anymore and therefore maybe can go away. But the point is: I set it to nil. So it's nil anyways!
So when would __weak for a local variable make sense, and what kind of crazy thing must I do somewhere else so that I really need that?
A: I use __weak local variables if I have to manipulate self inside of a block to avoid a retain cycle. Consider this example where I'm using GCD and blocks to perform a network request for a string, and then setting it on a label declared by the class, in this case, TurtlesViewController.
__weak TurtlesViewController *weakSelf = self;
dispatch_queue_t networkQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(networkQueue, ^{
// Kick off a network task for some data that is going to populate a label declared on our class
NSString *returnString = [networkDataSource retrieveTurtleTime];
// Dispatch back to the main thread to populate the UILabel
dispatch_async(dispatch_get_main_queue(), ^{
// Using self.label here creates a retain cycle. Self owns the block and the block has captured self
self.label.text = returnString;
// Instead, we use weakSelf for our reference to the label as it will be torn down by ARC at the end of the loop.
weakSelf.label.text = returnString;
});
});
| |
doc_23528333
|
I am using dotnetnuke version 9.
Does dotnetnuke 9 support Arabic languages?
A: The best answer appears to be:
you should localize your portal; and for create right to left portal you should edit Default.css file in 'portals/_default' directory
Regards
Mohammad
Reference
| |
doc_23528334
|
<TextBlock Grid.Column="1" Foreground="White" VerticalAlignment="Center"
TextOptions.TextFormattingMode="Display" TextOptions.TextRenderingMode="ClearType"
FontSize="16" FontFamily="SegoiUI" Text="{TemplateBinding Title}"
TextTrimming="CharacterEllipsis"/>
So, this TextBlock shows my window Title. The problem is, that value of TextBlock is not visible in design-time:
When I launch my application, window title appears:
How can I make TextBlock show it's text in the window constructor?
| |
doc_23528335
|
try:
yield 1
finally:
print("finally")
def main():
print(next(gen()))
This code prints
finally
1
I don't understand the order of execution here. Why is "finally" printed before "1"?
A: The reason why "finally" is printed before "1" is because the first thing Python does is resolve next(gen()), which involves returning 1 and printing "finally". Once Python is done executing next(gen()), it has printed finally, and has a value of 1. Now, it can resolve print(1), which prints "1".
A: Here is an Example what is happening
*
*next(gen()) is executed -> gen() prints "finally" -> next() gets the value
*next() returns the value
*print() prints the value
You have to look here inside first and then the outer shell and the outer outer shell etc.
A: You can rewrite the line print(next(gen())) as
g = gen() # temporary variable
val = next(g)
# # the generator is now deleted because the variable g is not referenced anymore
del(g) # that calls the "finally" block `print("finally")`
print(val)
If you assign the generator to a variable, but don't delete it then it is recycled at the end of main function. That is what you probably expect.
A generator should be assigned to a variable if you use it by next(), otherwise there would be no way to use a generator with more items because it would be recycled after the first item!
| |
doc_23528336
|
I've managed to break the y-axis, but the command: subplots_adjust does not seem to work.
Current code:
def scatter_plot(data, x, y, hue, anon):
imgdata = BytesIO()
fig, (ax1, ax2)= plt.subplots(2, 1, figsize=fig_size, sharex=True)
cols = list()
for key in colors.keys():
if re.search('Warm_.+|Cold_.+', key):
cols.append(colors.get(key))
data.rename(columns={x: f'{x} (mio. DKK)', y: f'{y} (mio. DKK)'}, inplace=True)
print(colors)
ax1 = sns.scatterplot(x=f'{x} (mio. DKK)', y=f'{y} (mio. DKK)', data=data, ax=ax1, hue='Forsikringsselskab', style='Årstal',
palette=cols[0:len(colors)-1])
ax2 = sns.scatterplot(x=f'{x} (mio. DKK)', y=f'{y} (mio. DKK)', data=data, ax=ax2, hue='Forsikringsselskab', style='Årstal',
palette=cols[0:len(colors)-1])
plt.legend(frameon=True, loc=(1.04, 0.5))
ax2.set_ylim(-90, 150)
ax1.set_ylim(250, 290)
ax1.get_legend().remove()
ax1.set_ylabel("")
ax2.set_ylabel("")
fig.text(0.002, 0.55, 'Investeringsafkast før forsikringsteknisk rente (mio. DKK)', va='center', rotation='vertical')
plt.axhline(0, linestyle=':')
plt.subplots_adjust(hspace=0.2)
plt.tight_layout()
fig.savefig(imgdata, format='png', dpi=300)
plt.close()
return imgdata
The current output of this code creates:
Output
My desire is to mimimize the distance. What am I missing?
Thank you in advance for your time!
| |
doc_23528337
|
<form action="<?php echo $paypal_url; ?>" method="post" name="frmPayPal1">
<input type="hidden" name="business" value="<?php echo $paypal_id; ?>">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="item_name" value="amount">
<input type="hidden" name="amount" value="<?php echo $amount; ?>">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="handling" value="0">
I want get payment for service business, but this will show product business. Please help me to solve this question? (it mean don't show quantity)
A: then I use this code.it will some good.
<form action="<?php echo $paypal_url; ?>" method="post" name="frmPayPal1">
<input type="hidden" name="business" value="<?php echo $paypal_id; ?>">
<input type="hidden" name="cmd" value="_xclick-subscriptions" />
<input type="hidden" name="item_name" value="fee">
<input type="hidden" name="a3" value="<?php echo $amount; ?>"/>
<input type="hidden" name="p3" value="1"/>
<input type="hidden" name="t3" value="D"/>
<input type="hidden" name="src" value="1"/>
<input type="hidden" name="sca" value="1"/>
<input type="hidden" name="no_note" value="1"/>
| |
doc_23528338
|
void syscall(uint64_t arg1, uint64_t arg2) {
// arg1 -> rax arg2 -> rdi
__asm__("syscall" : : "a" (arg1), "D" (arg2));
}
When I compile that I get:
mov eax, 60
syscall
I'm in a function, so "edi" is being get from arguments, but like you can see is "eax", I want to use rax.
How can I force 64bit registers instead of 32bit ones?
A: This actually sets the RAX register to 60:
mov eax, 60
Writing to EAX always clears the upper 32-bit half of the 64-bit register. This is not like AH and AL, where writes preserve the rest of the register.
If you absolutely want a move to RAX, you need to use something like this:
static inline __attribute__ ((always_inline)) void
syscall(uint64_t arg1, uint64_t arg2)
{
__asm__("mov rax, %0; syscall" : : "i" (arg1), "D" (arg2) : "rax");
}
Note that gas will still assemble this as a 32-bit immediate move.
| |
doc_23528339
|
IS anyone familiar with this implementation?
A: @Eatlon, you can use a contact importer that works on mobile, like CloudSponge.com. You can use the widget version: it'll provide a list to the user select which contacts to import (Gmail, Yahoo, Outlook.com, etc), ask the user consent, show all contacts to select and then return to you all the selected contacts.
| |
doc_23528340
|
Thanks.
| |
doc_23528341
|
The biggest issue seems to be dplyr 0.5 which is the latest avaiable package for this service (current CRAN package is 0.7.4)
Am I doing something wrong? maybe something in provisioning (like selecting the wrong type of cluster)?
I can not believe MS would put so much work in R and not update it's cluster service, I must be missing something here.
A: You can install all dependencies rather quickly - it took me about 20 minutes. Just look at the error messages and install the packages stated. I needed only these ones
| |
doc_23528342
|
Here's my code :
If ActivePresentation.Slides(4).Shapes("Rectangle 84").TextFrame.TextRange.Text.Value >= ActivePresentation.Slides(4).Shapes("Rectangle 95").TextFrame.TextRange.Text.Value Then XXXX
Unfortunately if Rectangle 84 has a value of "11" and Rectangle 95 a value of 6, then currently the 6 is highlighted.
Is there any way to convert the text to a numerical value so I get the right result please?
Thanks
James
A: Try converting the values to numbers first, for example using CLng (convert to long) or CDbl (convert to double) if you expect non-integers.
If CDbl(ActivePresentation.Slides(4).Shapes("Rectangle 84").TextFrame.TextRange.Text.Value) >= CDbl(ActivePresentation.Slides(4).Shapes("Rectangle 95").TextFrame.TextRange.Text.Value) Then XXXX
The string "11" is "smaller" than "6" because they get sorted alphabetically.
You could also check if the text is valid using IsNumeric before converting to prevent type mismatches
| |
doc_23528343
|
So I wrote the code:
public void method(Quaternion rotation)
{
Vector3 vector = rotation.eulerAngles;
process(vector); // doesn't change vector
Quaternion result = Quaternion.Euler(vector.x, vector.y, vector.z);
if (rotation != result)
{
using (StreamWriter writer = new StreamWriter("Quaternions", true))
{
writer.Write(rotation + "\t->\t" + vector + "\t->\t" + result + "\n");
}
}
}
And got results means Quaternions rotation and result are not same.
(0.1, 0.0, 0.0, 1.0) -> (13.4, 348.3, 359.3) -> (0.1, -0.1, 0.0, 1.0)
(0.1, -0.1, 0.0, 1.0) -> (10.3, 0.1, 358.6) -> (-0.1, 0.0, 0.0, -1.0)
(0.1, 0.1, 0.0, 1.0) -> (13.2, 349.1, 359.3) -> (0.1, -0.1, 0.0, 1.0)
(0.1, -0.1, 0.0, 1.0) -> (10.3, 0.1, 358.6) -> (-0.1, 0.0, 0.0, -1.0)
(0.1, 0.1, 0.0, 1.0) -> (13.9, 346.0, 359.6) -> (0.1, -0.1, 0.0, 1.0)
I tried to change Quaternion.Euler(vector.x, vector.y, vector.z) to Quaternion.Euler(vector), if (rotation != result) to if (rotation.normalized != result.normalized), but nothing changed.
Please teach me how I can correctly transform Quaternion to Vector3 and back into Quaternion.
Thanks in advance.
Edit: precise version
(0.1208651, -0.1202484, 0.0108935, 0.9852986) -> (13.9, 346.3, 359.4) -> (0.1205529, -0.1181887, 0.0094058, 0.9856012)
(0.1117781, -0.0784635, 0.0001221, 0.9906307) -> (13.9, 346.6, 359.4) -> (0.1206529, -0.1155783, 0.0093524, 0.9858990)
(0.1206530, -0.1155784, 0.0093524, 0.9858992) -> (13.2, 349.1, 359.3) -> (0.1146793, -0.0939169, 0.0047323, 0.9889418)
(0.1102806, -0.0695964, -0.0030001, 0.9914563) -> (13.7, 347.4, 359.1) -> (0.1191836, -0.1079238, 0.0057138, 0.9869727)
(0.1191836, -0.1079238, 0.0057138, 0.9869727) -> (12.9, 350.0, 359.1) -> (0.1130020, -0.0854713, 0.0017047, 0.9899103)
Upd:
Thank you everyone who answered! I decided to not convert Quaternion to Vector3 and back.
A: first off, odd way to debug something in Unity.
And now to the question. Why are you trying to convert something to something else and then back to itself? According to your code you are not changing the created Vector3, so why not just use the original Quaternion?
EulerAngles can't really hold as much information about the rotation of a Quaternion than the Quaternion itself, so It's very likely that information can get lost or altered when working with Eulers.
Here are the two links to Unity-Documentation that you might wanna look at. The first explains, why working with EulerAngles tends to be inconsistent and the other might have a solution for whatever it is you're trying to do.
https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html
https://docs.unity3d.com/ScriptReference/Quaternion-operator_multiply.html
| |
doc_23528344
|
private void reloadData()
{
rebuildAdapter();
tables[gridNumber] = new DataTable();
adapters[gridNumber].Fill(tables[gridNumber]);
grids[gridNumber].ItemsSource = tables[gridNumber].DefaultView;
}
What am I missing?
A: Ok, solved that now. I had overlooked that the boolean value "isManualEditCommit" also needs to be set to false again when a DBConcurrencyException is thrown. For anyone interested, see code below:
private void grids_CellEditEnding(object sender, Microsoft.Windows.Controls.DataGridCellEditEndingEventArgs e)
{
try
{
Microsoft.Windows.Controls.DataGrid grid = (Microsoft.Windows.Controls.DataGrid)sender;
gridNumber = Convert.ToInt16(grid.Name.Substring(grid.Name.Length - 1, 1)) - 1;
if (!isManualEditCommit)
{
isManualEditCommit = true;
grid.CommitEdit(Microsoft.Windows.Controls.DataGridEditingUnit.Row, true);
using (SqlConnection con = new SqlConnection(GUI.dictSettings["connectionString"]))
{
con.Open();
SqlCommandBuilder com = new SqlCommandBuilder(adapters[gridNumber]);
adapters[gridNumber].UpdateCommand = com.GetUpdateCommand();
adapters[gridNumber].Update(tables[gridNumber]);
tables[gridNumber].AcceptChanges();
con.Close();
}
isManualEditCommit = false;
}
}
catch (DBConcurrencyException ex)
{
isManualEditCommit = false;
reloadData();
} catch(Exception ex){
isManualEditCommit = false;
reloadData();
}
}
| |
doc_23528345
|
I was able to make a template with 3 columns : stock_code;item_name;price
All future imports will only have these 3 columns. Now here is my question:
*
*How can I determine the delimiter on import?
I have done the following on the file input
<input type="file" class="custom-file-input" id="File" accept=".csv/text/plain"
This sets the browse window to - custom files and not All files. The problem here is if they do set it to all files, I need to determine the delimiter so there is not an error.
2.In addition to determining delimiter I need to make sure that the file is only 3 columns
Useful Info:
I do have CSVHelper nuget package
and im working on asp.net mvc 4.6
Please help
A: I have written code that implements a "delimiter detector for csv data", so I can describe the strategy that I used. First, I defined a set of "acceptable delimiters" ordered by priority: ',', '\t', ';', '|'. Those are the most common delimiters that I've seen in use.
Then, I read the first line of data out of the csv, this could be done with StreamReader.ReadLine(). I then iterate over every character in the line, and keep track of how many times I see each delimiter. The delimiter that was seen the most is the winner.
This works quite well, especially when the first line in the file is a header row that contains mostly alpha character. However, for some cultures it is common to find ',' used as a decimal point in numbers, and they tend to use ';' as the CSV delimiter. If the first row is all numeric values with decimal points (no headers) then this algorithm can mis-detect ',' as being the delimiter. I doubt this would likely ever happen in practice.
My implementation can be seen here. There is a bit extra complexity because I'm processing data out of an intermediate buffer; that could be simplified if you adapted it to your own needs.
Depending on what you intend to do with the CSV data you could use the library that this code lives in: Sylvan.Data.Csv. It is available as a nuget package.
using Sylvan.Data.Csv;
...
// by default, detects delimiter and assumes a header row is present
var csv = CsvDataReader.Create("MyData.csv");
if(csv.FieldCount != 3) {
throw new Exception("Invalid file");
}
while(csv.Read())
{
if(csv.RowFieldCount != 3) {
// the row contains a different number of columns than expected
throw new Exception("Invalid row at " + csv.RowNumber);
}
var stockCode = csv.GetString(0);
var name = csv.GetString(1);
// this next line would throw a FormatException if the the price column doesn't contain
// a numeric value
var price = csv.GetDecimal(2);
}
| |
doc_23528346
|
Mon
20-04-2020 |Tue 21-04-2020|Wed 22-04-2020|Thu 23-04-2020|Fri 24-04-2020|Sat 25-04-2020|Sun 26-04-2020
I am a beginner so i don't know much about it and stuck on it from a while. Thanks in advance.
A: If you want to list the current week days, starting from Monday you can do this :
var today = DateTime.Now;
var startDate = today.AddDays(-(((today.DayOfWeek - DayOfWeek.Monday) + 7) % 7));
var endDate = startDate.AddDays(7);
var currentWeekDays = Enumerable.Range(0, 7).Select(x => startDate.AddDays(x));
And if you want to format a date to get Mon 20-04-2020, you can use the format "ddd dd-MM-yyyy".
To conclude, you can obtain Mon 20-04-2020|Tue 21-04-2020|Wed 22-04-2020|Thu 23-04-2020|Fri 24-04-2020|Sat 25-04-2020|Sun 26-04-2020 by doing this :
var formattedCurrentWeekDays = currentWeekDays.Select(d => d.ToString("ddd dd-MM-yyyy")).ToList();
var result = string.Join("|", formattedCurrentWeekDays);
Console.WriteLine(result);
| |
doc_23528347
|
A: Assuming you are using AWS Cognito to set up a user pool: go to your user pool in the AWS console. Go to APP Integration and create a cognito domain. It will generate a URL for the Cognito domain. Put this in the authorized javascript origins on the Google console.
See the documentation from AWS: https://aws.amazon.com/premiumsupport/knowledge-center/cognito-google-social-identity-provider/
| |
doc_23528348
|
Please tell me whats the problem.
Code
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
export default function App() {
return (
<View>
<Image
style={styles.backgroundImage}
source={require('./assets/bg.jpg')}
/>
</View>
);
}
const styles = StyleSheet.create({
backgroundImage: {
height: '100%',
width: undefined,
aspectRatio: 1,
zIndex: 1,
},
});
Its just showing white screen. Nothing else.
A: The react-native image component needs to have the size set by pixels.
So your first solution would be to get the dimensions of your screen/window and set the width and height accordingly. So you need to calculate using the aspect ratio. You can also use a resize mode like 'stretch', 'contain', 'cover', etc. as described here
import React from "react";
import { Image, StyleSheet, View, Dimensions} from "react-native";
const dimensions = Dimensions.get('window');
const imageHeight = Math.round(dimensions.width * 9 / 16); //calculate with aspect ratio
const imageWidth = dimensions.width;
function App() {
return (
<View>
<Image
style={styles.backgroundImage}
source={require('./assets/bg.jpg')}
/>
</View>
);
}
const styles = StyleSheet.create({
backgroundImage: {
height: imageHeight,
width: imageWidth,
zIndex: 1,
},
});
export default App;
Second solution:
as it seems that you want to set it as background image would be to use the BackgroundImage component as described here
function App() {
return (
<ImageBackground style={styles.backgroundImage} source={require('./assets/bg.jpg')} />
);
}
const styles = StyleSheet.create({
backgroundImage: {
height: '100%',
width: undefined,
aspectRatio: 1,
zIndex: 1,
}
});
| |
doc_23528349
|
But i'm stuck
Good thing is, I was able to compress using commandline
zip -r outputFile.zip *.dSYM
A: Command line works for me everytime
zip -r dysm.zip {GUID}.dSYM
A: I had the same issue. I was able to work around it by copying the dSYMs folder from my package contents to my hard drive. Then I could zip it instantly. I think the issue is trying to compress from the package contents.
I followed the steps from this answer but instead of compressing from the package contents I copied it to another folder then compressed.
| |
doc_23528350
|
function login_status() {
if (logged_in()) {
echo $log_status = "Sign Out";
}
else {
echo $log_status = "Sign In";
}
}
The function is inside a file and that file is included on all pages.
How can i show the function returned string "Sign Out" or "Sign In" inside my nav bar in all of my pages?
My nav bar code is inside a file called header.php and included on all pages just like the footer.
The function is working, I only need to know how to show the echoed text inside of my nav bar.
A: You could use output buffering and capture the echo calls:
ob_start();
login_status();
$o = ob_get_clean();
if ($o === "Sign In") {
// signed in
}
Or, you could write good code ;)
Output buffering works here, but this is of course not very good software design.
A: Use return instead of echo in function
function login_status()
{
if (logged_in()) {
$log_status = "Sign Out";
}
else {
$log_status = "Sign In";
}
return $log_status;
}
and get it:
<div>
<?php echo login_status(); ?>
</div>
| |
doc_23528351
|
/**
* This function returns either an array of email addresses and names or, optionally, a string that can be used in
* mail headers.
*
* @param string $type Should be 'to', 'cc', 'bcc', 'from', 'sender', or 'reply-to'.
* @param bool $asString
* @return array|string|bool
*/
public function getAddresses($type, $asString = false)
{
$type = ( $type == 'reply-to' ) ? 'replyTo' : $type;
$addressTypes = array('to', 'cc', 'bcc', 'from', 'sender', 'replyTo');
if (!in_array($type, $addressTypes) || !isset($this->$type) || count($this->$type) < 1)
return false;
if (!$asString) {
if ($type == 'from')
return $this->from[0];
elseif ($type == 'sender')
return $this->sender[0];
return $this->$type;
} else {
$outputString = '';
foreach ($this->$type as $address) {
if (isset($set))
$outputString .= ', ';
if (!isset($set))
$set = true;
$outputString .= isset($address['name']) ?
$address['name'] . ' <' . $address['address'] . '>'
: $address['address'];
}
return $outputString;
}
}
I have probably just made a dumb mistake, but I have no idea now. Any insight would be quite helpful.
So currently, I am just looping through the messages and outputing the message subject, from, to, and the body. For example:
$server = new Server('imap.myserver.com', 993);
$server->setAuthentication('test@domain.com', 'mypassword');
$messages = $server->getMessages();
$i = 0;
$output = "";
foreach($messages as $message) {
$html = true;
$subject = $message->getSubject(); //get the subject of the email
$sentFrom = $message->getAddresses('from'); // who sent the email
$sentTo = $message->getAddresses('to'); //who is the email to
$body = $message->getHtmlBody();
//construct the email with a wrapper for little nicer look
$output .= "<div class=\"email\">";
$output .= "<div class=\"header\">";
$output .= "<p>{$subject}</p>";
$output .= "<p>{$sentFrom}</p>";
$output .= "<p>{$sentTo}</p>";
$output .= "</div>";
$output .= "<div class=\"body\">";
$output .= $body;
$output .= "</div>";
$output .= "</div>";
}
echo $output;
if (++$i = 10) break;
If everything is working correctly, when I refresh the page, the script connects to the email server, checks the emails, and gather the subject, to, from, and body of all the emails in the foreach. It also will output the emails to the screen. Unfortunately, the only 2 variables not really working are the $sentTo and $sentFrom. I guess I am just confused why I am not getting the addresses returned to me using $sentTo = $message->getAddresses('to'); when the function in Message.php says:
* @param string $type Should be 'to', 'cc', 'bcc', 'from', 'sender', or 'reply-to'.
A: So, after digging into it further, I have found the solution. It appears that once I added in:
$arrayedTo = print_r($sentTo);
$arrayedFrom = print_r($sentFrom);
I got the following
Array
(
[0] => Array
(
[address] => firstlast@mydomain.com
[name] => My Name
)
)
Array
(
[address] => firstlast@sentfromdomain.com
[name] => Name of Sender
)
Therefore, in my foreach loop I had to do the following to get the proper results. I guess I just overlooked the fact that it was returning an array.
Sent From Address: {$sentFrom['address']}
Sent To Address: {$sentTo[0]['address']}
| |
doc_23528352
|
11645766.560000001000 -> 11645766.560000001
10190045.740000000000 -> 10190045.74
1455720.820000000100 -> 1455720.8200000001
etc...
I am using regex, over String.Trim(), because the numbers are in one string, actual example:
!BEGIN !>>C85.18 POS_LEVEL.T129{11645766.560000001000} = POS_LEVEL.T129 {10190045.740000000000} + WORK_LEVEL.T129{1455720.820000000100} END;
need to convert to:
!BEGIN !>>C85.18 POS_LEVEL.T129{11645766.560000001} = POS_LEVEL.T129{10190045.74} + WORK_LEVEL.T129{1455720.8200000001} END;
A: In .Net you can do the following
var newStr = Regex.Replace(input, "0+$",String.Empty);
A: If the numbers are embedded in a random string, regexes are the way to go:
Replace (?<=\.\d+?)0+(?=\D|$) with an empty string
That will trim trailing zeros if they appear after the period in a decimal number (it will always leave a single zero). It also accounts for numbers that appear at the very end.
And since you've added the .NET tag in the meantime, here's the code:
string replaced = Regex.Replace(
inputString,
@"(?<=\.\d+?)0+(?=\D|$)",
String.Empty);
A: ([0]+)\b
then delete $1
A: One caveat on the above RegEx AND Trim()... if your input does NOT have a decimal point, you could end up with wrong numbers. E.g., ("1000").TrimEnd('0') = 1.
This workaround will fix that issue:
string Trimmed = (Untrimmed.IndexOf('.')>=0) ? Untrimmed.TrimEnd('0') : Untrimmed;
Of course, the use of a "." for decimals is culture-specific--some cultures use commas. If you're trying to built in culture-awareness, you need to use System.Threading.Thread.CurrentThread.CurrentCulture.NumberDecimalSeparator instead of a literal '.' character.
Edit: Based on your edited question above, RegEx is the right answer. Something like:
Trimmed = RegEx.Replace(Untrimmed, "(\d\.\d*[1-9])0+([^\d]|$)", "$1$2");
(The [1-9] above is my lazy way to avoid \d being greedy and capturing the 0's, there's likely a more straightforward way to do it.)
A: The following will match zeros that follow a decimal point and any number of decimals, and that do not precede a decimal point or digit.
(?<=\.\d*)(0+)(?=[^.\d])
| |
doc_23528353
|
Website loads perfectly the homepage. Until I tried to load other pages they download a php file instead.
My Nginx config file is here:
location /oldwebsite{
try_files $uri $uri/ /oldwebsite/index.php$args /oldwebsite/index.php?q=$uri$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/pixlgraphx.sock;
fastcgi_index index.php;
fastcgi_read_timeout 180;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_param HTTPS "on";
fastcgi_param HTTP_X_FORWARDED_PROTO "https";
client_max_body_size 128M;
}
Nginx Config File
Nginx Config File 2
Nginx Config File 3
| |
doc_23528354
|
recyclerView = (RecyclerView) findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
views = new ArrayList<>();
d = new DatePicker(this);
views.add(d);
e = new TextInputEditText(this);
e.addTextChangedListener(this);
views.add(e);
ee = new TextInputEditText(this);
ee.addTextChangedListener(this);
// views.add(ee);
Button b = new Button(this);
b.setText("hi btn");
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "hi", Toast.LENGTH_SHORT).show();
}
});
views.add(b);
Adapter adapter = new Adapter(views, this);
recyclerView.setAdapter(adapter);
| |
doc_23528355
|
I've found this example http://mleibman.github.io/SlickGrid/examples/example5-collapsing.html, but i can't figure out how to add indents(preferably it'd be css class, which i can add on my backend).
I've tried to add cssClasses to slickgrid row, but this doesnt append selected class
What am i doing wrong?
A: Without much information from your problem, you can do a simple trick:
Add a level/number pair (this indicates the deep of the object) to every item of generated json. The slickgrid example you found is using a span element to set the indent. So, you need to do something like this:
<span style="display:inline-block;height:1px;width:"+(15*jsonObject['level'])+"px"></span>
If not works for you, please post more information.
| |
doc_23528356
|
Effectively two machines running in clustered mode.
On these same two machines I have also set up a ElasticSearch cluster.
I am writing around 150 000 records every sec... in batches of 5000
However, both the Java Processes of Elasticsearch and Spark use around 300% CPU when the Batch insert mode starts :(
Can someone shed some light as to what is happening?
A: This isnt a problem, just a maxing out of 3 of your 12 CPUs.
| |
doc_23528357
|
public static IHtmlContent Source(this IHtmlHelper html, string s)
{
var path = ServerMapPath() + "Views\\" + s;
I need to get the equivalent of Server.MapPath in asp.net core
A: recommended Solution
I recommend Don't use a static class. You can keep something similar to your class, and register it as a singleton.
public class SourceClass
{
private readonly IWebHostEnvironment _webHostEnvironment;
public SourceClass (IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment= webHostEnvironment;
}
private IHtmlContent Source(this IHtmlHelper html, string s)
{
string contentRootPath = _webHostEnvironment.ContentRootPath;
Path.Combine(contentRootPath,"Views",s)
}
}
Then, in Startup.ConfigureServices:
services.AddSingleton<SourceClass>();
Finally, inject SourceClass where you need it, instead of just statically referencing the class.
Another Solution
(Note :@regnauld provided this solution, but it had some drawbacks, which I thought would be fully answered)
But if you want to use a static method you can do(Note: In .Net Core 3 IHostingEnvironment is absolute and IWebHostEnvironment must be used instead ):
*
*for ServerPath ,use
((IWebHostEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment))).ContentRootPath
OR
*
*for WebRootPath (wwwroot) ,use
((IWebHostEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment))).WebRootPath
in this answer you can find more details.
I also recommend that you use this code:
var path = Path.Combine(WebRootPath,"Views",s)
instead of
var path = WebRootPath + "Views\\" + s
to run the code on all operating systems.
A: You need to inject IHostingEnvironment. Then:
var path = env.ContentRootPath + "Views\\" + s;
in an html helper you can do this:
((IHostingEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IHostingEnvironment))).ContentRootPath;
| |
doc_23528358
|
export type MyComponentProps = {
id: string
}
export const MyComponent = function(props: MyComponentProps) {
return (
<div>{props.id}</div>
);
}
Now, I want to make the id optional, but I do have a requirement to use identifiers so I make the id as optional and add a default prop.
import { v4 } from 'uuid';
export type MyComponentProps = {
id?: string
}
export const MyComponent = function(props: MyComponentProps) {
return (
<div>{props.id}</div>
);
}
MyComponent.defaultProps = {
id: `MyComponent-${v4()}`
}
Done! Except, now, if I render 2 different instances of MyComponent they will have the same id. How do I work around this? What I did is the following, but I am no react expert and I don't know if there is another way to accomplish this.
import { v4 } from 'uuid';
export type MyComponentProps = {
id?: string
}
export const MyComponent = function(props: MyComponentProps) {
const id = props.id?? `MyComponent-${v4()}`;
return (
<div>{id}</div>
);
}
A: If you want a per-component ID that stays the same between renders, you'll need to put it in state.
export const MyComponent = function(props: MyComponentProps) {
const [defaultId] = useState(v4)
const id = props.id ?? defaultId
return (
<div>{id}</div>
);
}
| |
doc_23528359
|
I am using the following line:
[[NSUserDefaults standardUserDefaults] setObject:object forKey:@"key"];
A: How much stuff is in your preferences? User preferences is not a database. There's a limit to what you should store there. And I hope you realise that you don't have to synchronise immediately after storing each single item to preferences, so storing five items shouldn't take longer than storing one.
| |
doc_23528360
|
The problem is that i am not able to use AppCompat library properly and its giving me
ClasscastException android.support.v7.widget.ShareActionProvider to action.View.ActionProvider
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity{
android.support.v7.widget.ShareActionProvider shareAction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
MenuItem item =(MenuItem) menu.findItem(R.id.menu_settings);
shareAction = (ShareActionProvider) MenuItemCompat
.getActionProvider(item);
shareAction.setShareIntent(createShareIntent());
return true;
}
public Intent createShareIntent() {
Intent share = new Intent(Intent.ACTION_SEND);
share.setAction(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, "TEST")
.setType("text/plain");
return share;
}
}
According the Guide at developer.android.com i am using the library correctly
Below is my menu file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:easyshare="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
easyshare:showAsAction="ifRoom"
easyshare:actionProviderClass="android.support.v7.widget.ShareActionProvider"
/>
</menu>
** Edited LogCat output ** Sorry earlier i was getting the exception as given in label but seeing now i am getting this error and somehow not able to find the problem
10-02 02:17:46.566: E/AndroidRuntime(896): FATAL EXCEPTION: main
10-02 02:17:46.566: E/AndroidRuntime(896): java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$styleable
10-02 02:17:46.566: E/AndroidRuntime(896): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:98)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:58)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
10-02 02 :17:46.566: E/AndroidRuntime(896): at net.mobitexter.easyshare.MainActivity.onCreate(MainActivity.java:16)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.app.Activity.performCreate(Activity.java:4465)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.app.ActivityThread.access$600(ActivityThread.java:127)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.os.Handler.dispatchMessage(Handler.java:99)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.os.Looper.loop(Looper.java:137)
10-02 02:17:46.566: E/AndroidRuntime(896): at android.app.ActivityThread.main(ActivityThread.java:4448)
10-02 02:17:46.566: E/AndroidRuntime(896): at java.lang.reflect.Method.invokeNative(Native Method)
10-02 02:17:46.566: E/AndroidRuntime(896): at java.lang.reflect.Method.invoke(Method.java:511)
10-02 02:17:46.566: E/AndroidRuntime(896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
10-02 02:17:46.566: E/AndroidRuntime(896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
10-02 02:17:46.566: E/AndroidRuntime(896): at dalvik.system.NativeStart.main(Native Method)
10-02 02:18:02.152: I/Process(896): Sending signal. PID: 896 SIG: 9
*See if the manifest helps *
The below is the code of my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.mobitexter.easyshare"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="net.mobitexter.easyshare.MainActivity"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
A: you need to replace the cast of ShareActionProvider like this
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
MenuItem item =(MenuItem) menu.findItem(R.id.menu_settings);
shareAction = (android.support.v7.widget.ShareActionProvider) item.getActionProvider();
shareAction.setShareIntent(createShareIntent());
return true;
}
It should be work correctly. Please Test it and tell me if it work correctly.
| |
doc_23528361
|
I wonder why is the functional language (programming) good for big data? Is it because of the way they compile the code, or some other reasons.
Also, if the idea is wrong, can anyone explain why its wrong?
ps: If there are similar questions, forgive me :P
A: One of the reasons is that having immutable variables let's you execute code in parallel and scale very easy.
A: Zdravko is right about immutable state making concurrency easier and less prone to race condition style bugs. However, that helps only with multi-threaded concurrency. When you talk about big data, you are talking about horizontally scaled cluster computing. Not much support for that in Functional Programming languages.
There is something about FP that has captured the imagination of developers with Big Data dreams. Maybe it has something to do with FP's stream oriented higher order functions which let you think in terms of processing data streams. With FP, you solve problems with languaging such as union, intersection, difference, map, flatmap, and reduce.
But FP alone won't work in a distributed computing environment. At OSCON 2014, I learned about some open source projects that integrate FP languages with Hadoop. See Functional Programming and Big Data for a comparative evaluation of three such projects getting traction there days; Netflix Pig Pen, Cascalog, and Apache Spark.
| |
doc_23528362
|
*
*Browsing to C:\Windows\assembly gives an empty list.
*From the Developer Command Prompt (as admin), gacutil -l returns Number of items = 0
*Using a DOS Command prompt to list the contents of C:\Windows\assembly and C:\Windows\Microsoft.NET\assembly shows that there are quite some items installed.
*Nirsofts GacViewer tool shows 589 installed assemblies.
*Visual studio is running, can open and build solutions, only the WinForms designer has some quirks (probably related to missing items in the GAC?).
It looks like a permissions issue at first glance, but I am local administrator on my machine, so what could be the problem? Does windows 10 require any additional rights for manipulating the GAC that a "local admin" does not have by default?
If I rightclick, and choose "run as administrator" to open a command prompt, and then run:
gacutil -i myassembly.dll
Then I still get:
Failure adding assembly to the cache: Administrator permissions are needed to use the selected options. Use an administrator command prompt to complete these tasks.
A: After installing the Microsoft .NET Framework Repair Tool, all the problems disappeared.
Apparently disabling the Windows Search service can help in some cases, but that didn't work for me. The repair tool did.
| |
doc_23528363
|
But, when I try to get auth() I get following error:
let auth = fire.auth()
^
TypeError: fire.auth is not a function
My code is very simple:
let admin = require('firebase-admin');
let firebase = require('firebase');
const fire = firebase.initializeApp(config, "firebase");
let auth = fire.auth()
I'm, also, using Firebase Admin SDK for other functions and its auth() works fine.
There is some problem with use regular Firebase SDK on a Node.JS server?
EDIT:
I need both SDK because firebase-admin doesn't have functions like firebase.auth.sendPasswordResetEmail(email) or others.
Also, initializeApp is necessary for select the project in which I would operate.
A: Try deleting and re-installing node_modules. If the problem persists, you can add Firebase Authentication SDK to your script from the CDN:
<script src="https://www.gstatic.com/firebasejs/6.4.1/firebase-auth.js"></script>.
Refer here for the latest version: https://firebase.google.com/docs/web/setup
| |
doc_23528364
|
I want to replace these NaN values by mean value of other's DataFrames' corresponding values.
For exapmle let's look at 3 dataframes.
DataFrame1 with 1:M2 NaN :
M1 M2 M3
0 1 1 2
1 8 NaN 9
2 4 2 7
3 9 6 3
DataFrame 2 with NaN value at 0:M3:
M1 M2 M3
0 2 3 NaN
1 1 1 6
2 1 2 9
3 4 6 2
DataFrame3:
M1 M2 M3
0 1 4 2
1 2 9 1
2 1 6 5
3 1 NaN 4
So we replace NaN in first DataFrame by 5 (9+1)/2. Second NaN should be replaced by 2 because (2+2)/2, third by 6 and so on.
Is there any good and elegant way to do it?
A: We can concat , then using groupby fillna , after split should get what you need
s=pd.concat([df1,df2,df3],keys=[1,2,3])
s=s.groupby(level=1).apply(lambda x : x.fillna(x.mean()))
df1,df2,df3=[x.reset_index(level=0,drop=True) for _,x in s.groupby(level=0)]
df1
Out[1737]:
M1 M2 M3
0 1 1.0 2.0
1 8 5.0 9.0
2 4 2.0 7.0
3 9 6.0 3.0
A: This is one way using numpy.nanmean.
avg = np.nanmean([df1.values, df2.values, df3.values], axis=0)
for df in [df1, df2, df3]:
df[df.isnull()] = avg
df = df.astype(int)
Note: since np.nan is float, we convert explicitly back to int.
| |
doc_23528365
|
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
DatabaseClass::class.java,
"database_name",
)
.fallbackToDestructiveMigration()
.build()
A: This is to control different threads accessing the database at once, to prevent multiple instances being created. If you didn't synchronise here, then two different threads could both create a new instance of the database, whereas the singleton pattern is supposed to facilitate a single shared instance across the lifecycle of your program.
However the example you've linked in your question generally isn't enough and you should use something like double-check locking. So this might be better:
return INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase().also {
INSTANCE = it
}
}
As a side note, this isn't necessary. You could have no synchronisation and no shared instances. However it is recommended for the database to be a singleton due to expensive initialisation cost, so this is one example of a pattern to use.
| |
doc_23528366
|
It's really causing issues because if I end up doing something like duplicateName = duplicateName, it obviously doesn't work.
const duplicateName = "Hi";
if(1 == 1) {
const duplicateName = "Hey"
}
ES LINT
{
"env": {
"es6": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"plugin:@typescript-eslint/recommended",
"prettier",
"prettier/@typescript-eslint"
],
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
}
| |
doc_23528367
|
Why is, for example,
let gL = G_of 1L
[1L..100000L] |> List.map (fun n -> factorize gL n)
significantly slower than
[1L..100000L] |> List.map (fun n -> factorize (G_of 1L) n)
By looking at Reflector, I can see that the compiler is treating each of these in very different ways, but there is too much going on for me to decipher the essential difference. Naively I assumed the former would perform better than the later because gL is precomputed whereas G_of 1L has to be computed 100,000 times (at least it appears that way).
[Edit]
It looks like this may be a bug with F# 2.0 / .NET 2.0 / Release-mode, see @gradbot's answer and discussion.
A: Reflector shows test2() turned into 4 classes while test1() is turned into two classes. This only happens in debug mode. Reflector shows identical code (one class for each) in release mode. Unfortunately Reflector is crashing when I try to view the source in C# and the IL is really long.
let test1() =
let gL = G_of 1L
[1L..1000000L] |> List.map (fun n -> factorize gL n)
let test2() =
[1L..1000000L] |> List.map (fun n -> factorize (G_of 1L) n)
A quick benchmark.
let sw = Stopwatch.StartNew()
test1() |> ignore
sw.Stop()
Console.WriteLine("test1 {0}ms", sw.ElapsedMilliseconds)
let sw2 = Stopwatch.StartNew()
test2() |> ignore
sw2.Stop()
Console.WriteLine("test2 {0}ms", sw2.ElapsedMilliseconds)
Benchmarks ran on I7 950 @3368Mhz, windows 7 64bit, VS2010 F#2.0
x86 Debug
test1 8216ms
test2 8237ms
x86 Release
test1 6654ms
test2 6680ms
x64 Debug
test1 10304ms
test2 10348ms
x64 Release
test1 8858ms
test2 8977ms
Here is the complete code.
open System
open System.Diagnostics
let inline zero_of (target:'a) : 'a = LanguagePrimitives.GenericZero<'a>
let inline one_of (target:'a) : 'a = LanguagePrimitives.GenericOne<'a>
let inline two_of (target:'a) : 'a = one_of(target) + one_of(target)
let inline three_of (target:'a) : 'a = two_of(target) + one_of(target)
let inline negone_of (target:'a) : 'a = zero_of(target) - one_of(target)
let inline any_of (target:'a) (x:int) : 'a =
let one:'a = one_of target
let zero:'a = zero_of target
let xu = if x > 0 then 1 else -1
let gu:'a = if x > 0 then one else zero-one
let rec get i g =
if i = x then g
else get (i+xu) (g+gu)
get 0 zero
type G<'a> = {
negone:'a
zero:'a
one:'a
two:'a
three:'a
any: int -> 'a
}
let inline G_of (target:'a) : (G<'a>) = {
zero = zero_of target
one = one_of target
two = two_of target
three = three_of target
negone = negone_of target
any = any_of target
}
let inline factorizeG n =
let g = G_of n
let rec factorize n j flist =
if n = g.one then flist
elif n % j = g.zero then factorize (n/j) j (j::flist)
else factorize n (j + g.one) (flist)
factorize n g.two []
let inline factorize (g:G<'a>) n = //'
let rec factorize n j flist =
if n = g.one then flist
elif n % j = g.zero then factorize (n/j) j (j::flist)
else factorize n (j + g.one) (flist)
factorize n g.two []
let test1() =
let gL = G_of 1L
[1L..100000L] |> List.map (fun n -> factorize gL n)
let test2() =
[1L..100000L] |> List.map (fun n -> factorize (G_of 1L) n)
let sw2 = Stopwatch.StartNew()
test1() |> ignore
sw2.Stop()
Console.WriteLine("test1 {0}ms", sw2.ElapsedMilliseconds)
let sw = Stopwatch.StartNew()
test2() |> ignore
sw.Stop()
Console.WriteLine("test2 {0}ms", sw.ElapsedMilliseconds)
Console.ReadLine() |> ignore
| |
doc_23528368
|
A: Linking is the process of connecting all the compiled objects to each other to form the final executable. When you call a function in one piece of code, it's the job of the linker to hook the code that calls the function to the code that implements the function.
A: Source: here
"Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned."
In other words: Linking connects together all your compiled libraries/binaries that depend on each-other so that execution of your program will be possible.
| |
doc_23528369
|
hive> create table schema1.card_master like schema2.card_master;
That works, and it is partitioned as was the original on a field. This new table has hundreds of fields so they are inconvenient to list out, but I want all the fields populated from the original table using a Join filter. Now I want to populate it using a JOIN:
hive> insert overwrite table schema1.card_master (select * from schema2.card_master ccm INNER JOIN schema1.accounts da on ccm.cm13 = da.cm13);
FAILED: SemanticException 1:23 Need to specify partition columns because the destination table is partitioned. Error encountered near token 'cmdl_card_master'
I checked the partition that was copied over, and it was a field mkt_cd that could take on 2 values, US or PR.
So I try
hive> insert overwrite table schema1.card_master PARTITION (mkt_cd='US') (select * from schema2.card_master ccm INNER JOIN schema1.accounts da on ccm.cm13 = da.cm13);
FAILED: SemanticException [Error 10044]: Line 1:23 Cannot insert into target table because column number/types are different ''US'': Table insclause-0 has 255 columns, but query has 257 columns.
hive>
What is going on here? Is there any work around to load my data without having to explicitly mention all the fields in the Select statement for schema2.card_master ?
A: select * selects columns from each table in a join. Use select ccm.* instead of select * to select columns from ccm table only. Also remove static partition specification ('US'), use dynamic instead, because ccm.* contains partition column, and when you are loading static partition you should not have partition column in the select.
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
insert overwrite table schema1.card_master partition(mkt_cd) --dynamic partition
select ccm.* --use alias
from schema2.card_master ccm
INNER JOIN schema1.accounts da on ccm.cm13 = da.cm13
;
| |
doc_23528370
|
Why? I can not fine AUDITPIPE_SET_PRESELECT_MODE.
Can I use libbsm/openbsm in Swift?
var mode = AUDITPIPE_PRESELECT_MODE_LOCAL // <- works very well
if ioctl(auditFD, AUDITPIPE_SET_PRESELECT_MODE, &mode) == -1 {
return -1
}
A: I ran into the same issue with Swift unable to import these complex macros. Quinn “The Eskimo!” pointed me in the direction of declaring them as c constants. So I created them in a c file in my project.
In the .h file I did the following:
#include <stdio.h>
#include <bsm/libbsm.h>
#include <sys/ioctl.h>
#include <security/audit/audit_ioctl.h>
// -- Macros used for creating an auditpipe
extern unsigned long QAUDITPIPE_SET_PRESELECT_MODE;
extern unsigned long QAUDITPIPE_GET_QLIMIT_MAX;
extern unsigned long QAUDITPIPE_SET_QLIMIT;
extern unsigned long QAUDITPIPE_SET_PRESELECT_FLAGS;
extern unsigned long QAUDITPIPE_SET_PRESELECT_NAFLAGS;
// -- End auditpipe macros
And in my .c file i have:
unsigned long QAUDITPIPE_SET_PRESELECT_MODE = AUDITPIPE_SET_PRESELECT_MODE;
unsigned long QAUDITPIPE_GET_QLIMIT_MAX = AUDITPIPE_GET_QLIMIT_MAX;
unsigned long QAUDITPIPE_SET_QLIMIT = AUDITPIPE_SET_QLIMIT;
unsigned long QAUDITPIPE_SET_PRESELECT_FLAGS = AUDITPIPE_SET_PRESELECT_FLAGS;
unsigned long QAUDITPIPE_SET_PRESELECT_NAFLAGS = AUDITPIPE_SET_PRESELECT_NAFLAGS;
So now I can just use QAUDITPIPE_SET_PRESELECT_MODE in my Swift code. Works great!
| |
doc_23528371
|
selenium.click("link=target window");
selenium.selectWindow("Title of target window");
assertTrue((selenium.isTextPresent("content in target window")));
selenium.close();
selenium.selectWindow("null");
But if i run this i'm getting error like "Could not find window with title ... "
A: There is information about how the selectWindow() function locates the window here. In particular,
If you're having trouble figuring out what is the name of a window
that you want to manipulate, look at the selenium log messages which
identify the names of windows created via window.open (and therefore
intercepted by selenium). You will see messages like the following for
each window as it is opened:
debug: window.open call intercepted;
window ID (which you can use with selectWindow()) is "myNewWindow"
| |
doc_23528372
|
Following this article on MetamodelGenerator , I have configured annotation processor on intelij as suggested.
And my gradle file is as below. I have taken the hibernate-jpamodelgen artifact from maven central as suggested. But still i don't see any Meta Model classes being generated in the build/generated folder or sub-folder. How do i fix this. Any help will be greatly appreciated. This is a blocker for me.
buildscript {
repositories {
mavenLocal()
}
ext {
lombokVersion = '1.18.16'
}
}
plugins {
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.abc.reports'
version = '0.0.1'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
testAnnotationProcessor "org.projectlombok:lombok:${lombokVersion}"
implementation "org.projectlombok:lombok:${lombokVersion}"
implementation group: 'org.springframework.data', name: 'spring-data-jpa', version: '2.7.0'
implementation("org.liquibase:liquibase-core:3.8.2")
implementation("mysql:mysql-connector-java:8.0.17")
implementation 'org.hibernate.orm:hibernate-jpamodelgen:6.1.1.Final'
}
tasks.named('test') {
useJUnitPlatform()
}
As suggest by @y-bedrov - i am already using gradle for build and run
| |
doc_23528373
|
public abstract class RepositoryBase: IRepository
{
...
[AccessByRole]
public virtual void Add(T entity)
{
....
}
[AccessByRole]
public virtual void Update(T entity)
{
...
}
[AccessByRole]
public virtual void Delete(T entity)
{
...
}
[AccessByRole]
public virtual T GetById(long id)
{
...
}
}
Usage of repository (I'm using Autofac for IoC):
public class Service
{
private readonly IRepository repository;
public Service(IRepository repository)
{
this.repository = reporitory;
}
....
public UpdateUserEntities(...)
{
...
reporitory.Update(T); // There is a need for check user rights before calling this method.
}
}
There is a necessity of checking rights of the User before calling CRUD operations.
So my question is: How should the attributes source code look like, so the CRUD operations called after the rights checked?
A: Well, the easiest way would be to check the role in each action, and short circuit if that's not authorized. For example:
if(AuthorizedForRole[someAction]==true)
{
[some code]
}else{
Return "Unauthorized access attept";
}
| |
doc_23528374
|
A: A wizard is just a UI control with many steps in it. You can use it to insert, edit, delete or anything else you can think of. You can have an INSERT wizard and an EDIT wizard. The difference would be that there would be two of them and that the code behind for each one (presumably on the CompletedStep) would have slightly different code to persist the data. The insert wizard would call an insert database query and the edit one would call an update query.
That being said, you can access the control inside a FormView, I'm not sure why you said that you can't access controls indie a FormView. You can. See Using FindControl: Accessing Controls in a Formview.
You could even put the two wizards inside the two states of the formview - InsertTemplate and EditTemplate but thats getting a little crazy :)
| |
doc_23528375
|
Method vratiUtakmicu() is returning object like this:
{
nameOfFirstTeam: some string,
goalsFirstTeam: random number,
goalsSecoundTeam: random number,
nameOfSecoundTeam: some string
}
But when I call utakmicaToString() method it doesn't take value of goalsFirstTeam,goalsSecoundTeam
Instead looks like it's creating new random score and then print in console.
Copy my code and run so you will see the difference.
Can somebody explain to me why is this happening?
How can I fix this so method utakmicaToString() will take values
vratiUtakmicu(), and not creating random result again?
const arrEkipe = ["Srbija" , "Italija" , "Makedonija", "Bugarsk"];
class Utakmica{
constructor(ekipa1,ekipa2){
this.ekipa1 = ekipa1;
this.ekipa2 = ekipa2;
}
rezultat = () =>{
return Math.ceil(Math.random() * 6 );
}
vratiUtakmicu = () => {
return {domacin: this.ekipa1 , domaciGolovi: this.rezultat() ,
gostGolovi: this.rezultat(), gost: this.ekipa2}
}
utakmicaToString = () => {
return this.vratiUtakmicu().domacin + " " +
this.vratiUtakmicu().domaciGolovi + " : " +
this.vratiUtakmicu().gostGolovi + " " +
this.vratiUtakmicu().gost + " " ;
}
}
var Kolo1 = {};
for(let i = 0; i < arrEkipe.length;i+=2){
Kolo1["Utakmica" + i] = new Utakmica(arrEkipe[i],arrEkipe[i+1]);
}
console.log("The result form this console has to be the same")
console.log(Kolo1.Utakmica0.vratiUtakmicu())
console.log("like result from this console but it looks like utakmicaToString() sets new
random result")
console.log(Kolo1.Utakmica0.utakmicaToString())
| |
doc_23528376
|
The class "active" is not applied to the proper link. Any ideas how to fix this?
HTML:
<div data-spy="scroll" data-target="#navbar">
<div id="navbar" data-spy="affix" class="sticky-nav">
<ul class="nav inline">
<li><a href="#introduction">Introduction</a></li>
<li><a href="#products">Products</a></li>
<li><a href="#company">Company</a></li>
</ul>
</div>
<div class="sections">
<section id="introduction" name="introduction">Test1</section>
<section id="products" name="products">Test2</section>
<section id="company" name="company">Test3</section>
</div>
</diV>
A: It seems to work if you assign the data-spy and data-target attributes to a body tag instead of the containing div.
http://plnkr.co/edit/O1244QqRJEOcRfXCCk5J
| |
doc_23528377
|
<div id='innerWrapper'>
<img src ='image.png'" />
</div>
</div>
#wrapper{
display: table;
border-spacing:0;
}
#innerWrapper {
display:table-cell;
padding:0;
margin:0;
border:0;
}
img {
padding:0;
margin:0;
border:0;
}
In Chrome, this renders a 1px margin on right side of the image and pushes innerWrapper div out. How to remove the margin? CSS reset did not help
A: Have you tried
<div id='innerWrapper'><img src ='image.png'" /></div>
Without the line breaks in the source?
A: Reset the margins for all DIVs on the page:
div {
margin:0;
padding:0;
}
| |
doc_23528378
|
For Example:
unsigned char x[]="567";
unsigned char y[]="94";
Now I have to add the integer values in both x and y. That is:
int sum=661;
What is the simplest way to do this?
A: You're looking for atoi() .
A: You have at least two options if you use standard library. The first is atoi() function from stdlib.h and second is sscanf()function from stdio.h.
Here are examples:
atoi()
char number_string[] = "47";
int number;
number = atoi(number_string);
sscanf()
char number_string[] = "47";
int number;
int return;
return = sscanf(number_string, "%d", &number);
/* it would be good idea to check the return value here */
sscanf() gives you a better error handling. Return value of sscanf() determines how many items were succesfully read (how many variables were filled). If there was an input failure, EOF is returned.
atoi() returns 0 if no valid conversion could be performed.
| |
doc_23528379
|
servicenumber | meternumber | usagedatetime | usage
11111 | 22222 | 2019-01-01 | 1.85
11111 | 22222 | 2019-01-02 | 2.25
11111 | 22222 | 2019-01-03 | 1.55
11111 | 22222 | 2019-01-04 | 2.15
11111 | 33333 | 2019-02-01 | 2.95
11111 | 33333 | 2019-02-02 | 3.95
11111 | 33333 | 2019-02-03 | 2.05
11111 | 33333 | 2019-02-04 | 3.22
As you can see, a service number can be related to multiple meter numbers. Think of the service number as a unique identifier for a geographic location that doesn't change.
And I have a Django model:
class MeterUsage(models.Model):
objectid = models.IntegerField(
db_column='OBJECTID', unique=True, primary_key=True)
servicenumber = models.IntegerField(
db_column='serviceNumber', blank=True, null=True)
meternumber = models.IntegerField(
db_column='meterNumber', blank=True, null=True)
usagedatetime = models.DateTimeField(
db_column='usageDateTime', blank=True, null=True)
usage = models.DecimalField(
max_digits=38, decimal_places=8, blank=True, null=True)
And I have a basic serializer:
class MeterUsageSerializer(serializers.ModelSerializer):
class Meta:
model = MeterUsage
fields = (
'usagedatetime',
'usage'
)
And the current response is:
[
{
"usagedatetime": "2019-01-01",
"usage": "1.85"
},
{
"usagedatetime": "2019-01-02",
"usage": "2.25"
},
{
"usagedatetime": "2019-01-03",
"usage": "1.55"
},
....
]
But what I really want is (need the usage separated by meter number):
[
{
"servicenumber": "11111",
"meternumber": "22222",
"usagedata": [
{
"usagedatetime": "2019-01-01",
"usage": "1.85"
},
{
"usagedatetime": "2019-01-02",
"usage": "2.25"
},
{
"usagedatetime": "2019-01-03",
"usage": "1.55"
},
{
"usagedatetime": "2019-01-04",
"usage": "2.15"
},
...
]
},
{
"servicenumber": "11111",
"meternumber": "33333",
"usagedata": [
{
"usagedatetime": "2019-02-01",
"usage": "2.95"
},
{
"usagedatetime": "2019-02-02",
"usage": "3.95"
},
{
"usagedatetime": "2019-02-03",
"usage": "2.05"
},
{
"usagedatetime": "2019-02-04",
"usage": "3.22"
},
...
]
},
...
]
My end goal is to display this data in a line chart using the ChartJS library in an Angular 7 app, and the data needs to be in this format:
chartData = [
{
label: '22222',
data: [1.85, 2.25, 1.55, 2.15]
},
{
label: '33333',
data: [2.95, 3.95, 2.05, 3.22]
}
];
Is it possible to use a serializer to format the data as I've shown above? I've tried different techniques based on various tutorials I've read, but nothing seems to work and now I'm just confused about how to handle it.
Any insight is appreciated!
A: If you are not planning to change your model structure, you can not do what you want with a ModelSerializer. With ModelSerializer, you get 1 item in the resulting list for each database row, but you want to merge several rows into a single item in the resulting list. What you can try however, is selecting unique servicenumner - meternumber pairs and directly subclass Serializer to serializer your data.
In your view:
queryset = MeterUsage.objects.values('servicenumber', 'meternumber').distinct()
return Response(MeterUsageSerializer(queryset, many=True).data)
And your seriliazer:
class MeterUsageSerializer(serializers.Serializer):
servicenumber = serializers.IntegerField()
meternumber = serializers.IntegerField()
usagedata = serializer.SerializerMethodField()
def get_usagedata(self, obj):
return [{
'usagedatetime': item.usagedatetime.strftime('%Y-%m-%d'),
'usage': item.usage
} for item in MeterUsage.objects.filter(servicenumber=obj['servicenumber'], meternumber=obj['meternumber'])]
If you can change your model structure, you can structure your models and serializers in the following way:
class MeterUsage(models.Model):
objectid = models.IntegerField(
db_column='OBJECTID', unique=True, primary_key=True)
servicenumber = models.IntegerField(
db_column='serviceNumber', blank=True, null=True)
meternumber = models.IntegerField(
db_column='meterNumber', blank=True, null=True)
class Meta:
unique_together = ('servicenumber', 'meternumber')
class MeterUsageData(models.Model):
meterusage = models.ForeignKey(MeterUsage, on_delete=models.CASCADE, related_name='data')
usagedatetime = models.DateTimeField(
db_column='usageDateTime', blank=True, null=True)
usage = models.DecimalField(
max_digits=38, decimal_places=8, blank=True, null=True)
class MeterUsageDataSerializer(serializers.ModelSerializer):
usagedatetime = serializers.DateTimeField(format=''%Y-%m-%d'')
class Meta:
model = MeterUsageData
fields = ('usagedatetime', 'usage')
class MeterUsageSerializer(serializers.ModelSerializer):
data = MeterUsageDataSerializer(many=True)
class Meta:
model = MeterUsage
fields = ('servicenumber', 'meternumber', 'data')
With this model - serializers structure, you can get the output like this in the view:
queryset = MeterUsage.objects.filter(...)
return Response(MeterUsageSerializer(queryset, many=True).data)
Note that with both these approaches, you issue a database query for each servicenumber - meternumber pair.
A: I don't know exactly how to do this, but maybe something kind of like this:
# assuming you have current_response set to your first data format described in your question
# add "header dict" to every entry in current_response list, save as output
output = [dict() for x in len(current_response)]
for i, entry in current_response:
output[i] = {
"servicenumber": "11111",
"meternumber": i,
"usagedata": current_response[i],
}
# create chartData list with dict for every data point containing both meternumber and usagedata
chartData = []
for entry in output:
data_point = {
label: entry["meternumber"],
data: entry["usagedata"]["usage"]
},
chartData.append(data_point)
print(chartData)
Be warned, I haven't tested this, so I don't think it's working, but maybe I help you a bit at least with the concept of doing this.
A: This is just very simple task. Let me give you an insight..
The easy way is to create two tables.
The First (main) table should hold informations for service number and Meter number. The second table should be a sub table that will hold informations for usage and datetime.
Since the service number as a unique id, you can create the table to have a foreign key reference. Anyway the issue of foreign key is optional as you can get everything working without it.
In your code you will need to loop through the main table and then get the sub table where service number in the main table matches that of the sub table. Thats all.
Think of this as Post and comment tables will generate that kind of arrays with Post being the main table and Comment being a sub.
Let me know what you feel..
| |
doc_23528380
|
$qry = "
Select
MAX(changedate)
FROM
producten
";
$stmt = $connection->prepare($qry);
$stmt->error;
$stmt->execute();
$result = $stmt->get_result();
$up = $result->fetch_assoc();
$stmt->close();
$main .='Last update '.$up['changedate'];
But I receive this error message:
Notice: Undefined index: changedate in /home/jcslnl/domains/jcsl.nl/public_html/michael/paginas/home.php on line 22
Is this because MAX is not longer supported? Or should I continue to search for the error?
It could also be that I did something wrong in the table, it's the firsttime i used timestamp i.s.o. unix timestamp.
A: Aggregate functions will work in mysql, different to the sql standard. to access the value of MAX(changedate) from php, you have to alias it: like this
Select
MAX(`changedate`) as cngdate
FROM
your_table
A: The answer to your question is yes, mysqli supports MAX. However, you need to alias the column, since you aren't actually selecting the column changedate, but the result of a function which selects the value of changedate. In which case SELECT MAX(changedate) as changedate provides you with the desired result.
You can also use var_dump($up); to see this more clearly in your result.
A: print_r($up)
Why guess is that it is named something different. So just name it in your query
Select max(changedate) as maxdate
And then use $up['maxdate'] in your output.
A: add $stmt->bind_result($changedate); after the execute statement. i.e.
$qry = "
Select
MAX(changedate)
FROM
producten
";
$stmt = $connection->prepare($qry);
$stmt->error;
$stmt->execute();
$stmt->bind_result($changedate);
$stmt->close();
$main .='Last update '.$changedate;
A: The column result will actually be MAX(changedate), i.e. $up['MAX(changedate)'].
However to make it more readable you should use an alias for you selection
Select
MAX(changedate) as changedate
FROM
producten
and use the same $up['changedate'].
A: You have to add an alias for a result of MAX function,
SELECT MAX(changedate) AS maxdate
FROM producten
| |
doc_23528381
|
private void Page_Loaded(object sender, RoutedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
Page mainPage = rootFrame.Content as MasterPage;
Frame myframe = mainPage.FindName("frameBody") as Frame;
Page page1 = frame.Content as Page1;
Page page2 = frame.Content as Page2;
Button btnpage = page1.FindName("btnPage2") as Button;
}
When I navigate page2 or Load the page2 in the frame At that time i am not able to find the controls (TextBox, GridView) in page2 using the same code.
A: When you do Frame.Navigate(newPage) you are releasing all references to the old content and it gets garbage collected. If you want to persist data you need to cache the data. If you need to keep the controls, then you probably need to rethink your architecture.
The answer to your question is though, the reason you can't see the controls is because they no longer exist in the visual tree. They are removed and garbage collected. The way around this is to cache them.
Reference Information:
MSDN Frame Documentation
Reference Source - Frame.cs
and since your next question will be how to persist data between pages, check out
MSDN Frame.Navigate(Type,Object) Documentation
| |
doc_23528382
|
unsigned char *aes_decrypt(EVP_CIPHER_CTX *e, unsigned char *ciphertext, int *len)
{
int p_len = *len, f_len = 0;
unsigned char *plaintext = (unsigned char*)malloc(p_len + 128);
memset(plaintext,0,p_len);
EVP_DecryptInit_ex(e, NULL, NULL, NULL, NULL);
EVP_DecryptUpdate(e, plaintext, &p_len, ciphertext, *len);
EVP_DecryptFinal_ex(e, plaintext+p_len, &f_len);
*len = p_len + f_len;
return plaintext;
}
The problem is that len is returning a value that does not match the entire decoded string. What could be the problem ?
A: When you say "string", I assume you mean a zero-terminated textual string. The encryption process is dependent on a cipher block size, and oftentimes padding. What's actually being encoded and decoded is up to the application... it's all binary data to the cipher. If you're textual string is smaller than what's returned from the decrypt process, your application needs to determine the useful part. So for example if you KNOW your string inside the results is zero-terminated, you can get the length doing a simple strlen. That's risky of course if you can't guarantee the input... probably better off searching the results for a null up to the decoded length...
A: If you are using cipher in ECB, CBC or some other chaining modes, you must pad plain text to the length, which is multiple of cipher block length. You can see a PKCS#5 standard for example. High-level functions like in OpenSSL can perform padding transparently for programmer. So, encrypted text can be larger than plain text up to additional cipher block size.
| |
doc_23528383
|
int i = 0;
switch (i)
{
case 0:
int k = 0;
break;
case 1:
k = 1;
break;
}
Edit: even more strange, adding Console.Out.WriteLine(k); after case 1: gives error use of unassigned variable 'k'...
A:
Any reasons why this is permitted?
We probably cannot say for certain: The essential answer is "because it is" or "because your reasons for thinking it shouldn't be differ with the thinking of those who designed the language" but we can't really speak to questions like "what were Microsoft thinking when they designed it such that...", unless perhaps someone is one of the privileged few to have sat in that design meeting and can be authoritative
SharpLab.io will, however, tell you what happens under the hood; it compiles then decompiles your code and shows you the result, so you can get an idea of what your code was transformed into by the compiler:
Note: swapped your numbers for other, non-default, ones so that identification of what was what can be maintained after the compiler changes the names
A lot of the code you write is syntactic sugar for something else; here you can see your int k isn't buried within the switch, scoped to only "within the first case", but transformed into something else entirely.. It's thus legal C# because nothing prevents it not being, and you can rationalize that in a way that will help you remember it.. In a similar way, perhaps this looks like it shouldn't work:
object o = "";
if(o is string s){
}
s = "";
s looks, to me, like it's created within the scope of the if, yet it's accessible outside the if.. You'll find a similar explanatory transformation if you run that through SharpLab..
| |
doc_23528384
|
see http://jsfiddle.net/jfp06nc9/1/
showing this is undefined
However, when the setTimeout is used, then this is bound to window:
see http://jsfiddle.net/jfp06nc9/2/
and http://jsfiddle.net/jfp06nc9/3/
showing that this === window returns true.
so it looks like the function fn passed to setTimeout is invoked not as a function, but as a method, like window.fn() or fn.call(window) or (fn.bind(window))().
see http://jsfiddle.net/jfp06nc9/4/
showing the last 3 calls above would all show this === window as true.
Is that true? I can't find any specification about it so please include that in your answer.
(the jsfiddle was running in Chrome 46.0)
P.S. This question is NOT about what this is bound to, but about, in non-strict mode, setTimeout can run fn() and the this will be bound to window. But in strict mode, if setTimeout really runs it as fn(), then this should now be undefined instead of window, so there is a subtle difference there, that it seems setTimeout runs it (or arrange to run it) not as fn() but as fn.call(window)
The jsfiddle and code:
http://jsfiddle.net/jfp06nc9/7/
(function() {
"use strict";
setTimeout(function() {
"use strict";
console.log(this);
}, 1000);
}());
Since the function runs in strict mode, if it is run as a function, then this should be undefined but it is in fact window
A: setTimeout is part of the HTML spec (as opposed to ECMAScript), and it does indeed clarify that window should be used for this.
The relevant part of the spec is as follows:
*
*Let method context proxy be method context if that is a WorkerGlobalScope object, or else the WindowProxy that corresponds to method context.
(emphasis mine)
along with:
4.2 Run the appropriate set of steps from the following list:
If the first method argument is a Function
Call the Function. Use the third and subsequent method arguments (if any) as the arguments for invoking the Function. Use method context proxy as the thisArg for invoking the Function.
(emphasis mine)
| |
doc_23528385
|
int a = ...;
long b = ...;
if (a < b)
doSomethings();
always works (excepted for unsigned)
I just tested with a few values, but I want to be sure. I assume a is cast to long in the comparison, what about others type ?
A: In this condition
if (a < b)
an object of type int is always converted to the type long provided that one of the operands has type long because type long has higher rank than type int.
As for other types then according to the C Standard (6.5.8 Relational operators)
3 If both of the operands have arithmetic type, the usual arithmetic
conversions are performed.
It means that after the integer promotion an operand with a lower rank is converted to the type of the other operand.
A: int/long compare always works. The 2 operands are converted to a common type, in this case long and all int can be converted to long with no problems.
int ii = ...;
long ll = ...;
if (ii < ll)
doSomethings();
unsigned/long compare always works if long ranges exceeds unsigned. If unsigned range was [0...65535] and long was [-2G...2G-1], then the operands are converted to long and all unsigned can be converted to long with no problems.
unsigned uu16 = ...;
long ll32 = ...;
if (uu16 < ll32)
doSomethings();
unsigned/long compare has trouble when long ranges does not exceed unsigned. If unsigned range was [0...4G-1] and long was [-2G...2G-1], then the operands are converted to long, a common type that does not encompass both ranges and problems ensue.
unsigned uu32 = ...;
long ll32 = ...;
// problems
if (uu32 < ll32)
doSomethings();
// corrected solution
if (uu32 <= LONG_MAX && uu32 < ll32)
doSomethings();
// wrong solution
if (ll32 < 0 || uu32 < ll32)
doSomethings();
If type long long includes all the range of unsigned, code could use do the compare with at least long long width.
unsigned uu;
long ll;
#if LONG_MAX >= UINT_MAX
if (uu < ll)
#if LLONG_MAX >= UINT_MAX
if (uu < ll*1LL)
#else
if (uu32 <= LONG_MAX && uu32 < ll32)
// if (ll < 0 || uu < ll)
#endif
| |
doc_23528386
|
Now I see Templates > Visual C# > Cross-Platform > Cross Platform App. When I click on this, it takes me to a new screen where I can select Master Detail or Blank App as well as Forms/Native or Shared/PCL. I click the Blank App and select Forms & PCL then click Agree.
Visual Studio acts like it is trying to create the project. I get the "Creating project 'appname'...." dialog. However it just sits on this dialog and does nothing else. When I look at the folder structure, I can see that it has created the PCL folder and the Android folder. It does not create any other folder and I ultimately have to kill Visual Studio to get out of it as it will just sit there and spin.
I know the new project is supposed to be for VS2017, which I don't have. I'm not sure why I'm seeing the VS2017 new project instead of the VS2015 Cross-Platform project? Either way, I really need to create a new PCL project. What do I need to do to fix this?
A: I had the same problem and I solved by installing the xamarin version from Jan 27th 2017.
You can follow my SO post to install an older version of xamarin
A: I'm having the same problem. Last week, when it initially occurred, I ended up completely UNinstalling Visual Studio 2015, then reinstalling. The normal Xamarin new project templates were back after that. This morning as I started a new project, the Xamarin templates were missing again. Frustrating! Someone over on the Xamarin.com forums reported the same problem, and that they resolved by uninstalling Xamarin from the Control Panel then reinstalling (presumably from the Xamarin web site). This did NOT work for me when I tried it this morning.
@Daniel suggested rolling back to the previous version of Xamarin (v6.1.4 from January 27th). I tried this, but got the error...
"Gtk# version 2.12.22 or greater must be installed."
The install failed. Looks like I'm not able to roll back to the previous version.
@BillReiss suggested a Xamarin patch build for what seems like the same or similar problem (documented in VS2015 stops responding when I create or open a xamarin forms project). I tried installing this, but it does NOT restore the missing new project templates.
Anyone know where Visual Studio new project templates are stored, and whether it's possible to get new template files online?
A: Looks like this issue has been resolved with a new version of Xamarin for Visual Studio 2015 that rolled out today (v4.3.0.784). Xamarin's Cross-Platform "blank app" template is now available as "Cross Platform App (Xamarin.Forms or Native)". Once the template is selected, a dialog appears allowing the choice of Forms/Native and Shared/PCL projects.
New Visual Studio 2015 Cross-Platform "Blank App" Template
Cross-Platform App Template Helper
| |
doc_23528387
|
here is a working version of the style below on W3schools. Here
If I put a static Value into the tooltipcustom span it works perfectly but does not when I make it a data bound value.
I have research extensively and have only found one answer that seemed like it may work. they suggested to add a custom binding for tool tip but I am unable to do that in the current situation of the project.
<style>
.tooltipcustom {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltipcustom .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltipcustom .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltipcustom:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
This Div loops through a list of codes and each code has a list of the fields. each field will have its own tool tip that you can hover over that will give you the information about that field. the output would look like so with each separate data field having its own tool tip.
35B A 0000000000 00 001 02 BI 250-500 0000210 0000000
35B A 0000000000 00 001 03 PD 50 0000310 0000000
35B A 0000000000 00 001 04 UMB 250-500 0000008 0000000
<div data-bind="foreach: segmentCodes">
<div data-bind="foreach: fields">
<span class="tooltipcustom" data-bind="text: Value">
<span class="tooltiptext">test</span>
</span>
</div>
A: the trick here is to use container less binding
<!-- ko text: value --><!-- /ko -->
to stop overwriting the inner html
var ViewModel = {
segmentCodes: [{
fields: [{
value: 'some value',
tooltip: 'some value tooltip'
}, {
value: 'some value 22',
tooltip: 'some value 22 tooltip'
}]
},
{
fields: [{
value: 'other value',
tooltip: 'other value tooltip'
}]
}
]
};
ko.applyBindings(ViewModel);
.tooltipcustom {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltipcustom .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltipcustom .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltipcustom:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
.main {
margin: 50px;
}
.main span {
margin: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="main" data-bind="foreach: segmentCodes">
<div data-bind="foreach: fields">
<span class="tooltipcustom">
<!-- ko text: value --><!-- /ko -->
<span class="tooltiptext" data-bind="text: tooltip"></span>
</span>
</div>
</div>
| |
doc_23528388
|
I suspect the answer lies in the __eq__ method of the default object returned by object(). What is the implementation of __eq__ for this default object?
EDIT: I'm using Python 2.7, but am also interested in Python 3 answers. Please clarify whether your answer applies to Python 2, 3, or both.
A: object().__eq__ returns the NotImplemented singleton:
print(object().__eq__(3))
NotImplemented
By the reflexive rules of rich comparisons, when NotImplemented is returned, the "reflected" operation is tried. So if you have an object on the RHS that returns True for that comparison, then you can get a True response even though the LHS did not implement the comparison.
class EqualToEverything(object):
def __eq__(self,other):
return True
ete = EqualToEverything()
ete == object() # we implemented `ete.__eq__`, so this is obviously True
Out[74]: True
object() == ete # still True due to the reflexive rules of rich comparisons
Out[75]: True
python 2 specific bit: if neither object implements __eq__, then python moves on to check if either implement __cmp__. Equivalent reflexive rules apply here.
class ComparableToEverything(object):
def __cmp__(self,other):
return 0
cte = ComparableToEverything()
cte == object()
Out[5]: True
object() == cte
Out[6]: True
__cmp__ is gone in python 3.
In both python 2 and 3, when we exhaust all of these comparison operators and all are NotImplemented, the final fallback is checking identity. (a is b)
A: object doesn't implement __eq__, so falls back on the default comparison id(x) == id(y), i.e. are they the same object instance (x is y)?
As a new instance is created every time you call object(), my_object will never* compare equal to anything except itself.
This applies to both 2.x and 3.x:
# 3.4.0
>>> object().__eq__(object())
NotImplemented
# 2.7.6
>>> object().__eq__(object())
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
object().__eq__(object())
AttributeError: 'object' object has no attribute '__eq__'
* or rather, as roippi's answer points out, hardly ever, assuming sensible __eq__ implementations elsewhere.
| |
doc_23528389
|
However, the user and course field shows up as dropdowns. But they do not have any data in the dropdown list. How can I have django to pull data from the database and display the information into each dropdown on my form?
models.py:
class Student(models.Model):
user = models.OneToOneField(User)
course = models.ForeignKey(Course)
view.py:
def home(request):
if request.method == 'GET':
form = StudentForm()
else:
form = StudentForm(request.POST)
if form.is_valid():
pass
return render(request, "request.html", {'form': form}, context_instance=RequestContext(request))
forms.py:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
Update
Actually found out that the changes weren't saved to my DB. They are now loading into the form. However in the dropdown list, it is showing up as "Student Object", and "Course Object"
How can I make it so they show up with proper names?
A: I would advocate that you move away from doing this if this is testing, and instead follow the guidelines for testing as outlined in the django tutorials, i.e. it creates a fake database for you and you create Users and Courses via Users.objects.create(username=...)
| |
doc_23528390
|
In ApplicationController I added this code:
def default_url_options
{ locale: I18n.locale }
end
In theory, I should now always have the locale parameter in all URLs. Right? But why is this not happening? The first thing I need is to have the locale parameter absolutely always in the URL inside the specific namespace.
Next I have this controller:
class Public::BaseController < ApplicationController
layout 'public'
around_action :prepare_locale
private
def prepare_locale(&action)
received_locale = params[:locale].presence || I18n.default_locale
if I18n.available_locales.include?(received_locale.to_sym)
I18n.with_locale(received_locale, &action)
else
I18n.with_locale(I18n.default_locale, &action)
end
end
end
And this code, which is responsible for changing the locale parameter:
class Service::LanguagesController < Service::BaseController
def change
received_locale = params[:new_locale].presence || I18n.default_locale
redirect_back(
fallback_location: root_path,
allow_other_host: false,
params: { # this is to make sure
locale: received_locale
},
locale: received_locale
)
end
end
As a result, params[:new_locale] has a new locale. But redirect_back doesn't change anything. Why?
This code works:
redirect_to root_path(locale: received_locale)
But this option doesn't fit, as it is inconvenient.
In total, I don't understand how I can do what I intended.
A: I looked at rails internals and saw that redirect_back is a redirect_to passing referrer as first argument. See here
But in that case the params passed to redirect_to are ignored because it's just an String.
I suggest you to use redirect_to instead and pass locale explicit.
| |
doc_23528391
|
I used to have a lot of stuff going on in one of my controllers. Someone told me that its good practice to have "fat models and thin controllers" So I was moving some things over to the model.
In my controller's show method I used to have some @ variables that I would use in my view. Now I have those variables in a method in my model. Will I still be able to access those in my view? If so do I have to make any adjustments?
Thanks
A: You will have to create an instance of your model in the controller as an @ variable. You can then call the methods from that inside the view.
e.g. imagine you used to have some long bunch of logic in your controller which calculated a credit score for a customer culminating in
@credit_score = credit_score
and you've now moved this into a credit_score method on the Customer model.
You now just need
@customer = Customer.find...
in the controller
and you can the use <%= @customer.credit_score %> within the view.
This is what people mean by fat models and thin controllers. If you'd like some more advice then it's best to update the question with some specifics from your app.
A: The common practice is to define the variables of this kind in controllers:
@object = Model.new
to later use it in form_for or something like that. Some people use Model.new directly in views instead. That's somewhat unusual but still makes sense, especially knowing that Rails just loops through all of the instance variables in your controller every time to make them available in your views
| |
doc_23528392
|
Removed the opening part/protocol from the urls since i don't have the reputation to post this many links, but everything is https.
I have a page at: www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp
From the AMP cache: www-qponverzum-hu.cdn.ampproject.org/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp
I've been following the documentation at developers.google.com/amp/cache/update-ping
If i make an /update-ping request, it seems to work fine, returns a 200 no content response, but due to the high amount of urls/pages we would like to use /update-cache since it allows for a higher request rate.
I've created a private and public RSA key and made the public key acessible at www.qponverzum.hu/.well-known/amphtml/apikey.pub
I've been trying to use the following php code to generate the update-cache url
$ampBaseUrl = "https://www-qponverzum-hu.cdn.ampproject.org";
$signatureUrl = '/update-cache/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp?amp_action=flush&_ts='.time();
// opening the private key
$pkeyid = openssl_pkey_get_private("file://private-key.pem");
// generating the signature
openssl_sign($signatureUrl, $signature, $pkeyid)
// urlsafe base64 encoding
$signature = urlsafe_b64encode($signature);
// final url for updating
$ampUrl = $ampBaseUrl.$signatureUrl."&_url_signature=".$signature;
The urlsafe_b64encode function I'm using:
function urlsafe_b64encode($string) {
return str_replace(array('+','/','='),array('-','_',''), base64_encode($string));
}
$ampUrl ends up looking like this: https://www-qponverzum-hu.cdn.ampproject.org/update-cache/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp?amp_action=flush&_ts=1500362660&_url_signature=NjTCnmqUGpMY_CokGxchoczSOxnTLQvcQsX4fv2gIhW3H8hVw24mKCpmNoyV-9LND3OAR9ld80KeMH3lip863p_wBorIy1BAag7bRfvWcxsPrbqbox87VMrUWCEsry5epWxKYl2qNCT1GMv8SYAJ5WR0QZR0Qjvw5MXfZjohmbvrxJ7mWlc7fcvWoIXuO_q_yFkhi7A-fOZWm9sy8UDIlq-zNEPkVUwfqfWc_HbNHgvrk9Z6zZSNzB-dWAOT6QYAc1KeEVOIbvQxKkLkGMArTpydj5iLxz0aERvglKRl215Bqh6_jZu95T5yKv7X4R127ylpWYW2YDlTR9bgRE7Faw
If I make a simple GET request to this url(with a browser or curl) i get a 403 error('Your client does not have permission to get URL').
I've checked the webserver logs, but it doesn't seem like there're any requests made to the public keys url.
I think I'm missing something very obvious, so any feedback would be greatly appreciated.
A: There's an error in $signatureUrl - it should be amp_ts instead of _ts in the query params and in openssl_sign add the fourth parameter
openssl_sign($signatureUrl, $signature, $pkeyid, OPENSSL_ALGO_SHA256);
The signature needs to be signed with SHA256, if you omit the last parameter it uses SHA1
I've used your script with these 2 changes for my work project and it's working fine.
It should return "OK" in the response body if it's fine.
Check this https://gist.github.com/krzysztofbukowski/739ccf4061d69360b5b2c8306f5878bd
A: Try to set the response content type to "text/plain" for https://www.qponverzum.hu/.well-known/amphtml/apikey.pub as recommended in here
=========
I use the script for update cache, but I got the 403 forbidden error.
It's hard to debug and find out the root cause.
Did someone succed?
A: All the other answers have really helped - thanks. I'm adding a little here which may hopefully also help.
As @kul3r4 points out (I missed it first time round) the apikey.pub file needs to be served as plain text. Here is the Nginx config rule for that;
location /.well-known/amphtml/apikey.pub { ## serve amp public key as plain/text
default_type text/plain;
}
If you are echoing out @Krzysztof Bukowski's answer to the screen, the fact that & is in the url parameters means my browser was stripping out the amp part of the amp_ts and amp_url_signature so be aware of that.
If you are struggling with the file paths and syntax of this;
$pkeyid = openssl_pkey_get_private("file://amp-private-key.pem");
Then just follow this answer here and put the contents of your private key in a variable -> Openssl and PHP
| |
doc_23528393
|
private void FireMultishot()
{
StartCoroutine(Cooldown());
//Play the sound when the bullet is fired.
AudioSource.PlayClipAtPoint(fireBulletSound, Camera.main.transform.position);
GameObject Temporary_Bullet_Handler = Instantiate(Bullet, Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation) as GameObject;
GameObject Temporary_Bullet_Handler1 = Instantiate(Bullet, Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation);
GameObject Temporary_Bullet_Handler2 = Instantiate(Bullet, Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation) as GameObject;
//Rotate the top and bottom bullets by 30 degrees.
Temporary_Bullet_Handler1.transform.Rotate(Vector3.forward * 30);
Temporary_Bullet_Handler2.transform.Rotate(Vector3.forward * -30);
//Tell the bullet to be "pushed" forward by an amount set by Bullet_Forward_Force.
Temporary_Bullet_Handler.GetComponent<Rigidbody2D>().AddForce(transform.right * Bullet_Forward_Force);
Temporary_Bullet_Handler1.GetComponent<Rigidbody2D>().AddForce(transform.right * Bullet_Forward_Force);
Temporary_Bullet_Handler2.GetComponent<Rigidbody2D>().AddForce(transform.right * Bullet_Forward_Force);
//Basic Clean Up, set the Bullets to self destruct after 3 Seconds.
Destroy(Temporary_Bullet_Handler, 3.0f);
Destroy(Temporary_Bullet_Handler1, 3.0f);
Destroy(Temporary_Bullet_Handler2, 3.0f);
}
A: transform.right is not Temporary_Bullet_Handler1.transform.right
The former is the transform of your player and you're using that same value for all three bullets.
| |
doc_23528394
|
I have a set of results
Result 1
sub1
sub2
sub3
Result 2
sub1
sub2
sub3
I need to find how many times either set of the above results appears in a much larger data set of results below.
Result 1
sub1
sub2
sub3
Result 2
sub1
sub3
sub4
Result 2
sub1
sub2
sub3
Result 2
sub1
sub2
sub3
sub4
In the example above, Result 1 from the first set would match the first result in the second set, and Result 2 would match the final 2 results in the second set, because they contained all the sub results from the first set. So Result 1 would show a frequency count of 1, while Result 2 would show a frequency count of 2.
I'm rather new with SQL, but would like to find a solution to the above problem.
Sample Data from yesterday:
Group Ad Date
A 1 7/14
A 2 7/14
A 3 7/14
B 1 7/14
B 2 7/14
B 3 7/14
B 4 7/14
C 1 7/14
D 1 7/14
D 3 7/14
D 4 7/14
I need to find out how many times Group A Ads 1-3 ran in the past week, but say on Monday Group A ran only ads 1 and 3. I don't want this result returned. Tuesday Group A ran ads 1, 2, 3, 4. I WOULD want to know this result, Wednesday Group A had ads 1, 2, 3 run, this again I would want to know.
Group Ad Date
A 1 7/09
A 3 7/09
A 1 7/10
A 2 7/10
A 3 7/10
A 4 7/10
A 1 7/14
A 2 7/14
A 3 7/14
So, given the example, I would expect to see this:
Group Ad Date
A 1 7/10
A 2 7/10
A 3 7/10
A 1 7/14
A 2 7/14
A 3 7/14
A: It's a little messy, but here is what I was able to come up with:
SELECT a.*, b.*
FROM
(
SELECT 'A' AS grp, 1 AS ad UNION ALL
SELECT 'A', 2 UNION ALL
SELECT 'A', 3
) a
CROSS JOIN
(
SELECT DISTINCT date
FROM tbl
WHERE date >= CURDATE() - INTERVAL 1 WEEK
) b
LEFT JOIN tbl c ON a.grp = c.grp
AND a.ad = c.ad
AND b.date = c.date
INNER JOIN
(
SELECT a.date
FROM
(
SELECT 'A' AS grp, 1 AS ad UNION ALL
SELECT 'A', 2 UNION ALL
SELECT 'A', 3
) a
CROSS JOIN
(
SELECT DISTINCT date
FROM tbl
WHERE date >= CURDATE() - INTERVAL 1 WEEK
) b
LEFT JOIN tbl c ON a.grp = c.grp
AND a.ad = c.ad
AND b.date = c.date
GROUP BY a.date
HAVING COUNT(1) = COUNT(c.grp)
) d ON b.date = d.date
I'm a little too tired to write an explanation, but perhaps when I wake up tomorrow, I will continue my answer.
For now, you can view a SQLFiddle Example. Notice I have inserted four more values than there are in your example data to showcase how the query works when a set appears more than once per day.
^ You can see in the second executed query that you can also filter the frequency the set appears in each day via HAVING COUNT(1) >= 2.
A: In SAS SQL:
proc sql;
CREATE TABLE tbl (
grp CHAR(1),
ad INT,
date DATE
);
INSERT INTO tbl
values('A', 1, '09jul2012'd)
values('A', 3, '09jul2012'd)
values('A', 1, '10jul2012'd)
values('A', 2, '10jul2012'd)
values('A', 3, '10jul2012'd)
values('A', 4, '10jul2012'd)
values('A', 1, '14jul2012'd)
values('A', 2, '14jul2012'd)
values('A', 3, '14jul2012'd)
values('A', 1, '14jul2012'd)
values('A', 2, '14jul2012'd)
values('A', 3, '14jul2012'd)
;
quit;
proc sql noprint; /* the set and upper date I'm interested in */
CREATE TABLE my_set (
grp CHAR(1),
ad INT,
date DATE
);
INSERT INTO my_set (grp, ad)
VALUES ('A', 1)
VALUES ('A', 2)
VALUES ('A', 3)
;
update my_set set date=today()-1;
select count(*) into :my_set_size from my_set
;
quit;
proc sql;
create table potential_dates as
select t.date, s.grp, s.ad, count(*) as ad_occurrence
from my_set s
inner join tbl t
on s.grp = t.grp and s.ad = t.ad and s.date >= t.date
group by t.date, s.grp, s.ad
;
quit;
proc sql;
create table result as
select a.* from potential_dates a
inner join (select date from potential_dates
group by date
having count(*) = &my_set_size ) d
on a.date = d.date
;
quit;
date grp ad ad_occurrence
10JUL12 A 1 1
10JUL12 A 2 1
10JUL12 A 3 1
14JUL12 A 1 2
14JUL12 A 2 2
14JUL12 A 3 2
A: Maybe you could sort and transpose:
proc sort data=mydata1;
by group date;
run;
proc transpose data=mydata1 out=mydata2;
by group date;
var ad;
run;
data mydata3;
set mydata2;
if not missing(col1,col2,col3);
run;
You will have one row per date. If needed, you could merge this back on to your original data:
data mydata4;
merge mydata1 mydata3;
by group date;
run;
| |
doc_23528395
|
$var1=array();
$var1['something']['secondary_something'][1]="foo";
$var1['something']['secondary_something'][2]="foo";
$var1['something']['secondary_something'][3]="foo";
$var1['something']['secondary_something'][4]="foo";
Now I have a function, that takes an array for input:
function something($input=array()){
print_r($input);//print the array out
}//end of function
But I need $input to be like a reference to $var1, so when I call the function, appending to variable 2 ($input) like this:
$myInputVar=array();
$myInputVar['something']['secondary_something'][]="foo";
$myInputVar['something']['secondary_something'][]="foo";
//Notice how I append to the var above, not giving a key name in the third dimension of the array.
something($myInputVar);
Now that would simply print:
Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo [1] => foo ) ) )
But I need the second var ($input, from the function) to be a reference of the first var ($var1).
So, the end result should be:
Array ( [something] => Array ( [secondary_something] => Array ( [5] => foo [6] => foo ) ) )
Some guys have told me to use the =& (which makes one var a reference to another), but I just can't seem to get my head around how I would do it with =& in this case.
Is what I'm trying to do even possible? If so, could you please shine some light on it.
A: I am struggling to understand what you are trying to achieve.
Why would you print the array out?
You always need a value and an array if you want to push something into the array.
You can do this with
function something(&$array, $val) { // take the assigned $array as reference
$array[] = $val;
}
Then calling with
$test = array();
something($test, 'foo');
print_r($test); // => array ( 'test' )
I hope this helps
EDIT
function something(&$array, $array_new) {
$array = array_merge($array, $array_new); // to combine/merge both arrays
// please keep in mind that $array is technically $var, because it references to this variable
}
$var1=array();
$var1['something']['secondary_something'][1]="foo";
$var1['something']['secondary_something'][2]="foo";
$var1['something']['secondary_something'][3]="foo";
$var1['something']['secondary_something'][4]="foo";
$myInputVar=array();
$myInputVar['something']['secondary_something'][]="foo";
$myInputVar['something']['secondary_something'][]="foo";
something($var, $myInputVar);
A: You can make the function receive a reference to the array. Like so:
function something(&$arr) {
$arr['something']['secondary_something'][]="something1";
$arr['something']['secondary_something'][]="something2";
}
Now you can do something like the following:
$var1 = array();
$var1['something']['secondary_something'][1]="foo";
$var1['something']['secondary_something'][2]="bar";
$var1['something']['secondary_something'][3]="foobar";
$var1['something']['secondary_something'][4]="barfoo";
something($var1); //this should now append the items to $var1.
print_r($var1); //check to see if calling 'something' really did add the items.
A: Try this:
$var1 = array();
$var2 = array();
assign($var1, $var2, 'foo'); // add an item in both $var1 & $var2
assign($var1, $var2, 'bar'); // append another item it both $var1 & $var2
assign($var1, $var2, 'buz', 5); // add an item in both $var1 & $var2 at index 5
echo print_r($var1, TRUE) . print_r($var2, TRUE);
function assign(&$var1, &$var2, $value, $index=NULL) {
if (is_int($index)) {
$var1['something']['secondary_something'][$index] = $var2['something']['secondary_something'][$index] = $value;
} else {
$var1['something']['secondary_something'][] = $var2['something']['secondary_something'][] = $value;
}
}
which will output:
Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo [1] => bar [5] => buz ) ) ) Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo [1] => bar [5] => buz ) ) )
| |
doc_23528396
|
env=BACKTORY_AUTHENTICATION_MASTER_KEY=058f04d8ea6545sdf65sde99e49
env=BACKTORY_AUTHENTICATION_CLIENT_KEY=5a3ba2f0e4b0a24sdfsd4ffb4
env=BACKTORY_MASTER_ACCESS_TOKEN=my_token
.
.
.
is any way to set this variable automatically ?
and second question is : one time i set this variable manually by this way export variable = value one by one! but now i cant see any of them when i use printenv. is after restarting Ubuntu every environment variable will deleting?
thanks.
| |
doc_23528397
|
I was using code someone else wrote, which worked until a few weeks ago. I am new to this, but even i can see that the code was not very good, so i am trying to rewrite.
First I log into the site and create an tunnel. Then I move to the page where my list is and grab the list, etc.
Here's what's weird. The login fails every time, until I turn on Fiddler. With Fiddler running it succeeds every time.
Any idea about why this would happen and how to fix?
Many thanks.
A: I got it working!
For anyone who finds themselves in the same situation (I've seen a number of posting of similar questions - but the answers hadn't worked for me, so I expect I am not alone), I eventually saw that I needed to set the security protocol to TLS. The specific syntax I used was:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
The setting needs to be specified before the Httpwebrequest get or post event occurs.
If you have a similar problem, I hope this helps.
A: I had an invalid "User-Agent" header. It contained invalid characters (ä, ö, ü).
| |
doc_23528398
|
ID_1 Permit No. ID_2 1 Largest Event 10 Largest Event 2 Largest Event
10220 To Be Permitted 0010001-24.1 4.0548 0.822 3.9611
Why is this happening? It's a minor formatting error, but it can be quite the eyesore.
A: From natsort with reindex
from natsort import natsorted
l=['1 Largest Event','10 Largest Event','2 Largest Event']
natsorted(l)
Out[789]: ['1 Largest Event', '2 Largest Event', '10 Largest Event']
df=df.reindex(columns=natsorted(list(df)))
A: Problem is your columns are sorted like strings in lexicographical order.
So need sorting with custom function by first splitted value converted to ints:
df = df[sorted(df.columns, key=lambda x: int(x.split()[0]))]
Sample:
cols = ['1 Largest Event',
'10 Largest Event',
'2 Largest Event',
'3 Largest Event',
'4 Largest Event',
'5 Largest Event',
'6 Largest Event',
'7 Largest Event',
'8 Largest Event',
'9 Largest Event']
df = pd.DataFrame(0, columns=cols, index=[0])
print (df)
1 Largest Event 10 Largest Event 2 Largest Event 3 Largest Event \
0 0 0 0 0
4 Largest Event 5 Largest Event 6 Largest Event 7 Largest Event \
0 0 0 0 0
8 Largest Event 9 Largest Event
df = df[sorted(df.columns, key=lambda x: int(x.split()[0]))]
print (df)
1 Largest Event 2 Largest Event 3 Largest Event 4 Largest Event \
0 0 0 0 0
5 Largest Event 6 Largest Event 7 Largest Event 8 Largest Event \
0 0 0 0 0
9 Largest Event 10 Largest Event
0 0 0
EDIT:
You can also filter last 3 columns for sorting:
df = df[df.columns[:3].tolist() + sorted(df.columns[3:], key=lambda x: int(x.split()[0]))]
print (df)
ID_1 Permit No. ID_2 1 Largest Event 2 Largest Event \
0 10220 To Be Permitted 0010001-24.1 4.0548 3.9611
10 Largest Event
0 0.822
| |
doc_23528399
|
const sectors = [
{
SectorID: 5,
Name: "Wood Truss/Panel/Building Components"
},
{
SectorID: 33,
Name: "LBM Retail/Pro Contractor"
},
{
SectorID: 24,
Name: "Light Gauge Steel Truss/Panel"
}
];
Then I do have a list of selected checkboxes here,
const selectedSectors = [
{
SectorID: 5
},
{
SectorID: 24
}
];
So here using SectorID, we can find a match.
Expected result: Need to make the selected sector to be checked on load.
Solution I tried:
const [checkedItems, setCheckedItems] = useState({});
React.useEffect(() => {
const newData = sectors.map((sector) => {
return selectedSectors.map((selected) => {
if (selected.SectorId === sector.SectorId) {
setCheckedItems((prev) => {
const checkedItems = {
...prev.checkedItems,
[sector.Name]: true
};
return { ...prev, checkedItems };
});
}
});
});
}, []);
The above one doesn't make the selected sectors checked and I think I am doing something wrong here.
Populating checkboxes like:
{sectors &&
sectors.map((sector, index) => (
<React.Fragment key={index}>
<label className="block mr-4">
<input
className="mx-2 leading-tight"
name={sector.Name}
checked={checkedItems[sector.Name]}
onChange={(e) => handleInputChange(e, sector)}
type="checkbox"
/>
<span className="text-sm">{sector.Name}</span>
</label>
</React.Fragment>
))}
Codesandbox:
Requirement: Please help me to make the checkboxes get checked by default on comparing with selectedSectors..
A: You have no need to create another array with checked items. Just change your input like-
<input className="mx-2 leading-tight"
name={sector.Name}
checked={!!selectedSectors.find(item => item.SectorID === sector.SectorID)}
onChange={(e) => handleInputChange(e, sector)}
type="checkbox" />
A: If you don't need to do anything with the checked state then you should use the defaultChecked attribute and simply search the selectedSectors array for a match.
defaultChecked={selectedSectors.some(
(selectedSector) =>
selectedSector.SectorID === sector.SectorID
)}
If you want to keep your checkedItems state then you can initialize your state in the effect. Iterate over the sectors array and reduce into an object of sector ids to selected values
React.useEffect(() => {
const defaultCheckedSectors = sectors.reduce(
(defaultChecked, sector) => ({
...defaultChecked,
[sector.SectorID]: selectedSectors.some(
(selectedSector) => selectedSector.SectorID === sector.SectorID
)
}),
{}
);
setCheckedItems(defaultCheckedSectors);
}, []);
Update the checked attribute to use the SectorId.
<input
className="mx-2 leading-tight"
name={sector.Name}
checked={checkedItems[sector.SectorID]} // <-- use SectorID
onChange={(e) => handleInputChange(e, sector)}
type="checkbox"
/>
You will need to also update handleInputChange to consume the sector. Alternatively you could also just simply pass the SectorID value.
const handleInputChange = (event, sector) => { // <-- consume sector
const { checked } = event.target;
setCheckedItems(prev => ({
...prev,
[sector.SectorID]: checked // <-- use sector for ID
}))
};
A: This whole approach isn't quite the React way to do it. There should be a single source of truth in state that tracks the sectors' values AND if they're checked. And the initial state for useState should be used to determine the initially checked status.
See this code sandbox I forked from yours to see it rewritten in a more React-y way
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.