_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d15601 | val | Ok this is the answer if you are interested
import pygame
#Initialise pygame
pygame.init()
#Create the screen
screen = pygame.display.set_mode((1200, 700))
screen.set_alpha(None)
#Change the title and the icon
pygame.display.set_caption('The Thoughtful Minds')
icon = pygame.image.load('IA.png')
pygame.display.set_icon(icon)
#Dots
dot = pygame.image.load('point.png')
class Dot:
def __init__(self, pos):
self.cx, self.cy = pos
def draw(self):
screen.blit(dot,(self.cx-8 , self.cy-8))
def text_objects(text,font):
textSurface = font.render(text, True, (100,100,100))
return textSurface, textSurface.get_rect()
dots = []
#Running the window
i = 0
running = True
draging = False
while running:
mx, my = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
pass
elif event.type == pygame.MOUSEBUTTONDOWN:
for oPosition in dots:
if ((oPosition.cx - 8) < mx < (oPosition.cx + 8)) and ((oPosition.cy - 8) < my < (oPosition.cy + 8)):
draging = True
break
if i<3:
# append a new dot at the current mouse position
dots.append(Dot((mx,my)))
i += 1
elif event.type == pygame.MOUSEBUTTONUP:
draging = False
elif event.type == pygame.MOUSEMOTION:
if draging :
oPosition.cx = mx
oPosition.cy = my
# clear the display
screen.fill((30,30,30))
# draw all the dots
if len(dots)>1:
for i in range(len(dots)-1):
pygame.draw.line(screen, (50, 50, 50), [dots[i].cx,dots[i].cy],[dots[i+1].cx,dots[i+1].cy],2 )
for d in dots:
d.draw()
if mx < 50 and my < 50:
pygame.draw.rect(screen,(24,24,24),(0,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(0,0,50,50))
text = pygame.font.Font("freesansbold.ttf",25)
textSurf, textRect = text_objects('–', text)
textRect.center = (25,25)
screen.blit( textSurf, textRect )
if 52 < mx < 102 and my < 50:
pygame.draw.rect(screen,(24,24,24),(52,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(52,0,50,50))
textSurf, textRect = text_objects('+', text)
textRect.center = (76,25)
screen.blit( textSurf, textRect )
# update the dispalay
pygame.display.flip()
A: pygame is low lewel, it does not have any preimplemented method for drag and drop. You have to built it by yourself.
You have to play with the various events types. Here is the idea:
First, create a variable dragged_dot = None outside the main loop. And in the event loop check for the following events:
*
*pygame.MOUSEBUTTONDOWN event tells you when the button is pressed. When you detect this event, check if the mouse is clicking on an existing dot or not. This is what your for loop does. If not, add a new dot like you are already doing. Otherwise, set the dot to be dragged: dragged_dot = oPosition.
*pygame.MOUSEMOTION event tells you when the mouse moves. When you detect this event, check if there is a dragged dot: if dragged_dot is not None. If so, edit it's coordinates adding the mouse motion so that it can be redrawn at a new position (remember to delete the image of the dot at the previous postion). Use event.rel to know the difference between previous mouse position and current mouse position.
*pygame.MOUSEBUTTONUP event tells you when the button is released. Simply set dragged_dot = None, so that the dot is dropped and will not follow the mouse motion anymore. | unknown | |
d15602 | val | Okay - discovered that despite the fact that the PLIST file in the platforms folder is not being overwritten, the use of a PLIST file in the native folder is still effective in working around the issue.
Discovered this when syntax errors entered my file and my build broke, despite the platforms copy of the PLIST still being exactly the same as the original. | unknown | |
d15603 | val | Lets assume that you need all payment information with its invoices and customer details related to that payment.
If you are Looking for the above Response then You can Simply Retrieve Data with Nested Eager Loading
Like
$payments=SalesPayments::with('salesInvoice.customer')->where(Your condition)->get();
In Payments Model
public function SalesInvoice(){
return $this->BelongsTo(Your sales model class)
}
In SalesInvoice Model
public function customer(){
return $this->BelongsTo(Your user model class)
}
A: As you have not defined relationships, we have to go with Query builder, Update your joins as below
$payments = DB::table('sales_payments')
->join('sales_invoices', 'sales_invoices.invoice_id', '=', 'sales_payments.invoice_id')
->join('customers', 'sales_invoices.customer_id', '=', 'customers.customer_id')
->join('payment_options', 'payment_options.paymentoption_id', '=', 'sales_payments.paymentoption_id')
->select('sales_payments.*', 'sales_invoices.*', 'customers.*', 'payment_options.*')
->get();
Then you can add where clause. | unknown | |
d15604 | val | My advise is you're not using REST properly. There is a good answer about how to best structure a ServiceStack REST service. It's a common issue when starting out, I had issues like this too.
Understanding your use case:
In your specific case if we look at /orders/customers/7 this would work better is you think of it this way:
/customers/7/orders
The reason you do it this way:
*
*It resolves your route ambiguity problems
*The context is clear. We can see we are working with Customer 7 without navigating a long url
*We can see 'with customer 7' we want their orders
Think of routing like this:
/orders Everybody's Orders
/orders/1 Order 1 (without being aware of the customer it belongs to)
/customers All Customers
/customers/7 Customer 7's details
/customers/7/orders All Customer 7's orders
/customers/7/orders/3 Customer 7's order number 3
The beauty of doing things like this is operations on data are done consistently. So you want to find all cancelled orders:
/orders/cancelled
You want to cancel a specific order by it's orderId
/orders/4/cancel
You want to list a specific customer's open orders
/customers/6/orders/open
You want to list customer 6's cancelled orders
/customers/6/orders/cancelled
You want to cancel an order for customer 6 that you are viewing
/customers/6/orders/2/cancel
Obviously these are just scenarios, your routes will differ.
Simplifying action handlers:
You will probably want to define your action handlers so they can cope with coming from multiple routes. What I mean is, one action handler would be responsible for Listing Orders
/orders
/customers/6/orders
What I do is this:
[Route("/orders","GET")]
[Route("/customers/{CustomerId}/orders","GET")]
public class ListOrdersRequest : IReturn<List<Order>>
{
public int? CustomerId { get; set; }
}
So you can see the two order listing routes come in. If they use /orders then our customerId won't have a value but the other route will. So in our action handler we can simply test for this:
public List<Order> Get(ListOrdersRequest request)
{
// Use `CustomerId` to narrow down your search scope
if(request.CustomerId.HasValue){
// Find customer specific orders
} else {
// Find all orders
}
return orders;
}
Client-side concerns:
So to address your using 'typed' client concerns. Creating the routes and action handlers using the above method will allow you to do:
client.Get(new ListOrdersRequest { CustomerId = 7 }); // To get customer 7's orders
client.Get(new ListOrdersRequest()); // All orders
Thus giving you 1 clear method for Listing Orders.
Final thoughts:
Obviously it means you will have to rework what you have which will probably be a pain, but it's the best approach, well worth the effort.
I hope this helps you understand the best structure.
Update:
@stefan2410 requested that I address the issue of Kyle's use of an int[] in a route for a GET request:
If you want to use an int[] in a GET request you have to consider changing it during transport in the URL so it can be used RESTfully.
So you could do this:
class OrdersRequest
{
public string Ids { get; set; }
public OrdersRequest(int[] ids)
{
Ids = string.Join(",", Array.ConvertAll(ints, item => item.ToString()));
}
}
client.Get(new OrdersRequest(new [] {1,2,3}));
Creates the route /orders/1,2,3 and matches /orders/{Ids}. The problem with doing this is in order to use the Ids at the server side you have to convert the string "1,2,3" back to an int[].
The better way to deal with an int[] in a request is to use POST. So you can do:
class OrdersRequest
{
public int[] Ids { get; set; }
public OrdersRequest(int[] ids)
{
Ids = ids;
}
}
client.Post(new OrdersRequest(new[] {1,2,3}));
Creates the route /orders and matches the route /orders. | unknown | |
d15605 | val | This is a side effect from using Tk more than once in a program. Basically, "a1" is tied to the "root" window, and when you destroy "root", "a1" will no longer work.
You have a couple options:
*
*Keep the same window open all the time, and swap out the Frames instead.
*Use Toplevel() to make new windows instead of Tk.
Option 1 seems the best for you. Here it is:
from tkinter import *
root=Tk()
root.geometry("500x500")
a1=StringVar(value='hippidy')
ans1=StringVar()
def ans1():
a=a1.get() #not getting it from ques1()
print(repr(a))
def ques1():
global frame
frame.destroy() # destroy old frame
frame = Frame(root) # make a new frame
frame.pack()
question1=Label(frame, text="How many Planets are there in Solar System").grid()
q1r1=Radiobutton(frame, text='op 1', variable=a1, value="correct").grid()
q1r2=Radiobutton(frame, text='op 2', variable=a1, value="incorrect").grid()
sub1=Button(frame, text="Submit", command=ans1).grid()
next1But=Button(frame, text="Next Question", command=ques2).grid()
def ques2():
global frame
frame.destroy() # destroy old frame
frame = Frame(root) # make a new frame
frame.pack()
question2=Label(frame, text="How many Planets are there in Solar System").grid()
next2But=Button(frame, text="Next Question")
frame = Frame(root) # make a new frame
frame.pack()
button=Button(frame,text="Start Test", command=ques1).grid()
root.mainloop()
Also, don't be scared of classes. They are great.
Also, the way you have a widget initialization and layout on the same line is known to cause bugs. Use 2 lines always. So instead of this
button=Button(frame,text="Start Test", command=ques1).grid()
Use this:
button=Button(frame,text="Start Test", command=ques1)
button.grid()
A: You need to use a single instance of Tk. Variables and widgets created in one cannot be accessed from another.
A: Your code has some common mistakes. You are creating a new window on each question. It is not a good idea. You can use Toplevel but I will suggest you to use the root. You can destroy all of your previous widgets and place new ones. When the first question, both radiobuttons are unchecked and return 0 when none is selected. You are creating the buttons in Window1 so you will have to tie it with your var.
from tkinter import *
global root
root=Tk()
root.geometry("500x500")
a1=StringVar(root)
a1.set(0) #unchecking all radiobuttons
ans1=StringVar()
def ans1():
a=a1.get()
print(a)
def ques1():
for widget in root.winfo_children():
widget.destroy() #destroying all widgets
question1=Label(root, text="How many Planets are there in Solar System").grid()
q1r1=Radiobutton(root, text='op 1', variable=a1, value="correct").grid()
q1r2=Radiobutton(root, text='op 2', variable=a1, value="incorrect").grid()
sub1=Button(root, text="Submit", command=ans1).grid()
next1But=Button(root, text="Next Question", command=ques2).grid()
def ques2():
for widget in root.winfo_children():
widget.destroy()
question2=Label(root, text="How many Planets are there in Solar System").grid()
next2But=Button(root, text="Next Question")
button=Button(root,text="Start Test", command=ques1)
button.grid() | unknown | |
d15606 | val | JMF (Java Media Framework) should be able to detect any media, including a webcam.
Potentially through CaptureDeviceManager.getDeviceList();
For "installing JMF on Linux", one way is simply to:
*
*download it.
*Change directories to the install location.
*Run the command
:
% /bin/sh ./jmf-2_1_1e-linux-i586.bin
A: Here is a piece of code I use in a simple Webcam client with JMF:
Format format = new RGBFormat();
MediaLocator cameraLocator = null;
// get device list
Vector deviceList = CaptureDeviceManager.getDeviceList(format);
// if devices available
if(deviceList != null && deviceList.size() > 0) {
// pick first
CaptureDeviceInfo device = (CaptureDeviceInfo) deviceList.get(0);
cameraLocator = device.getLocator();
}
It picks the first available webcam. Of course, after having the webcam you can store the cameraLocator and try to re-open it on the 2nd run. | unknown | |
d15607 | val | The operationId must match the controller function.
Looks like there is a case mismatch in your code:
*
*operationId: addTestconf
*function name: addTestConf
A: This is a CORS related problem
if you try to request the Api using a different url/host than the indicated in .yaml file you'll get this error
so if in your .yaml you have
host: "localhost:8085"
and used 127.0.0.1:8080 you may face this issue. | unknown | |
d15608 | val | LOAD DATA INFILE 'this.csv'
INTO TABLE seed
(col1) SET source = 0;
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';
Have a look into SO answer.
This is the reference
A: Query that ended up working
load data local infile 'this.csv' into table seeds.seed
fields terminated by ',' lines terminated by '\n'
(@col1,@col2) set url=@col2, source='0';
A: it's quite tricky using load data infile. I spent all last week trying to work it out with so many numerous errors. I'll give you my insights.
I can't see your create table statement so I don't know what datatypes you are using.
If you have integer fields then you have to put at least a 0 in each field in your csv file even if it is wrong. you remove it later post import.
If your integer field is a auto_increment like a primary key then you can omit the field alltogether. don't make my mistake and just leave the field there with no values. Delete it completely otherwise your csv will start with a field terminator character and cause no end of issues.
load data infile 'file.csv'
into table mytablename
fields terminated by ','
lines terminated by '\r\n' - ( for windows)
ignore 1 lines (field1, field2, field4 etc.) - you list your fields in your csv there. If you have fields with no data then you can delete them from your csv and omit them from the list here too.
ignore 1 lines - ignores the first line of the csv which contains your field list.
set id=null,
field3=null;
I set my auto_increment id field to null as its not in the csv file and the mysql knows it exists and what to do with it.
Also set field3 to null because that had no values and was deleted from the csv file as an example. | unknown | |
d15609 | val | Assuming the JavaScript in your example is already in the HTML, in your code behind just use
RegisterStartupScript (http://msdn.microsoft.com/en-us/library/bb310408.aspx) to fire the button click:
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
sb.Append("<script>")
sb.Append("$('#opendialog').click();")
sb.Append("</script>")
If (Not ClientScript.IsStartupScriptRegistered("open")) Then
ClientScript.RegisterStartupScript(Me.GetType(), "open", sb.ToString())
End If
Here is a discussion onRegisterStartupScript vs RegisterClientScriptBlock: Difference between RegisterStartupScript and RegisterClientScriptBlock? | unknown | |
d15610 | val | That message will be in the Gauge report under the step it was executed in.
I personally look at the html reports, but I would assume it is in the xml option as well.
If you want something instantaneous you can write to the console where real time messages are output. This also helps if some sort of bug in the code prevents the reports from being written (like an infinite loop that keeps the report from being written at the end of the full execution).
Here is what it would look like. The gray box is the GaugeMessage.
A: Gauge.writeMessage api allows you to push messages to the reports at logical points.
For example, the step implementation below
@Step("Vowels in English language are <vowelString>.")
public void setLanguageVowels(String vowelString) {
Gauge.writeMessage("Setting vowels to " + vowelString);
vowels = new HashSet<>();
for (char ch : vowelString.toCharArray()) {
vowels.add(ch);
}
}
yields this html report: | unknown | |
d15611 | val | Check to see if PHP has been enabled in the Apache httpd.conf file. See here for further details: http://www.devarticles.com/c/a/Apache/Using-Apache-and-PHP-on-Mac-OS-X/
A: Ok.. seems that I found the solution myself. For some weird reason, I have like 4 different localhost default folders. I had to search manually through each folder containing index.html and move test.php there. Eventually, I found an obscure folder somewhere in the /usr/ folder, moved test.php to there, and it worked. Apparently I have like 4 different versions for each .conf file, and each one states a different thing. Only one of them works.
Phew. What a relief. | unknown | |
d15612 | val | Within your routes file, try moving the "match 'posts/...'" line before "resources :posts". | unknown | |
d15613 | val | The theoretical wifi bandwidth is 11 megabits.
*
*One 1280x720 YUV image: 1280*720*1.5 = 1.3824 megabits
*One 24fps stream of these images: 24*1.3824 megabits = 33.18 megabits
So you cannot transmit the native stream of RGB images over WiFi.
That is why in the source code of the Tango Ros Streamer app you will see
constexpr double COLOR_IMAGE_RATE = 8.; // in Hz.
You can either modify the code of this app to decrease the size of the images and increase the COLOR_IMAGE_RATE, either you want the full resolution and you can create an application which saves all the images on the device. | unknown | |
d15614 | val | It's hard to get too specific without actual code and data to look at, but here's a general idea. This example uses the dwsJSON library from DWS, but the basic principles should work with other JSON implementations. It assumes that you have a JSON array made up of JSON objects, each of which contains only valid name/value pairs for your dataset.
procedure JsonToDataset(input: TdwsJSONArray; dataset: TDataset);
var
i, j: integer;
rec: TdwsJSONObject;
begin
for i := 0 to input.ElementCount - 1 do
begin
rec := input.Elements[i] as TdwsJSONObject;
dataset.Append;
for j := 0 to rec.ElementCount - 1 do
dataset[rec.names[j]] := rec.Values[j].value.AsVariant;
dataset.Post;
end;
//at this point, do whatever you do to commit data in this particular dataset type
end;
Proper validation, error handling, etc is left as an exercise to the reader.
A: The following code is more specific to your example. You can make use of JSON functionality used in this code, even though your requirement changes.
In this array of string list contains (key, value) pairs. each string contains one record in the JSON object. You can refer using array index.
procedure ParseJSONObject(jsonObject : TJSONObject);
var
jsonArray : TJSONArray;
jsonArrSize,
jsonListSize : Integer;
iLoopVar,
iInnLoopVar : Integer;
recordList : array of TStringList;
begin
jsonArrSize := jsonObject.Size;
SetLength(recordList, jsonArrSize);
for iLoopVar := 0 to jsonArrSize - 1 do
begin
recordList[iLoopVar] := TStringList.Create;
jsonArray := (jsonObject.Get(iLoopVar)).JsonValue as TJSONArray;
jsonListSize := jsonArray.Size;
for iInnLoopVar := 0 to jsonListSize - 1 do
begin
ParseJSONPair(jsonArray.Get(iInnLoopVar), recordList[iLoopVar]);
end;
end;
end;
procedure ParseJSONPair(ancestor: TJSONAncestor; var list : TStringList);
var
jsonPair : TJSONPair;
jsonValue : TJSONValue;
jsonNumber : TJSONNumber;
keyName : String;
keyvalue : String;
begin
if ancestor is TJSONPair then
begin
jsonPair := TJSONPair(ancestor);
keyName := jsonPair.JsonString.ToString;
if jsonPair.JsonValue is TJSONString then
keyValue := jsonPair.JsonValue.ToString
else if jsonPair.JsonValue is TJSONNumber then
begin
jsonNumber := jsonPair.JsonValue as TJSONNumber;
keyvalue := IntToStr(jsonNumber.AsInt);
end
else if jsonPair.JsonValue is TJSONTrue then
keyvalue := jsonPair.JsonValue.ToString
else if jsonPair.JsonValue is TJSONFalse then
keyvalue := jsonPair.JsonValue.ToString;
end;
list.Values[keyName] := keyvalue;
end; | unknown | |
d15615 | val | i guess thats matlab code (maybe add matlab tag next time). if you look at the colon operator in matlab doc http://de.mathworks.com/help/matlab/ref/colon.html then when used on left side of an assignement it will fill the matrix and keep dimenesions so you need same amount of elements. | unknown | |
d15616 | val | No you can not use the same driver on windows phone (windows 8).
you have to develop the same driver from scratch by following Windows CE and Mobile Driver development for windows phone 7 that might work on windows 8.but ddk is not open for all better ask msdn support for the same. | unknown | |
d15617 | val | You've tagged this question with the ssl tag, and SSL is the answer. Curious.
A: I would choose this simple solution.
Summarizing it:
*
*Client "I want to login"
*Server generates a random number #S and sends it to the Client
*Client
*
*reads username and password typed by the user
*calculates the hash of the password, getting h(pw) (which is what is stored in the DB)
*generates another random number #C
*concatenates h(pw) + #S + #C and calculates its hash, call it h(all)
*sends to the server username, #C and h(all)
*Server
*
*retrieves h(pw)' for the specified username, from the DB
*now it has all the elements to calculate h(all'), like Client did
*if h(all) = h(all') then h(pw) = h(pw)', almost certainly
No one can repeat the request to log in as the specified user. #S adds a variable component to the hash, each time (it's fundamental). #C adds additional noise in it.
A: You can also simply use http authentication with Digest (Here some infos if you use Apache httpd, Apache Tomcat, and here an explanation of digest).
With Java, for interesting informations, take a look at :
*
*Understanding Login Authentication
*HTTP Digest Authentication Request & Response Examples
*HTTP Authentication Woes
*Basic Authentication For JSP Page (it's not digest, but I think it's an interesting source)
A: There are MD5 libraries available for javascript. Keep in mind that this solution will not work if you need to support users who do not have javascript available.
The more common solution is to use HTTPS. With HTTPS, SSL encryption is negotiated between your web server and the client, transparently encrypting all traffic.
A: This sort of protection is normally provided by using HTTPS, so that all communication between the web server and the client is encrypted.
The exact instructions on how to achieve this will depend on your web server.
The Apache documentation has a SSL Configuration HOW-TO guide that may be of some help. (thanks to user G. Qyy for the link)
A: This won't be secure, and it's simple to explain why:
If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.
But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!
Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.
And finally, do you really want to require users to have javascript turned on before they can log into your website?
In any case, SSL is neither an expensive or especially difficult to set up solution any more
A: You need a library that can encrypt your input on client side and transfer it to the server in encrypted form.
You can use following libs:
*
*jCryption. Client-Server asymmetric encryption over Javascript
Update after 3 years (2013):
*
*Stanford Javascript Crypto Library
Update after 4 years (2014):
*
*CryptoJS - Easy to use encryption
*ForgeJS - Pretty much covers it all
*OpenPGP.JS - Put the OpenPGP format everywhere - runs in JS so you can use it in your web apps, mobile apps & etc.
A: I've listed a complete JavaScript for creating an MD5 at the bottom but it's really pointless without a secure connection for several reasons.
If you MD5 the password and store that MD5 in your database then the MD5 is the password. People can tell exactly what's in your database. You've essentially just made the password a longer string but it still isn't secure if that's what you're storing in your database.
If you say, "Well I'll MD5 the MD5" you're missing the point. By looking at the network traffic, or looking in your database, I can spoof your website and send it the MD5. Granted this is a lot harder than just reusing a plain text password but it's still a security hole.
Most of all though you can't salt the hash client side without sending the salt over the 'net unencrypted therefore making the salting pointless. Without a salt or with a known salt I can brute force attack the hash and figure out what the password is.
If you are going to do this kind of thing with unencrypted transmissions you need to use a public key/private key encryption technique. The client encrypts using your public key then you decrypt on your end with your private key then you MD5 the password (using a user unique salt) and store it in your database. Here's a JavaScript GPL public/private key library.
Anyway, here is the JavaScript code to create an MD5 client side (not my code):
/**
*
* MD5 (Message-Digest Algorithm)
* http://www.webtoolkit.info/
*
**/
var MD5 = function (string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function AddUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x,y,z) { return (x & y) | ((~x) & z); }
function G(x,y,z) { return (x & z) | (y & (~z)); }
function H(x,y,z) { return (x ^ y ^ z); }
function I(x,y,z) { return (y ^ (x | (~z))); }
function FF(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function GG(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function HH(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function II(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray=Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
};
function WordToHex(lValue) {
var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
}
return WordToHexValue;
};
function Utf8Encode(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var x=Array();
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
return temp.toLowerCase();
}
A: For a similar situation I used this PKCS #5: Password-Based Cryptography Standard from RSA laboratories. You can avoid storing password, by substituting it with something that can be generated only from the password (in one sentence). There are some JavaScript implementations. | unknown | |
d15618 | val | Here is a demo how it could be achieved with the pure javascript.
var createSublist = function(container, args) {
var ul = document.createElement('ul');
for(var j = 0; j < args.length; j++) {
var row = args[j];
var li = document.createElement('li');
li.innerText = row.text;
var nodes = row.nodes;
if(nodes && nodes.length) {
createSublist(li, nodes);
}
ul.appendChild(li);
}
container.appendChild(ul);
};
var data =[
{
"text":"France",
"nodes":[
{
"text":"Bread"
},
{
"text":"Nocco"
}
],
},
{
"text":"Italy",
"nodes":[
{
"text":"Pizza"
},
{
"text":"Wine",
"nodes": [
{
"text": "Red"
},
{
"text":"White"
}
]
}
]
}
];
var container = document.getElementsByClassName('container')[0];
if(container)
{
createSublist(container, data);
}
else
{
console.log('Container has not been found');
}
<div class="container">
</div>
A: JavaScript ES6 and a small recursive function
/**
* Convert Tree structure to UL>LI and append to Element
* @syntax getTree(treeArray [, TargetElement [, onLICreatedCallback ]])
*
* @param {Array} tree Tree array of nodes
* @param {Element} el HTMLElement to insert into
* @param {function} cb Callback function called on every LI creation
*/
const treeToHTML = (tree, el, cb) => el.append(
tree.reduce((ul, n) => {
const li = document.createElement("li");
if (cb) cb.call(li, n);
if (n.nodes?.length) treeToHTML(n.nodes, li, cb);
ul.append(li);
return ul;
}, document.createElement("ul"))
);
// DEMO TIME:
const myTree = [{
"id": 1,
"parent_id": 0,
"name": "Item1",
"nodes": [{
"id": 2,
"parent_id": 1,
"name": "Item2"
}]
}, {
"id": 4,
"parent_id": 0,
"name": "Item4",
"nodes": [{
"id": 9,
"parent_id": 4,
"name": "Item9"
}, {
"id": 5,
"parent_id": 4,
"name": "Item5",
"nodes": [{
"id": 3,
"parent_id": 5,
"name": "Item3"
}]
}
]
}];
treeToHTML(myTree, document.querySelector("#demo"), function(node) {
this.textContent = `${node.parent_id} ${node.id} ${node.name}`
});
<div id="demo"></div> | unknown | |
d15619 | val | Yes it is possible but you have to create form by giving row and column number because you want to create matrix:
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
echo "<th> E".$tr." </th>";
for($td=1;$td<=$rows;$td++){
echo '<td><input type="number" name="etat_'.$tr.'_'.$td.'" placeholder="nb d etat" /></td>';
}
echo "</tr>";
}
echo "</table>";
echo '<input type="submit" name="submit" value="Create Table">';
echo '</form>';
in f.php fetch data :
if(isset($_POST['submit'])) {
print_r($_POST);
}
It gives you output:
Array
(
[etat_1_1] => 1 //means 1st row 1st column
[etat_1_2] => 2 //means 1st row 2nd column
[etat_1_3] => 3 //means 1st row 3rd column
[etat_2_1] => 4 //means 2nd row 1st column and so on...
[etat_2_2] => 5
[etat_2_3] => 6
[etat_3_1] => 7
[etat_3_2] => 8
[etat_3_3] => 9
[submit] => Create Table
) | unknown | |
d15620 | val | the javascript function date.getMonth() would return 2 for the month March, but you want '03'
so use this:
var mm = date.getMonth()+1;
mm=(mm<=9)?'0'+mm:mm;
A: Your formatting is incorrect so you are actually returning NaN.
Where you are passing 'yyyy mm dd', you should instead be passing the start variable, so:
$.fullCalendar.moment('yyyy mm dd');
should be
$.fullCalendar.moment(start).format('YYYY MM DD');
Additionally, note that your date format needs to be uppercase, per the Moment.js site, and can more simply be written as moment(start).format('YYYY MM DD');
DEMO
$('#fullCal').fullCalendar({
header: {
left: '',
center: 'prev title next today',
right: ''
},
selectable: true,
select: function(start, end, allDay) {
var title = prompt('Evento a insertar:');
if (title) {
start = moment(start).format('YYYY MM DD');
end = moment(end).format('YYYY-MM-DD'); /* w/ dashes if that is what you need */
alert('start: ' + start + ' end: ' + end);
/*rest of your code... */
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.1.1/fullcalendar.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.1.1/fullcalendar.min.js"></script>
<div id="fullCal"></div> | unknown | |
d15621 | val | I was able to retrieve the HTML as a string by doing the following.
driver.findElement(By.id('Profile')).getAttribute("innerHTML").then(function(profile) {
console.log(profile);
});
A: I got the inner HTML with:
element.getAttribute('innerHTML').then(function (html) {
console.log(html)
}) | unknown | |
d15622 | val | With canvas there are 2 'size' settings:
Through CSS you'll set the DISPLAY size, so to set the PHYSICAL size of the canvas, you MUST use its attributes. So NO CSS/Style.
Think about it this way: you create a IMAGE with physical size: (let's say) 400px*400px.
Then just as a normal image (jpg,png,gif) that has a physical size, you can still choose to change the DISPLAYED size and thus aspect-ratio: like 800px*600px. Even % is normally supported.
Hope this explains clearly WHY this happened and why your solution in your comment is also the correct solution!! | unknown | |
d15623 | val | Gob is much more preferred when communicating between Go programs. However, gob is currently supported only in Go and, well, C, so only ever use that when you're sure no program written in any other programming language will try to decode the values.
When it comes to performance, at least on my machine, Gob outperforms JSON by a long shot. Test file (put in a folder on its own under your GOPATH)
$ go test -bench=.
testing: warning: no tests to run
BenchmarkGobEncoding-4 1000000 1172 ns/op
BenchmarkJSONEncoding-4 500000 2322 ns/op
BenchmarkGobDecoding-4 5000000 486 ns/op
BenchmarkJSONDecoding-4 500000 3228 ns/op
PASS
ok testencoding 6.814s
A: Package encoding/gob is basically Go specific and unusable with other languages but it is very efficient (fast and generates small data) and can properly marshal and unmarshal more data structures. Interfacing with other tools is often easier via JSON. | unknown | |
d15624 | val | �
This is usually a sign for an invalid UTF-8 character.
My bet is that your PHP file is ISO-8859-1 encoded. The pound sign has a different code point in ISO-8859-1 than in UTF-8. When data from the PHP file is used in a UTF-8 context, the pound sign becomes invalid.
Save the PHP file with UTF-8 encoding - this can usually be set in the editor's "Save As" dialog.
A: Found the reason. I was using ScriptFTP to batch upload files, Filezilla sorted it out. It mus t have been changing the format or something during upload.
A: I had a similar problem, but in my case was that my php file was encoded in ANSI, I just needed to change the file encoding to UTF-8
remember to do this when you have special characters if he were invalid so remember to edit these characters after changing the file encoding
I have helped you or others xD | unknown | |
d15625 | val | If anyone else has this problem, I fixed it by simply adding this to my link:
:target => "_top"
That makes it loads the auth into the top window.
From here:
https://developers.facebook.com/docs/authentication/canvas/ | unknown | |
d15626 | val | Try :
RedirectMatch ^/ecommerce/cabinets/aluminium_cabinets/?$ http://www.testsite.co.uk/products/cabinets/?types[]=illuminated-aluminium-cabinets&types[]=non-illuminated-aluminium-cabinets | unknown | |
d15627 | val | Hiding and unhiding is not the solution. What you need is just one line:
yourCarousel.clipsToBounds = YES;
A: I actually tried to reproduce your problem and did see that the carousel view stays for a second when 'pop' or back button press happens. This particularly happens when you the carousel is swiped and then the back button pressed. As a workaround, I was able to fix it by setting the iCarousel hidden in the viewWillDisappear method.
- (void)viewWillDisappear:(BOOL)animated
{
[YOUR_CAROUSEL_NAME setHidden:YES]; //This sets the carousel to be hidden when you press Back button
}
If this looks to be hidden suddenly, you can perhaps try setting the alpha to 0.0 inside an animation block. Something like this:
- (void)viewWillDisappear:(BOOL)animated
{
//[YOUR_CAROUSEL_NAME setHidden:YES];
[UIView animateWithDuration:0.2f animations:^{
[YOUR_CAROUSEL_NAME setAlpha:0.0f]; //This makes the carousel hide smoothly
}];
}
Hope this helps! | unknown | |
d15628 | val | From your question,
If you are using Google Map and GeoCoder class that means you must have Internet connection. And moreover when you are working with GPS, again you must have Internet Connection. If you are using GPS_PROVIDER then you required open sky type environment and for NETWORK_PROVIDER you can fetch gps details inside a room,but for both provider Internet is must.
A: You are missing the point of what GPS is designed to do.
Your phone's GPS doesn't do anything with an address. All GPS does is get the latitude/longitude of your current position, nothing more. The phone (via an internet connection) is able to identify your address based on the Latitude/Longitude that the GPS provides by using 3rd party provides (such as Google Maps)
It sounds like you just want to get the latitude/longitude of any address, not just for the device's physical location. That does not require GPS at all. But it needs an internet connection in order to access a provider to perform the geocoding.
A answer I provided to Does GPS require Internet? is a somewhat related to your issue. The 2nd to last paragraphs are pertinent here as well
While it requires a significant amount of effort, you can write your own tool to do the reverse geocoding, but you still need to be able to house the data somewhere as the amount of data required to do this is far more you can store on a phone, which means you still need an internet connection to do it. If you think of tools like Garmin GPS Navigation units, they do store the data locally, so it is possible, but you will need to optimize it for maximum storage and would probably need more than is generally available in a phone.
So effectively, you theoretically could write your own tool, cache data locally and query it as needed, but that not something that is easily done. | unknown | |
d15629 | val | C++/CLI still compiles like C++, file files are compiled separately and then linked together. This is different from C# which compiles all the files together. At compile time the files don't know about each other so the code doesn't compile (what is this enum?!). You need to have the enum definition in the same file (compilation unit) as the class.
The simple way to do this is to move the code into the same file. The header file solution is to move the enum definition into a header file and then include it (#include) in the other file. #include inserts the text of another file, giving the same effect. | unknown | |
d15630 | val | CF7 uses AJAX to submit forms and you can't see var_dump() in ordinary way. So through PHP you can use WordPress debug.log file. Iside "wp-config.php" instead of define('WP_DEBUG', false); write:
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
Then:
add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");
function wpcf7_do_something_else( &$WPCF7_ContactForm ) {
$name = $WPCF7_ContactForm->posted_data['your-name'];
ob_start(); // start buffer capture
var_dump($name);
$contents = ob_get_contents(); // put the buffer into a variable
ob_end_clean(); // end capture
error_log($contents); // write the log file
}
As option you can do that in front-end with JS thru the CF7 DOM events
Example - when your form is submit:
<script>
document.addEventListener( 'wpcf7submit', function( event ) {
var inputs = event.detail.inputs;
for ( var i = 0; i < inputs.length; i++ ) {
if ( 'your-name' == inputs[i].name ) {
alert( inputs[i].value );
/*
or in console:
console.log( inputs[i].value );
*/
break;
}
}
}, false );
</script> | unknown | |
d15631 | val | Assuming that you where following the Discord.NET documentation tutorials in setting up a command service...
You probably have a HandleCommand function, or something equivalent to that. It should contain a line of code that looks like this:
if(!(message.HasStringPrefix("PREFIX", ref argPos))) return;
Which basically means "if this message does not have the prefix at the start, exit the function". (Where message is a SocketUserMessage and argPos is a int, usually 0)
Put your line of code after that, so it would look like this...
//Blah
if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; }
await message.Channel.SendMessageAsync("blah");
//stuff
But, if you want the bot to only reply if the bot doesn't find a suitable command for the current command the user send, you can do this instead:
if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; }
var context = new CommandContext(client, message);
var result = await commands.ExecuteAsync(context, argPos, service);
if(!result.IsSuccess) {
//If Failed to execute command due to unknown command
if(result.Error.Value.Equals(CommandError.UnknownCommand)) {
await message.Channel.SendMessageAsync("blah");
} else {
//blah
}
}
A: It's not possible to implement this as a command. You have to subscribe to the MessageReceived Event of your DiscordSocketClient and simply send a message back to the channel when it fires.
private async Task OnMessageReceived(SocketMessage socketMessage)
{
// We only want messages sent by real users
if (!(socketMessage is SocketUserMessage message))
return;
// This message handler would be called infinitely
if (message.Author.Id == _discordClient.CurrentUser.Id)
return;
await socketMessage.Channel.SendMessageAsync(socketMessage.Content);
} | unknown | |
d15632 | val | The Web Request code works for me in US. Ensure the following:
*
*You're not using Proxy etc.
*You can enter this URL in the browser and see JSON results: http://maps.googleapis.com/maps/api/geocode/json?latlng=27.7121753,85.3434027&sensor=true
*Run Fiddler and see what is your request/response.
*Google MAP API access is allowed in the country you're trying from.
Most probably this looks like a proxy issue, since Google APIs would give back better error messages for country access/excessive requests etc.
Try setting your proxy in the config as follows:
<system.net>
<defaultProxy>
<proxy usesystemdefault = "false" proxyaddress="http://address:port" bypassonlocal="false" />
</defaultProxy>
</system.net> | unknown | |
d15633 | val | Okay, I think I found what the issue was.
If anyone has the same problem, here's how I resolved it:
*
*Set the sprite pivot point to the place you want the middle of the cell to be (in my case, the centre of the grass section)
*Set tile anchor back to (0.5, 0.5)
*Use the GetCellCenterWorld() method normally
The code I've posted in the question works just fine now.
A: [SerializeField] private Tilemap map;
private Camera camera;
[SerializeField] private Transform playerTransform;
void Start(){
camera = Camera.main;
}
// Update is called once per frame
void Update(){
if (Input.GetMouseButtonDown(0)){
var worldPos = camera.ScreenToWorldPoint(Input.mousePosition);
Vector3Int tilemapPos = map.WorldToCell(worldPos);
playerTransform.position = map.CellToWorld(tilemapPos);
Debug.Log(tilemapPos);
}
}
playerTransform.position = map.CellToWorld(clickedCellPosition);
Just convert it back and provide tilemapPos
A: Try tilemap.cellBounds.center
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html | unknown | |
d15634 | val | Other people have the same problem:
https://www.sqlservercentral.com/Forums/Topic1545616-392-1.aspx
There, the solution was to convert the string date to an actual date:
You need to do an explicit CONVERT to use the string literal. I
changed your code a little bit to remove the +1
CREATE TABLE Test( DayDate DATE, DayNumber AS (DATEDIFF( DD,
CONVERT( DATE, '2014-04-30', 120), DayDate)) PERSISTED)
INSERT INTO Test(DayDate) VALUES(GETDATE()) SELECT * FROM Test DROP
TABLE Test
The same answer explains this is because there are date formats that are non-deterministic and therefore you need to explicitly set a (deterministic) date format for the string conversion to be considered deterministic. | unknown | |
d15635 | val | > is to redirect output and overwrite whatever is in the file.
>> is to redirect output and append to the file.
for /F "tokens=*" %%A in (results.txt) do (
echo %%A
) >> imsofrustrated.txt | unknown | |
d15636 | val | No, it is not supported to add issues in Github when check in code at TFS. It could only add workitems in TFS.
If they couldn't see those workitem, you could export those workitems from TFS to Excel and send to them. Or like Daniel said in the comment, you could use VSTS instead of using TFS. | unknown | |
d15637 | val | Use console.log() to inspect your object behavior and view it on your browser's console (F12)
Example:
onSubmit(event: any) {
// debugger
if (!this.patientPastHistoryForm.invalid) {
this.submitted = true;
this.patientPastMedicalHistory = this.patientPastHistoryForm.value;
console.log(this.patientPastMedicalHistory); // check what you send in payload. this.clientsService.createPatientPastHistory(this.patientPastMedicalHistory).subscribe((response: any) => {
//debugger
console.log(response); // check what you got
if (response.statusCode == 200) {
//alert(response.message);
this.notifier.notify('success', response.message);
} else {
this.notifier.notify('error', response.message);
}
});
}
} | unknown | |
d15638 | val | Somehow my previous answer got deleted...
To get user input in Python, assign a variable to the results of the built-in input() function:
user_input = input("Type something: ")
print("You typed: " + user_input)
In Python 2, the raw_input() function is also available, and is preferred over input().
To get the password without it echoing back to the screen, use the getpass module:
import getpass
user_password = getpass.getpass("Enter password: ")
I'm not that familiar with curses, but it would seem that you could position your cursor, then call input() or getpass.getpass(). Just briefly reading over the documentation, there are apparently options to turn screen echoing on and off at will, so those may be better options. Read The Fine Manual :) | unknown | |
d15639 | val | There is something wrong with your Service Pack 1 installation, try to reinstall it with these instructions;
*
*Go to the Windows 7 Service Pack 1 download page on the Microsoft website.
*Select Install Instructions to see which packages are available for download, and make note of the one that you need.
*Select the appropriate language from the drop-down list, and then select Download.
*Select the packages you need to install, select Next, and then follow the instructions to install SP1. Your PC might restart a few times during the installation.
*After SP1 is installed, sign in to your PC. You might see a notification indicating whether the update was successful. If you disabled your antivirus software before the installation, make sure you turn it back on.
More details: https://support.microsoft.com/en-us/help/15090/windows-7-install-service-pack-1-sp1
After this, try to install Python 3.7 normally again. | unknown | |
d15640 | val | First, (almost) never use test$ within a dplyr pipe starting with test %>%. At best it's just a little inefficient; if there are any intermediate steps that re-order, alter, or filter the data, then the results will be either (a) an error, preferred; or (b) silently just wrong. The reason: let's say you do
test %>%
filter(grepl("[wy]", lith)) %>%
mutate(major = str_extract_all(test$lith, ...))
In this case, the filter reduced the data from 4 rows to just 2 rows. However, since you're using test$lith, that's taken from the contents of test before the pipe started, so here test$lith is length-4 where we need it to be length-2.
Alternatively (and preferred),
test %>%
filter(grepl("[wy]", lith)) %>%
mutate(major = str_extract_all(lith, ...))
Here, the str_extract_all(lith, ...) sees only two values, not the original four.
On to the regularly-scheduled answer ...
I'll add a row number rn column as an original row reference (id of sources). This is both functional (for things to work internally) and in case you need to tie it back to the original data somehow. I'm inferring that you group the values together as strings instead of list-columns, though it's easy enough to switch to the latter if desired.
library(dplyr)
library(stringr) # str_extract_all
library(tidyr) # unnest, pivot_wider
test %>%
mutate(
rn = row_number(),
tmp = str_extract_all(lith, "\\b([[:alpha:]]+) ?\\{([^}]+)\\}"),
tmp = lapply(tmp, function(z) strcapture("^([^{}]*) ?\\{(.*)\\}", z, list(categ="", val="")))
) %>%
unnest(tmp) %>%
mutate(across(c(categ, val), trimws)) %>%
group_by(rn, categ) %>%
summarize(val = paste(val, collapse = ", ")) %>%
pivot_wider(rn, names_from = "categ", values_from = "val") %>%
ungroup()
# # A tibble: 4 x 4
# rn incidental major minor
# <int> <chr> <chr> <chr>
# 1 1 dacite rhyolite basalt andesite
# 2 2 NA andesite flows, dacite flows NA
# 3 3 NA andesite dacite
# 4 4 NA basaltic andesitebasalt NA | unknown | |
d15641 | val | As you already seem to have found out yourself, that's possible using the TECH_DISCOVERED intent filter:
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
The problem is your tech-filter XML file. The tech-filter that you specified translates to *match any tag that is IsoDep and NfcA and NfcB and and NfcF and etc. As some of these tag technologies (e.g. Nfc[A|B|F|V]) are mutually exclusive, no tag will ever match this condition.
You can overcome this by specifying a tech-filter that matches all these technologies with logical or:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.IsoDep</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcB</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcF</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcV</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.Ndef</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NdefFormatable</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareClassic</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcBarcode</tech>
</tech-list>
</resources>
Or as you already found that your tag is NfcA, you could also simply match NfcA:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
</tech-list>
</resources>
A: To open your android app on NDEF_DISCOVERED.
You have to set your custom mimeType. By doing so, you are letting the android know that this is your custom tag and this application is well suitable for that tag.
Note: You can not expect your app to open for all the tag types/mime type that you show. As you know, that is user's choice to select his/her preferred app.
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<!-- THIS ONE -->
<data android:mimeType="application/com.myExample.myVeryOwnMimeType" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter> | unknown | |
d15642 | val | Best guess : missing assert for security demands. Check out MSDN tutorial to get started. And SecurityPermission class for Assert method. | unknown | |
d15643 | val | in css file change the background: url("images/shadow1.PNG") to background: url("../images/shadow1.PNG")
It has to return to the root folder (projects) using ../ and then enter the image folder to find the image.
A: Adding on Sotiris answer. The CSS 'locates' files starting from it's own location. This means you have to navigate to the image from the CSS' directory.
For example: your image reside in /trunk/images and the css in /files/css (I wouldn't suggest those folder names) you would have to go back 2 directories into the /trunk/images directory:
.something
{
background: url(../../trunk/images/image.png) 0 0 no-repeat;
} | unknown | |
d15644 | val | Take a look at python's threading basic package and see if it fits you.
https://docs.python.org/3/library/threading.html | unknown | |
d15645 | val | Interestingly, the solution here was that i needed to downgrade my rake version. The local version (in my C:\ruby dir) was overriding the one in the source directory, and couldn't be loaded. I had done gem update and updated all my local gems.
The commands were:
gem uninstall rake
gem install rake -v ('= 1.5.1')
A: I had a problem similar to this, which I ended up working around by hacking my rails version to not initialize active resource (by modifying the components method in /rails/railties/builtin/rails_info/rails/info.rb )
This is clearly a hack, but I didn't have a chance to work out why active_resource specifically was causing the rake conflict, and since I wasn't using active_resource anyway, it got me through the night.
A: rake aborted!
can`'t activate rake
It is mid-Autumn - perhaps too many leaves have fallen and the rake can't be used. Try using the leaf-blower instead.
Next time, keep up with the raking to prevent this. | unknown | |
d15646 | val | If you put commandbar in <Page.BottomAppBar/>, it always changes its position according to current ApplicationViewOrientation, you cannot control it.
But if you put it into a panel(e.g, Grid):
<Page
x:Class="AppCommandBar.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppCommandBar"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="9*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<CommandBar Name="cmdBar_ed" Grid.Row="1" Grid.ColumnSpan="2">
<CommandBar.PrimaryCommands>
<AppBarButton Name="newBtn" Label="test" Width="30">
</AppBarButton>
</CommandBar.PrimaryCommands>
<CommandBar.SecondaryCommands>
<AppBarButton Name="btn_save" Icon="Save" Label="Save"/>
<AppBarButton Name="btn_saveAs" Icon="Save" Label="Save As"/>
<AppBarButton Name="btnClose" Icon="Cancel" Label="Close File"/>
</CommandBar.SecondaryCommands>
</CommandBar>
</Grid>
You could manually set its position by current view's orientation.About how to detect current view's orientation, please check this thread How to detect orientation changes and change layout | unknown | |
d15647 | val | current_account stays nil because neither your if condition nor your elsif condition are true. It means that @current_player and @current_coach are nil (or false) | unknown | |
d15648 | val | Yes, Windows Server 2012 R2 and Windows Server 2016 both support SignalR. Just ensure WebSocket support is enabled and you're all set.
IIS Express is a cut-down version of IIS (which frustratingly does not work with IIS Manager), but internally it uses the same execution engine (including HTTP.sys integration) so it uses the same web.config files as the full-fat IIS too, so it supports SignalR too.
("IIS Express" is a thing because previously VS shipped with a simple web-server called Cassini, which used ASP.NET System.Web.dll for everything, which worked for simple applications but for more complex applications there was sufficient differing behaviour that it made development difficult) | unknown | |
d15649 | val | Negative indexes are calculated using len(l) + i (with l being the object and i being the negative index).
For example, with a list x = [1, 2, 3, 4] the index -2 is calculated as 4-2 = 2, so x[-2] returns 3
In this example, the index -1 is calculated as index 2
Therefore, 19 is inserted at index 2, the penultimate position. To fix this, use Z = np.insert(Y, len(Y), 19).
PS - this is the same with list.insert, not just with numpy arrays
Edit (suggested by Homer512): np.append may be easier than np.insert if you want to add to the end of an array: Z = np.append(Y, 19) | unknown | |
d15650 | val | This problem by hosting provider not allowing outbound connections on port 9243. (Smarterasp.net) They answered to me : "upgrade your hosting account to our .net premium plan, so you can enable spacial port to the remote server." | unknown | |
d15651 | val | If you are using Java 5 or later you are better off using ProcessBuilder rather than Runtime.exec. See here for more information. | unknown | |
d15652 | val | You will need the .forkJoin operator for that
Observable.forkJoin([observable1,observable2])
.subscribe((response) => {
console.log(response[0], response[1]);
});
You can import the Observable with;
import {Observable} from 'rxjs/Rx';
A: Angular < 6:
import {Observable} from 'rxjs/Observable';
...
return Observable.forkJoin(
this.http.get('someurl'),
this.http.get('someotherurl'));
Angular >= 6:
import {forkJoin} from 'rxjs';
...
return forkJoin(
this.http.get('someurl'),
this.http.get('someotherurl')); | unknown | |
d15653 | val | Alternative solution:
P/Invoke to the DnsQuery function and pass DNS_TYPE_SRV.
An example can be found in this excellent post by Ruslan. I reproduce the code below in case the link breaks, but emphasize it is taken directly from his blog.
public class nDnsQuery
{
public nDnsQuery()
{
}
[DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved);
[DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)]
private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType);
public static string[] GetSRVRecords(string needle)
{
IntPtr ptr1 = IntPtr.Zero;
IntPtr ptr2 = IntPtr.Zero;
SRVRecord recSRV;
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
throw new NotSupportedException();
}
ArrayList list1 = new ArrayList();
try
{
int num1 = nDnsQuery.DnsQuery(ref needle, QueryTypes.DNS_TYPE_SRV, QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0);
if (num1 != 0)
{
if (num1 == 9003)
{
list1.Add("DNS record does not exist");
}
else
{
throw new Win32Exception(num1);
}
}
for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recSRV.pNext)
{
recSRV = (SRVRecord)Marshal.PtrToStructure(ptr2, typeof(SRVRecord));
if (recSRV.wType == (short)QueryTypes.DNS_TYPE_SRV)
{
string text1 = Marshal.PtrToStringAuto(recSRV.pNameTarget);
text1 += ":" + recSRV.wPort;
list1.Add(text1);
}
}
}
finally
{
nDnsQuery.DnsRecordListFree(ptr1, 0);
}
return (string[])list1.ToArray(typeof(string));
}
private enum QueryOptions
{
DNS_QUERY_ACCEPT_TRUNCATED_RESPONSE = 1,
DNS_QUERY_BYPASS_CACHE = 8,
DNS_QUERY_DONT_RESET_TTL_VALUES = 0x100000,
DNS_QUERY_NO_HOSTS_FILE = 0x40,
DNS_QUERY_NO_LOCAL_NAME = 0x20,
DNS_QUERY_NO_NETBT = 0x80,
DNS_QUERY_NO_RECURSION = 4,
DNS_QUERY_NO_WIRE_QUERY = 0x10,
DNS_QUERY_RESERVED = -16777216,
DNS_QUERY_RETURN_MESSAGE = 0x200,
DNS_QUERY_STANDARD = 0,
DNS_QUERY_TREAT_AS_FQDN = 0x1000,
DNS_QUERY_USE_TCP_ONLY = 2,
DNS_QUERY_WIRE_ONLY = 0x100
}
private enum QueryTypes
{
DNS_TYPE_A = 0x0001,
DNS_TYPE_MX = 0x000f,
DNS_TYPE_SRV = 0x0021
}
[StructLayout(LayoutKind.Sequential)]
private struct SRVRecord
{
public IntPtr pNext;
public string pName;
public short wType;
public short wDataLength;
public int flags;
public int dwTtl;
public int dwReserved;
public IntPtr pNameTarget;
public short wPriority;
public short wWeight;
public short wPort;
public short Pad;
}
}
A: Open source, BSD licensed library here: http://dndns.codeplex.com/
A: This looks like another great candidate and is Apache 2.0 licensed. Latest build was Thu Dec 17, 2015 at 3:00 AM | unknown | |
d15654 | val | They removed some features in the routing for 1.3:
*
*"First path segments using full regular expressions was removed."
*"Next mid-route greedy star support has been removed."
From migration guide:
http://book.cakephp.org/view/1561/Migrating-from-CakePHP-1-2-to-1-3#Library-Classes-1565
See also 1.3 API:
http://api13.cakephp.org/class/router#method-Routerconnect | unknown | |
d15655 | val | The reason for you error, is that this code calls the Point default constructor (which doesn't exist)
Line(const Point& p1, const Point& p2) {
this->point1 = p1;
this->point2 = p2;
}
instead you should write it like this
Line(const Point& p1, const Point& p2) : point1(p1), point2(p2) {
}
Your version calls the Point default constructor and then assigns the point values. My version initialises the points by calling the Point copy constructor
A: The error message says "no default constructor", so you should add ones.
class Line {
public:
Line() {} // add this
Line(const Point& p1, const Point& p2) {
class Point {
public:
Point() {} // add this
Point(double a, double b) {
or ones with initialization (safer):
class Line {
public:
Line() : point1(), point2() {} // add this
Line(const Point& p1, const Point& p2) {
class Point {
public:
Point() : x(0), y(0) {} // add this
Point(double a, double b) {
or constructors with default arguments:
A: The core reason you are getting that error. Is because Line constructor doesn't know how to initialize point1 and point2 prior to your assignment statements in the constructor. That's what constructor initialization lists are for. It's usually better to do initial member initialization in the constructor initialization list instead of in the constructor body. Without a constructor initialization list, point1 and point2 get constructed with the default constructor (error because it's missing) and then immediate updated with additional code in constructor body. You can avoid the need for a default constructor on Point by having Line constructor defined as follows:
Line(const Point& p1, const Point& p2) : point1(p1), point2(p2)
{}
That will resolve your compiler error. Further, it's still not a bad idea to have a default constructor for Point. It's the type of class where it's often useful to have such a constructor. And some point later, you might need to have a collection of Point instances and the compiler will complain again without it. MakeCAT's answer is correct in that regards.
Aside: Your Distance function is passing Point parameters by value. This means the compiler needs to construct 3 new instances of Point each time Distance is invoked. Change your function signature for Distance as follows. If this doesn't make the compiler happy, it will at the very least, generate more efficient code.
static double Distance(const Point& p1, const& Point p2, const& Point p3) {
double distance = (abs((p1.y - p2.y) * p3.x - (p2.x - p1.x) * p3.y + p2.x * p1.y - p2.x * p1.x) / (sqrt(pow((p2.y - p1.y), 2.0) + pow((p2.x - p1.x), 2.0))));
return distance;
}
A: The problem is that you don't have a default constructor for that class and therefore when you create the points you don't know what values their variables will take.
The easiest and fastest way of solutions is to give default values to the constructor when it does not receive parameters
class Point {
public:
//only modification here
Point(double a = 0, double b = 0) {
this->setCoord(a, b);
}
double x;
double y;
void setCoord(double a, double b)
{
this->x = a;
this->y = b;
}
};
A: The default constructor is the constructor without parameters. If you have a user provided constructor taking parameters (like your Line constructor taking two Points) then you don't automatically get the default constructor, you need to add it yourself.
I suggest changing your classes
*
*to use in-class initializers
*to use member initialization instead of setting in the constructor body
*defaulting the default constructor (which requires step 1)
You can compare the IsoCppCoreguidelines for a more detailed explanation on these changes.
class Point {
public:
Point() = default;
Point(double a, double b) : x{a}, y{b} {}
double x{};
double y{};
};
class Line {
public:
Line() = default;
Line(const Point& p1, const Point& p2) : point1{p1}, point2{p2} {}
Point point1{};
Point point2{};
}; | unknown | |
d15656 | val | Even more simple, you can use precisely the same selector in jQuery as you could in CSS:
$('.element1, .element2').css('font-weight', 'bold);
A: The simple answer is yes, you can do that. But group your selectors using CSS syntax.
$('.element1, .element2, .element3').css('font-weight', 'bold');
A: $('.element1, .element2, etc').css('font-weight', 'bold');
JQuery multiple selectors.
A: Yes you can!
Except you want it like this: $('.element1,.element2').css('font-weight', 'bold);
Source: http://api.jquery.com/multiple-selector/
A: Use multiple selectors. Example:
$("div,span,p.myClass").css("border","3px solid red"); | unknown | |
d15657 | val | try something like:
json.events @fake_objects do |json, event|
json.extract! event, :id, :title, :description
json.start event.start_time
json.end event.end_time
json.url event_url(event, format: :html)
end
but @fake_objects should be defined as [], for single event you could write:
json.event do |json|
json.extract! @fake_object, :id, :title, :description
json.start @fake_object.start_time
json.end @fake_object.end_time
json.url event_url(@fake_object, format: :html)
end
If you need just array of results (without events: []) write json.array! .. | unknown | |
d15658 | val | what about this
for( var i = 1;i<=60;i++)
{
if(i == 30){
alert("value is:"+i);
}
}
A: both answers are count from 0 to 59.
Op want to count from 1 to 60
So,
for(i=1; i<=60;i++)
if(i==30) alert(i);
i=1;
while(i<=60){
if(i==30) alert(30);
i++;
}
A: // using for loop
for (i = 0; i < 60; i++) {
if (i === 30) {
alert('reached 30');
}
}
// using while loop
var c=0
while (c < 60) {
if (c === 30) {
alert('reached 30');
}
c++;
} | unknown | |
d15659 | val | Ext.layout.FitLayout ( which is what layout: 'fit' stands for) is for situations when you anly have one item in a container, because it tries to 'fit' this one component to the full size of the container.
From manual:
This is a base class for layouts that contain a single item that automatically expands to fill the layout's container.
If you have more than one item in container use different layout like Ext.layout.ContainerLayout (default one), Ext.layout.VBoxLayout or perhaps Ext.layout.TableLayout.
A: found the answer, the problem was here:
baseCls:'x-plain', | unknown | |
d15660 | val | You haven't really given us the information about the users and how they relate, so I will guess...
Try something like...
return Response()->json($post->load('user'));
A: Try something like that:
return Response()->json(['post' => $post, 'userdata' => $userdata]); | unknown | |
d15661 | val | I solved this. The Widget component was not being unmounted properly. I have to remove it forcefully form dom using
Mozilla docs removeChild
After that it works fine. | unknown | |
d15662 | val | Here how to save the model:
model_json = model.to_json()
with open("<path.json>", "w") as json_file:
json_file.write(model_json)
model.save_weights("<path.hdf5>", overwrite=True)
If you want to save the model and weights at every epoch, try searching for callbacks.
A: before saving the model, you need to train it using classifier2.fit()
https://keras.io/models/sequential/#fit
to save the model use classifier2.save('filename.hdf5') | unknown | |
d15663 | val | Try this:
*javascript; open_hisr_w_user.js*
/**
* This script is used to spawn a python process that generates a histogram for the specified username.
*
* @param {string} username - The username for which the histogram is being generated.
*
* @returns {ChildProcess} - The spawned python process.
*/
const spawn = require('child_process').spawn;
const username = 'some_username';
const pythonProcess = spawn('python', ['./create_histogram.py', username], {
detached: true,
stdio: ['ignore']
});
pythonProcess.unref(); | unknown | |
d15664 | val | By using merge_asof
pd.merge_asof(df1,df2,left_on='rank_one',right_on='rank_two',direction='forward')
Out[1206]:
country capital rank_one rank_two population
0 Germany Berlin 1 1 82M
1 France Paris 5 6 66M
2 Indonesia Jakarta 7 9 255M
A: You can use the pandas 'merge_asof' function
pd.merge_asof(df1, df2, left_on="rank_one", right_on="rank_two", direction='forward')
alternatively if you want to merge by closest and you don't mind if it's higher or lower you can use:
direction="nearest" | unknown | |
d15665 | val | This works for me in word 2010, definitely try hitting ignore.
A: Doesn't clicking Ignore do what you want? | unknown | |
d15666 | val | rename does not support a path for the destination (just the new filename):
rename "%userprofile%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs" "trusted.certs.old" | unknown | |
d15667 | val | Yes you could do like that. But, that will limit the capabilities of one address being shared with multiplie entities such as contacts, employees and so on (unless duplicating the record). However, if one address record never shares with multiple entities you can go ahead and do that.
How about having third table which holds the mapping between address and employees, contacts and so on? Let's say a new table called entity_address, the structure would look like this,
*
*id
*entity_id
*entity_name
*address_id (foreign key to id column of address table)
I personally prefer this approach, instead of having the address table to have entity_id and entity_name due to the reason I mentioned in the first paragraph.
Having said that, someone else, might have a different approach.
Anyway, happy to help you :)
A: You can think your relation to the other side.
An account can have many addresses. A contact can have many addresses. An employee can have many addresses.
This is a Many-To-Many Unidirectionnal relation.
You can build the relation in the target entity, rather than in the address one.
class Accounts
{
// ...
/*
* @ORM\ManyToMany(targetEntity="Address")
* @ORM\JoinTable
* (
* name="accounts_addresses",
* joinColumns=
* {
* @ORM\JoinColumn(name="account_id", referencedColumnName="id")
* },
* inverseJoinColumns=
* {
* @ORM\JoinColumn(name="address_id", referencedColumnName="id", unique=true)
* }
* )
*/
private $addresses;
// ...
}
// And so on for the others entities
This will build an relationship table in your database with a unique constraint on the address_id foreign key.
For more informations, take a look at this | unknown | |
d15668 | val | You can pass back and forth a running row count variable to the subreport using parameters and return variables.
You'd need something like this:
(in the master report)
<!-- variable that stores the running row count in the master report -->
<variable name="SubreportRowCount" class="java.lang.Integer" calculation="System">
<initialValueExpression>0</initialValueExpression>
</variable>
...
<subreport>
...
<!-- pass the current value to the subreport -->
<subreportParameter name="InitialRowCount">
<subreportParameterExpression>$V{SubreportRowCount}</subreportParameterExpression>
</subreportParameter>
...
<!-- get back the updated value from the subreport -->
<returnValue subreportVariable="RunningRowCount" toVariable="SubreportRowCount"/>
...
</subreport>
(in the subreport)
<!-- parameter that receives the initial value from the master -->
<parameter name="InitialRowCount" class="java.lang.Integer"/>
...
<!-- running row count variable -->
<variable name="RunningRowCount" class="java.lang.Integer">
<variableExpression>$P{InitialRowCount} + $V{REPORT_COUNT}</variableExpression>
</variable>
...
<!-- show the running count in a text element -->
<textField>
...
<textFieldExpression>$V{RunningRowCount}</textFieldExpression>
</textField> | unknown | |
d15669 | val | The normal way to implement Herb's advice is as follows:
struct A {
A& operator+=(cosnt A& rhs)
{
...
return *this;
}
friend A operator+(A lhs, cosnt A& rhs)
{
return lhs += rhs;
}
};
Extending this to CRTP:
template <typename Derived>
struct Base
{
Derived& operator+=(const Derived& other)
{
//....
return *self();
}
friend Derived operator+(Derived left, const Derived& other)
{
return left += other;
}
private:
Derived* self() {return static_cast<Derived*>(this);}
};
If you try to avoid the use of friend here, you realize it's almost this:
template<class T>
T operator+(T left, const T& right)
{return left += right;}
But is only valid for things derived from Base<T>, which is tricky and ugly to do.
template<class T, class valid=typename std::enable_if<std::is_base_of<Base<T>,T>::value,T>::type>
T operator+(T left, const T& right)
{return left+=right;}
Additionally, if it's a friend internal to the class, then it's not technically in the global namespace. So if someone writes an invalid a+b where neither is a Base, then your overload won't contribute to the 1000 line error message. The free type-trait version does.
As for why that signature: Values for mutable, const& for immutable. && is really only for move constructors and a few other special cases.
T operator+(T&&, T) //left side can't bind to lvalues, unnecessary copy of right hand side ALWAYS
T operator+(T&&, T&&) //neither left nor right can bind to lvalues
T operator+(T&&, const T&) //left side can't bind to lvalues
T operator+(const T&, T) //unnecessary copies of left sometimes and right ALWAYS
T operator+(const T&, T&&) //unnecessary copy of left sometimes and right cant bind to rvalues
T operator+(const T&, const T&) //unnecessary copy of left sometimes
T operator+(T, T) //unnecessary copy of right hand side ALWAYS
T operator+(T, T&&) //right side cant bind to lvalues
T operator+(T, const T&) //good
//when implemented as a member, it acts as if the lhs is of type `T`.
If moves are much faster than copies, and you're dealing with a commutative operator, you may be justified in overloading these four. However, it only applies to commutative operators (where A?B==B?A, so + and *, but not -, /, or %). For non-commutative operators, there's no reason to not use the single overload above.
T operator+(T&& lhs , const T& rhs) {return lhs+=rhs;}
T operator+(T&& lhs , T&& rhs) {return lhs+=rhs;} //no purpose except resolving ambiguity
T operator+(const T& lhs , const T& rhs) {return T(lhs)+=rhs;} //no purpose except resolving ambiguity
T operator+(const T& lhs, T&& rhs) {return rhs+=lhs;} //THIS ONE GIVES THE PERFORMANCE BOOST | unknown | |
d15670 | val | I think the "path" attribute should be "TestHandler.ashx" instead of its current value. It must match the URL you use in jQuery. Otherwise, 404 is expected.
A: 404 usually means a problem with the registration, basically it just can't find something to handle the request that came in.
Inside of the add node, try adding the following attribute at the end: resourceType="Unspecified"
That tells IIS not to look for a physical file when it sees the request for the ashx. I think that's causing the 404 | unknown | |
d15671 | val | Consolidate does not contain any template engine. You should install them on your level.
I guess you are using hogan templates, so you need to install it. Run this in your project root
npm install hogan.js --save | unknown | |
d15672 | val | The structure you have now is perfectly fine and valid. Therefore, you would not want to use product__preview__img. You would be defeating the purpose of BEM if you were to create those kind of selectors as you would be creating complex/unorganised code. If you feel the name is vague, you could try product__img-preview as this still ties in with the block element selector and not a stacked block element selector.
One more thing I could suggest since you are using BEM and to utilise it fully, is to change your modifier class names for the buttons you have to product__btn product__btn--orange as it will help keep your code maintainable as you have the block element selector along side a modifier which is the orange button in this case.
.product {
...
&__features {
...
}
&__btn {
...
&--orange {
...
}
}
}
As you can see, the deepest nesting level is the modifiers of the block element. | unknown | |
d15673 | val | You might want to use the join command to join column 2 of the first file with column 1 of the second:
join --nocheck-order -1 2 -2 1 file1.tsv file2.tsv
A few notes
*
*This is the first step, after this, you still have the task of cutting out unwanted columns, or rearrange them. I suggest to look into the cut command, or use awk this time.
*The join command expects the text on both files are in the same order (alphabetical or otherwise)
*Alternatively, import them into a temporary sqlite3 database and perform a join there. | unknown | |
d15674 | val | Best approach for this layout would be the Flexbox Technique
You can wrap the rows in the reverse order using wrap-reverse
$(document).ready(function() {
$('.create').on('click', function() {
$('.container').append('<div class="circle"></div>');
})
});
.container {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
background: #6CC4DA;
-webkit-flex-wrap: wrap-reverse;
-ms-flex-wrap: wrap-reverse;
flex-wrap: wrap-reverse;
align-items: baseline;
align-content: flex-start;
height: 280px;
width: 770px;
}
.circle {
background: #C78DEF;
border-radius: 50%;
width: 60px;
height: 60px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
</div>
<button class="create">Create a circle</button>
JSfiddle
A: You can flip horizontal parent div and flip horizontal back each child block:
$(document).ready(function() {
$(document).on('click', 'button', function() {
var
items = $('.content-item').size(),
space = document.createTextNode(' ');
$('.container').append($('<div class="content-item">' + (items + 1) + '</div>')).append(space);
});
});
.container {
width: 400px;
height: 200px;
background: cyan;
transform: ScaleY(-1);
}
.content-item {
display: inline-block;
width: 50px;
height: 50px;
border-radius: 50%;
margin: 5px;
text-align: center;
line-height: 50px;
background: purple;
color: #fff;
transform: ScaleY(-1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Increase population</button>
<div class="container">
<div class="content-item">1</div>
<div class="content-item">2</div>
<div class="content-item">3</div>
<div class="content-item">4</div>
<div class="content-item">5</div>
<div class="content-item">6</div>
<div class="content-item">7</div>
</div> | unknown | |
d15675 | val | I had a similar issue and I solved it by adding this parameter in my Databricks cluster :
spark.hadoop.hive.server2.enable.doAs false
See : https://docs.databricks.com/user-guide/faq/access-blobstore-odbc.html
RB | unknown | |
d15676 | val | .getbbox() returns a tuple of the left, right, upper, and lower coordinates. This is what is returned to the logo variable.
If you want to remove transparent portions of the image, use the following code:
logo = Image.fromarray(np.uint8(img)).convert('RGBA')
logo = logo.crop(logo.getbbox()) | unknown | |
d15677 | val | Entity beans do not (in general) support injection of any kind because they are not created by the container.
This general topic was recently discussed on the JSR-338 (JPA 2.1) mailing list and reasons were given why it is generally considered a bad idea for entities to reference entity managers. | unknown | |
d15678 | val | You need to calculate your sizes depending on the phone size - if two cell's width are larger then screen size ( including all offsets between them ) they will layout as in the first picture.
You have two options:
One is to deal with sizes and rescale cells according to device size
Two leave it as is - Make small changes for iphone6/6s/7.
If you opt out for first one, you will need to set up constraint for these sizes - aspect ratio or center horizontally ( which could crop the image a little ).
For changing sizes dynamically, take a look at:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout
More specific:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview
A:
You need to calculate the cell width.Try this code.
class YourClass: UIViewController {
//MARK:-Outlets
@IBOutlet weak var yourCollectionView: UICollectionView!
//Mark:-Variables
var cellWidth:CGFloat = 0
var cellHeight:CGFloat = 0
var spacing:CGFloat = 12
var numberOfColumn:CGFloat = 2
//MARK:-LifeCycle
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourCollectionView.contentInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
if let flowLayout = yourCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
cellWidth = (yourCollectionView.frame.width - (numberOfColumn + 1)*spacing)/numberOfColumn
cellHeight = cellWidth //yourCellHeight = cellWidth if u want square cell
flowLayout.minimumLineSpacing = spacing
flowLayout.minimumInteritemSpacing = spacing
}
}
extension YourClass:UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: cellWidth, height: cellHeight)
}
} | unknown | |
d15679 | val | Google has just today announced to make CalDAV and CardDAV available for everyone. Google's CardDAV Documentation (also just released today) is probably a good place to start. | unknown | |
d15680 | val | After searching I found the solution:
setRequestHeader "Authorization", "Bearer " + accessToken | unknown | |
d15681 | val | Your preference initializer code won't get called until those default values are needed (rather than on application startup, which I'm guessing was your expectation).
If you have yourself a preference page that contains some FieldEditors using your preference names, your preference initializer will get called when you go to the Preferences dialog and select that preference page.
Something along the lines of:
public class MyPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
public void createFieldEditors() {
Composite parent = getFieldEditorParent();
addField(new StringFieldEditor(Constants.PREFERENCES.FILE_COMPARE_TOOL_LOCATION, "File compare tool location", parent));
addField(new StringFieldEditor("xyz", "XYZ Value", parent));
addField(new BooleanFieldEditor("abc", "Enable the ABC widget", parent));
}
}
And of course, an extension point for the page:
<extension point="org.eclipse.ui.preferencePages">
<page
class="whatever.package.MyPreferencePage"
id="whatever.package.MyPreferencePage"
name="MyPrefs">
</page>
</extension> | unknown | |
d15682 | val | My 2 cents,
If you have 16 nodes, they should be in range [0;15] but in your PickupAndDelivery array we can see a 16...
EDIT: seems you have 17 nodes (with the depot) | unknown | |
d15683 | val | You can only include one analysis options file.
Plus package:pedantic/analysis_options.yaml and package:flutter/analysis_options_user.yaml
enforce different rules.
Example:
*
*Pedantic does not use empty_statements
*analysis_options_user.yaml uses it | unknown | |
d15684 | val | You can make a controller action somewhere that is dedicated to file downloads.
So, the link_to goes to that action, which somehow knows which file the user wants (either by dropping the entire url into a query variable or some other method appropriate to your application).
That action does a redirect_to http://website-where-file-is-stored.com/file-123456.mp3
When most modern browsers encounter such a situation, they won't render a blank page and start a download -- they will start the download, but then keep the user on the original page with the link_to. Perfect!
To have the file download as an attachment and not render in the browser (if it's a movie or pdf for example), website-where-file-is-stored.com has to serve the file with the header Content-disposition: attachment. See more info here: http://www.boutell.com/newfaq/creating/forcedownload.html
A: OK, I fixed this by adding the following cgi script to the cgi-bin on my remote server. the script sets the Content-Disposition header. In my case, the script is named "download.cgi".
#!/usr/local/bin/perl -wT
use CGI ':standard';
use CGI::Carp qw(fatalsToBrowser);
my $files_location;
my $ID;
my @fileholder;
$files_location = "../";
$ID = param('ID');
open(DLFILE, "<$files_location/$ID") || Error('open', 'file');
@fileholder = <DLFILE>;
close (DLFILE) || Error ('close', 'file');
print "Content-Type:application/x-download\n";
print "Content-Disposition:attachment;filename=$ID\n\n";
print @fileholder
And instead of doing link_to 'Download', "http://path/to/filename.mp3" I do this:
link_to 'Download' "http://path/to/cgi-bin/download.cgi?ID=filename.mp3"
If you want to use the same script, just bear in mind that the line: $files_location = "../" is a relative path. | unknown | |
d15685 | val | Use vim to test the regex. By typing / in vim you can search for stuff and the search uses regex.
For help on syntax have a look on vimregex
A: We can access Vim's registers in Ex mode or in searching mode by pressing Ctrl+R and then the register you want to paste.
In your situation we can use this to copy the text we want to test and then paste this in our search.
yi"/Ctrl+R0CR
Explanation:
yi" -> Yank inside of double quotes "
/ - > Open the search field
Ctrl+R0 -> paste the last yanked text
A: Do this in Vim. For syntax files, you often deal with start="^begin" stuff. Yank the regexp via yi", then highlight it via:
:let @/ = @"
Of course, if you need this often, bind this to a mapping (and :set hlsearch), like:
:nnoremap <F5> yi":let @/ = @"<CR>
A: Ideal solution:
https://github.com/bennypowers/nvim-regexplainer
But it seems that it only work on javascript regex, not vim's, so far.
Nice website (but no vim's regex engine)
Convert magic to very magic (to avoid backslashits):
https://github.com/sisrfeng/VimRegexConverter
Split to pieces of strings by hand:
if file_name =~# '\v^(' .. '[\%#~]' .. '|' .. '\.?[/\\]\a+:' .. '|' .. '^\d+' .. ')$'
vs
if file_name =~# '^\.\=[\\/]\|^\a\+:\|^[%#~]\|^\d\+$'
A: You can also try RegExr
It's a good tool to learn RegEx and try them in real time. | unknown | |
d15686 | val | Why not use ClickOnce, and it will do all that for you.
A: You may want to check out this Episode of Hanselminutes
http://www.hanselman.com/blog/HanselminutesPodcast138PaintNETWithRickBrewster.aspx
He talks with the creator of Paint.NET who ends up doing some pretty creative things with the installer. | unknown | |
d15687 | val | Create Procfile in main folder and add:
web: node src/<you-app-name>.js
Check the below image for where to put Procfile:
A: Create a Procfile with following content
web: node src/server.js
The Procfile is always a simple text file that is named Procfile exactly. For example, Procfile.txt is not valid.
The Procfile must live in your app’s root directory. It does not function if placed anywhere else.
Heroku app dynos executes the commands of Procfile
Read more about Procfile here https://devcenter.heroku.com/articles/procfile | unknown | |
d15688 | val | So, whenever user press homebutton can i save all these instances &
use it once user resume?.
The "instances" aren't removed when you press home. They are removed when the app is in the background and Android needs more memory some time later (might never happen).
Is it safe to store the activity references in savedinstancestate
Yes this is what saved instance state was made for:
As your activity begins to stop, the system calls
onSaveInstanceState() so your activity can save state information with
a collection of key-value pairs. The default implementation of this
method saves information about the state of the activity's view
hierarchy, such as the text in an EditText widget or the scroll
position of a ListView.
.
can i save all these instances?
You can't save the instances - you will have to store the information that you will use to re-build your activity as key-value pairs. What I do is I store just enough information so that the activity can rebuild itself.
For example, if the Activity has a list that was constructed from api.myapp.com, I will save this URL, as well as the scroll location of the list. The rest you should probably go retrieve again as if you had just launched the app for the first time - this will make your code much simpler. | unknown | |
d15689 | val | This is an error code that's specific to the component. If you don't have documentation that explains what the code might mean then you'll need support from the vendor.
A: As noted in my comment to Hans' answer, this error code is FACILITY_CONTROL, which is supposed to relate to OLE/ActiveX controls, and has an error code which lies in the standard range (i.e. for Microsoft use) defined in OleCtl.h, but is not documented in the Win32 header files so is probably internal to a Microsoft product such as Visual Basic.
Can you tell us anything else about the COM component you are trying to use?
If the COM component was written using Visual Basic, I think it's probable that what you are seeing is equivalent to the Runtime Error 339 which users of Visual Basic see if they try to reference an OCX control which has some of its dependencies missing. You might look at the dependencies of the COM server's DLL/EXE using Depends.exe and see whether you have them all present on your machine.
A: Back when I had to do a lot of COM work, I used COM Explorer quite a bit from these guys:
http://download.cnet.com/COM-Explorer/3000-2206_4-10022464.html?tag=mncol;lst
I had to install it last year to debug a bizarre COM registration issue with Office plugins.
Also, I have no affiliation with these guys whatsoever (and it looks like the company might be toast anyway). | unknown | |
d15690 | val | Your issue is most likely that at the point where your compiling your template the DOM hasn't loaded. While your render function is presumably not called until later which is why at the point your able to log the template.
When you declare a backbone view, the statements that assign a value to it's prototype are executed right away.
For example in your case the following line is executed right away
tmpl2: _.template( $.trim( $('#tmpl').html() ) ), //HTML from template
You can instead compile the template in your initialize function (assuming that that is called after the DOM has loaded).
For example
initialize: function () {
this.tmpl1 = _.template("<p>hello: <%= name %></p>"); //HTML hardcoded
this.tmpl2 = _.template( $.trim( $('#tmpl').html() ) );
}
However this has the disadvantage of the template being compiled for every instance of your view, what would probably make more sense in your case is to store your template separately and require it and use that. | unknown | |
d15691 | val | Do you have a /usr/local/lib64/libstdc++.so.6?
Typically only package installs have /usr prefix; the default for anything else is /usr/local. I'd check where your GCC was installed because I think you're examining the wrong file. You should find that your one is ultimately a link to a libstdc++.so.6.0.24.
GLIBCXX_3.4.19 implies GCC 4.8.3+ which (from memory) is the CentOS 7-packaged GCC. | unknown | |
d15692 | val | Thanks to AlwaysLearning for pointing me in the right direction, went with the PowerShell solution
Invoke-Sqlcmd
Thanks again!! | unknown | |
d15693 | val | If you run indexer.php from cli, using the following parameters, do the alerts become resolved:
indexer.php reindex all
If so, is executing indexer.php with those params as part of your script an option?
Edit: also, in Mage_Index_Model_Process take a look at reindexEverything() method.
indexer.php has an example of its usage.
A: I just encountered this issue in CE v1.9.0.1. My admin module was getting all processes as a collection and looping through each one calling reindexEverything(). I based the code on the adminhtml process controller which was working fine, but my code wasn't working at all.
I finally figured out the issue was that I had previously set the reindex mode to manual (to speed up my product import routine) as follows:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));
// run product import
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach($processes as $p)
{
if($p->getIndexer()->isVisible())
{
$p->reindexEverything();
//echo $p->getIndexer()->getName() . ' reindexed<br>';
}
}
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
SOLUTION: set mode back to MODE_REAL_TIME before reindexing everything:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));
// run product import
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach($processes as $p)
{
if($p->getIndexer()->isVisible())
{
$p->reindexEverything();
//echo $p->getIndexer()->getName() . ' reindexed<br>';
}
}
Note: these are snips from a few different methods hence the repeated assignment of $processes etc..
It seemed reindexEverything() wasn't doing anything when the processes index mode was set to MODE_MANUAL. Setting mode back to MODE_REAL_TIME and then calling reindexEverything worked fine.
I hope this helps someone as I had a few frustrated hours figuring this one out!
Thanks | unknown | |
d15694 | val | You can do solutions like @TonyAndrews by manipulating numeric or data values. For VARCHAR2 an alternative to dynamic SQL could be to have two expressions:
order by
case when :sorting='ASC' then col1 end ASC,
case when :sorting='DESC' then col1 end DESC
When :sorting has the value 'ASC' the result of that ORDER BY becomes like if it had been:
order by
col1 ASC,
NULL DESC
When :sorting has the value 'DESC' the result of that ORDER BY becomes like if it had been:
order by
NULL ASC,
col1 DESC
One downside to this method is that those cases where the optimizer can skip a SORT operation because there is an index involved that makes the data already sorted like desired, that will not happen when using the CASE method like this. This will mandate a sorting operation no matter what.
A: If the column you are sorting by is numeric then you could do this:
order by case when :dir='ASC' then numcol ELSE -numcol END
For a date column you could do:
order by case when :dir='ASC' then (datecol - date '1901-01-01')
else (date '4000-12-31' - datecol) end
I can't think of a sensible way for a VARCHAR2 column, other than using dynamic SQL to construct the query (which would work for any data type of course).
A: This will work for all data types:
SELECT *
FROM (SELECT table.*
,ROW_NUMBER() OVER (ORDER BY prod_id) sort_asc
,ROW_NUMBER() OVER (ORDER BY prod_id DESC) sort_desc
FROM table)
ORDER BY CASE WHEN :odb = 1 THEN sort_asc ELSE sort_desc END
A: Unfortunatelly, you can not do it dynamically, because Oracle builds the execution plan based on these ASC and DESC keywords.
What you can do is changing the ORDER BY clause to this:
SELECT * table
ORDER BY :order_param
And pass :odb value to :order_param if you want to order it by ASC (bigger :odb values would be least in order) or 1/:odb if you want to order by DESC (bigger :odb values would produce smaller 1/:odb values and would appear on top of the result).
And, as always, you can generate the query dynamically in a stored procedure:
IF ... THEN
EXECUTE IMMEDIATE 'SELECT * table ORDER BY CASE WHEN :odb = 1 THEN 1 END ASC';
ELSE
EXECUTE IMMEDIATE 'SELECT * table ORDER BY CASE WHEN :odb = 1 THEN 1 END DESC';
END IF; | unknown | |
d15695 | val | Through a day's study,I find the reason finally.The step of change as follow:
1.Change vertex.glsl and add some sentences:
uniform mat4 uVertexMatrix;
uniform mat4 uTextureMatrix;
void main() {
gl_Position = uVertexMatrix*a_vertexCoor;
vec2 textureCoor = (uTextureMatrix*vec4(a_textureCoor,0,1)).xy;
v_textureCoor = vec2(textureCoor.x,textureCoor.y);
}
2.Change onDrawFrame() method and add some sentences:
....
//important code
mSurfaceTexture.getTransformMatrix(mTextureMatrix);
...
GLES20.glUniformMatrix4fv(mVertexMatrixLocation,1,false,mVertexMatrix,0);
GLES20.glUniformMatrix4fv(mTextureMatrixLocation,1,false, mTextureMatrix,0);
...
Then you can get the correct result through two steps descript above.
In the previous vertex.glsl,the code v_textureCoor = vec2(1.0 - textureCoor.x,1.0-textureCoor.y); can transform the texture to get correct view based on https://learnopengl.com/Getting-started/Textures ,but it not works always on various devices.
In many open source projects,such as google/grafika and aiyaapp/AAVT,matrix-transform has been used to handle texture.They inspire me,and handle the problem finally. | unknown | |
d15696 | val | You should use the __() function (codex link). This function returns the translated string:
if(trim($_POST['contactSubject']) === '') {
$subjectError = __('Please enter a subject.', 'wpml_contact');
$hasError = true;
} else {
$subject = trim($_POST['contactSubject']);
}
The _e() function returns and displays the translated string. | unknown | |
d15697 | val | What you need is controlling the terminal's cursor.
After user giving input and hit enter, cursor moves to next line.
You need to move the cursor up one line then move it to end of that line, print % then move cursor back to the new line.
You can do that using Terminal's escape sequence.
This library can make it easier for you to perform cursor movement
http://code.activestate.com/recipes/475116-using-terminfo-for-portable-color-output-cursor-co/ | unknown | |
d15698 | val | There are at least a few bugs here:
*
*As mentioned in the comments, struct point *t is either a pointer to a single struct point, or an array of points. It is not a pointer to an array of pointers to struct point. So t[i]->x should be t[i].x.
*If ctr is intended to be the length of an array of points, t[ctr] will run off the end of the array, and could access uninitialized memory. In that case, t[ctr-1] would be the last element of the array.
*Rather than swapping entire points, you are just swapping the x coordinates.
A: From what I understand you don't want to sort it, but find point with maximum x and make sure it is stored at p[n-1].
struct point
{
float x;
float y;
} p[1000];
This is how it could look like:
void max(struct point *t, int ctr)
{
struct point temp;
int i;
for(i = 0; i < (ctr - 1); i++)
{
if (t[ctr - 1].x < t[i].x)
{
temp = t[ctr - 1];
t[ctr - 1] = t[i];
t[i] = temp;
}
}
}
This function takes struct point *t as an argument, which is pointer to first point just like p is. t[i] is struct point at index i (not pointer to struct point), so you use . instead of -> when you access its members. And since you are indexing from zero, last element of an array of size n has index n-1, which is place where the struct point with the highest x will be stored.
Example:
int main ()
{
for(int i = 0; i < 99; i++)
{
p[i].x = 1;
p[i].y = 3;
}
p[4].x = 7;
int n = 100;
max(p, n);
cout << p[n - 1].x;
return 0;
}
output: 7 | unknown | |
d15699 | val | In the interactive prompt, _ has "magic" behavior -- it gets set to the value of whatever expression was evaluated last:
>>> 3 + 3
6
>>> _
6
If, however, you assign something to a variable named _ yourself, then you only "see" that variable, and the magic variable is hidden ("masked"):
>>> _ = 3
>>> 3 + 3
6
>>> _
3
This happens because your local variable _ is unrelated to the variable that has the magic behavior, it just happens to have the same name.
So don't do that, not in the interactive prompt anyway.
A: It means exactly what it says it means; you should not assign anything to the _ variable as that would hide the real magic variable:
>>> 1 + 1
2
>>> _
2
>>> _ = 'foo'
>>> 2 + 2
4
>>> _
'foo'
The magic _ variable stores the result of the last expression that was echoed, but by assigning to _ you no longer can 'see' this magic variable. Looking up _ shows whatever value I assigned to it now.
Luckily, you can also delete the shadowing _ name again:
>>> del _
>>> 2 + 2
4
>>> _
4 | unknown | |
d15700 | val | If you change the following style you should get what you want:
#background_right {
/*background:transparent url(../images/bgr.png) no-repeat fixed center top;*/
background-color:white;
margin:0;
padding:0;
}
A: Just remove or outcomment the particular CSS line responsible for this. Or am I thinking too simple about this problem? If so, then please elaborate more about the context of the problem. If it is for instance an autogenerated stylesheet which you don't have control over, then best what you can do is to grab JavaScript (jQuery?) to remove/override the background image in the particular style class.
Edit: if you rather want a white background, then you'll need to get rid of the .body_background class as well. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.