Something like this should do the trick (However, read after the snippet for more info)
CREATE PROCEDURE GetFilteredData()
BEGIN
DECLARE bDone INT;
DECLARE var1 CHAR(16); -- or approriate type
DECLARE Var2 INT;
DECLARE Var3 VARCHAR(50);
DECLARE curs CURSOR FOR SELECT something FROM somewhere WHERE some stuff;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
--Fld1 type,
--Fld2 type,
--...
);
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO var1,, b;
IF whatever_filtering_desired
-- here for whatever_transformation_may_be_desired
INSERT INTO tblResults VALUES (var1, var2, var3 ...);
END IF;
UNTIL bDone END REPEAT;
CLOSE curs;
SELECT * FROM tblResults;
END
A few things to consider...
Concerning the snippet above:
More generally: trying to avoid needing a cursor.
I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.
Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.
Google says to check out getenv():
Returns an unmodifiable string map view of the current system environment.
I'm not sure how system variables differ from environment variables, however, so if you could clarify I could help out more.
Assuming you don't want to make it a block element, then you might try:
.title {
display: inline-block; /* which allows you to set the height/width; but this isn't cross-browser, particularly as regards IE < 7 */
line-height: 2em; /* or */
padding-top: 1em;
padding-bottom: 1em;
}
But the easiest solution is to simply treat the .title
as a block-level element, and using the appropriate heading tags <h1>
through <h6>
.
my solution:
; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = $.fn[ name ];
$.fn[ name ] = function( speed, easing, callback ) {
if(speed == null || typeof speed === "boolean"){
var ret=cssFn.apply( this, arguments )
$.fn.triggerVisibleEvent.apply(this,arguments)
return ret
}else{
var that=this
var new_callback=function(){
callback.call(this)
$.fn.triggerVisibleEvent.apply(that,arguments)
}
var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
return ret
}
};
});
$.fn.triggerVisibleEvent=function(){
this.each(function(){
if($(this).is(':visible')){
$(this).trigger('visible')
$(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
}
})
}
})(jQuery);
for example:
if(!$info_center.is(':visible')){
$info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
processMoreLessButton()
}
function processMoreLessButton(){
//some logic
}
Assuming by "special" you mean non-word characters, then that is pretty easy.
str = str.replace(/[_\W]+/g, "-")
Starting Xampp as a console application (simply by doubleclicking xampp_start.exe in the Xampp root folder) was the only thing that worked for me on Windows 10 (no Skype, no Word Wide Web Publishing Service). WampServer and UwAmp also didn't work.
GLM has good example of rotation : http://glm.g-truc.net/code.html
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
glm::mat4(1.0f),
glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
ViewTranslate,
Rotate.y,
glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
ViewRotateX,
Rotate.x,
glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
glm::mat4(1.0f),
glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));
I would use   is a lot cleaner in my opinion.
If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:
Sub norepeat()
Range("C8:C16").RemoveDuplicates (1)
End Sub
Regards
What you are trying to do can be simplified down to this.
$('input:text').bind('focus blur', function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
<input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
<input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
<input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
In my case the url was not loading when I was using parameter in it.
As a quick fix I add
<base href="<yourdomain/IP>"></base>
under tag of index.html file in build folder.
And this just fixed my problem.
The OP left out some crucial information from the question and only put it in a comment to an answer.
I need to initialize after declaring, because will be different depending on a condition, I mean something like this int myArray[SIZE]; if(condition1) { myArray{x1, x2, x3, ...} } else if(condition2) { myArray{y1, y2, y3, ...} } . . and so on...
With this in mind, all of the possible arrays will need to be stored into data somewhere anyhow, so no memcpy is needed (or desired), only a pointer and a 2d array are required.
//static global since some compilers build arrays from instruction data
//... notably not const though so they can later be modified if needed
#define SIZE 8
static int myArrays[2][SIZE] = {{0,1,2,3,4,5,6,7},{7,6,5,4,3,2,1,0}};
static inline int *init_myArray(_Bool conditional){
return myArrays[conditional];
}
// now you can use:
//int *myArray = init_myArray(1 == htons(1)); //any boolean expression
The not-inlined version gives this resulting assembly on x86_64:
init_myArray(bool):
movzx eax, dil
sal rax, 5
add rax, OFFSET FLAT:myArrays
ret
myArrays:
.long 0
.long 1
.long 2
.long 3
.long 4
.long 5
.long 6
.long 7
.long 7
.long 6
.long 5
.long 4
.long 3
.long 2
.long 1
.long 0
For additional conditionals/arrays, just change the 2 in myArrays to the desired number and use similar logic to get a pointer to the right array.
Does it have to be an actual service? Can you just use the built in scheduled tasks in the windows control panel.
What about something like a stream reducer ?
Here is an example using ES6 classes how to use one.
var stream = require('stream')
class StreamReducer extends stream.Writable {
constructor(chunkReducer, initialvalue, cb) {
super();
this.reducer = chunkReducer;
this.accumulator = initialvalue;
this.cb = cb;
}
_write(chunk, enc, next) {
this.accumulator = this.reducer(this.accumulator, chunk);
next();
}
end() {
this.cb(null, this.accumulator)
}
}
// just a test stream
class EmitterStream extends stream.Readable {
constructor(chunks) {
super();
this.chunks = chunks;
}
_read() {
this.chunks.forEach(function (chunk) {
this.push(chunk);
}.bind(this));
this.push(null);
}
}
// just transform the strings into buffer as we would get from fs stream or http request stream
(new EmitterStream(
["hello ", "world !"]
.map(function(str) {
return Buffer.from(str, 'utf8');
})
)).pipe(new StreamReducer(
function (acc, v) {
acc.push(v);
return acc;
},
[],
function(err, chunks) {
console.log(Buffer.concat(chunks).toString('utf8'));
})
);
You Missed a colon(:) before the username parameter. therefore your code must change from:
@Query("select u from user u where u.username like '%username%'")
to :
@Query("select u from user u where u.username like '%:username%'")
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
The default submit Action is Ext.form.action.Submit, which uses an Ajax request to submit the form's values to a configured URL. To enable normal browser submission of an Ext form, use the standardSubmit config option.
Link: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.Basic-cfg-standardSubmit
solution: put standardSubmit :true in your config. Hope that this will help you :)
Again, best answer is:
window.onbeforeunload = function () {
window.scrollTo(0,0);
};
(thats for non-jQuery, look up if you are searching for the JQ method)
EDIT: a little mistake its "onbeforunload" :) Chrome and others browsers "remember" the last scroll position befor unloading, so if you set the value to 0,0 just before the unload of your page they will remember 0,0 and won't scroll back to where the scrollbar was :)
This is an easy way to rename a file:
File oldfile =new File("test.txt");
File newfile =new File("test1.txt");
if(oldfile.renameTo(newfile)){
System.out.println("File renamed");
}else{
System.out.println("Sorry! the file can't be renamed");
}
I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't Foo.BA_ constant?
While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for the specification of a constant expression1. This refers to §4.12.4 Final Variables which defines a "constant variable" as follows:
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).
In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as "constant variables". The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.
In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final
may be what is needed.
You could change your code to use an enum
rather than int
constants, but that brings another couple of different restrictions:
default
case, even if you have case
for every known value of the enum
; see Why is default required for a switch on an enum?case
labels must all be explicit enum
values, not expressions that evaluate to enum
values.1 - The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and String
only, b) allow primaries that are literals (apart from null
) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, ++
, --
or instanceof
, and e) allow type casts to primitive types or String
only.
Note that this doesn't include any form of method or lambda calls, new
, .class
. .length
or array subscripting. Furthermore, any use of array values, enum
values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).
A simple answer:
To expand on the POSIX variables answer, note that you can do more interesting patterns. So for the case detailed here, you could simply do this:
tar -zxvf $1
cd ${1%.tar.*}
That will cut off the last occurrence of .tar.<something>.
More generally, if you wanted to remove the last occurrence of .<something>.<something-else> then
${1.*.*}
should work fine.
The link the above answer appears to be dead. Here's a great explanation of a bunch of the string manipulation you can do directly in Bash, from TLDP.
Wow, I couldn't believe some of the answers I've read here. There's actually an instruction in assembly which does this faster than anything else. bswap. You could simply write a function like this...
__declspec(naked) uint32_t EndianSwap(uint32 value)
{
__asm
{
mov eax, dword ptr[esp + 4]
bswap eax
ret
}
}
It is MUCH faster than the intrinsics that have been suggested. I've disassembled them and looked. The above function has no prologue/epilogue so virtually has no overhead at all.
unsigned long _byteswap_ulong(unsigned long value);
Doing 16 bit is just as easy, with the exception that you'd use xchg al, ah. bswap only works on 32-bit registers.
64-bit is a little more tricky, but not overly so. Much better than all of the above examples with loops and templates etc.
There are some caveats here... Firstly bswap is only available on 80x486 CPU's and above. Is anyone planning on running it on a 386?!? If so, you can still replace bswap with...
mov ebx, eax
shr ebx, 16
xchg bl, bh
xchg al, ah
shl eax, 16
or eax, ebx
Also inline assembly is only available in x86 code in Visual Studio. A naked function cannot be lined and also isn't available in x64 builds. I that instance, you're going to have to use the compiler intrinsics.
From the Linux manual page:
h A following integer conversion corresponds to a short int or unsigned short int argument, or a fol- lowing n conversion corresponds to a pointer to a short int argument.
So to print an unsigned short integer, the format string should be "%hu"
.
If you are using MS Excel 2007, you could use the conditional formatting
on the Home
tab as shown in the screenshot below. You could either use the color scales
default option as I have done here or you can go ahead and create a new rule
based on your data set.
In order to get the refresh_token
you need to include access_type=offline
in the OAuth request URL. When a user authenticates for the first time you will get back a non-nil refresh_token
as well as an access_token
that expires.
If you have a situation where a user might re-authenticate an account you already have an authentication token for (like @SsjCosty mentions above), you need to get back information from Google on which account the token is for. To do that, add profile
to your scopes. Using the OAuth2 Ruby gem, your final request might look something like this:
client = OAuth2::Client.new(
ENV["GOOGLE_CLIENT_ID"],
ENV["GOOGLE_CLIENT_SECRET"],
authorize_url: "https://accounts.google.com/o/oauth2/auth",
token_url: "https://accounts.google.com/o/oauth2/token"
)
# Configure authorization url
client.authorize_url(
scope: "https://www.googleapis.com/auth/analytics.readonly profile",
redirect_uri: callback_url,
access_type: "offline",
prompt: "select_account"
)
Note the scope has two space-delimited entries, one for read-only access to Google Analytics, and the other is just profile
, which is an OpenID Connect standard.
This will result in Google providing an additional attribute called id_token
in the get_token
response. To get information out of the id_token, check out this page in the Google docs. There are a handful of Google-provided libraries that will validate and “decode” this for you (I used the Ruby google-id-token gem). Once you get it parsed, the sub
parameter is effectively the unique Google account ID.
Worth noting, if you change the scope, you'll get back a refresh token again for users that have already authenticated with the original scope. This is useful if, say, you have a bunch of users already and don't want to make them all un-auth the app in Google.
Oh, and one final note: you don't need prompt=select_account
, but it's useful if you have a situation where your users might want to authenticate with more than one Google account (i.e., you're not using this for sign-in / authentication).
If you are using java Transport client 1.check 9300 is access able /open. 2.check the node and cluster name ,this should be the correct,you can check the node and cluster name by type ip:port in your browser. 3.Check the versions of your jar and Es installed version.
Yes, there is. For example, if you wanted to get the content of the first section of the article Stack Overflow, use a query like this:
The parts mean this:
format=xml
: Return the result formatter as XML. Other options (like JSON) are available. This does not affect the format of the page content itself, only the enclosing data format.
action=query&prop=revisions
: Get information about the revisions of the page. Since we don't specify which revision, the latest one is used.
titles=Stack%20Overflow
: Get information about the page Stack Overflow
. It's possible to get the text of more pages in one go, if you separate their names by |
.
rvprop=content
: Return the content (or text) of the revision.
rvsection=0
: Return only content from section 0.
rvparse
: Return the content parsed as HTML.
Keep in mind that this returns the whole first section including things like hatnotes (“For other uses …”), infoboxes or images.
There are several libraries available for various languages that make working with API easier, it may be better for you if you used one of them.
You could go to SmallestDotNet using IE from the server. That will tell you the version and also provide a download link if you're out of date.
If one really wants to make a variable read-only, IMHO the best way would be to use property() with only getter passed to it. With property() we can have complete control over the data.
class PrivateVarC(object):
def get_x(self):
pass
def set_x(self, val):
pass
rwvar = property(get_p, set_p)
ronly = property(get_p)
I understand that OP asked a little different question but since I found another question asking for 'how to set private variables' marked duplicate with this one, I thought of adding this additional info here.
You need to add the content-disposition header to the response:
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
return response;
Kind of a messy workaround, but assignment in lambdas is illegal anyway, so it doesn't really matter. You can use the builtin exec()
function to run assignment from inside the lambda, such as this example:
>>> val
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
val
NameError: name 'val' is not defined
>>> d = lambda: exec('val=True', globals())
>>> d()
>>> val
True
You should use this:
"\n"
You also might wanna have a look at PHP EOL.
File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();
Or, Try This:
String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();
I had the same problem. The solution was to update IntelliJ to the newest version.
You can use a StringWriter to write values to a string. It provides a stream-like syntax (though does not derive from Stream
) which works with an underlying StringBuilder
.
I just implemented as:
Array.prototype.exclude = function(list){
return this.filter(function(el){return list.indexOf(el)<0;})
}
Use as:
myArray.exclude(toRemove);
A similar question is here: Is there a limit to the length of a GET request?
I've hit the limit and on my shared hosting account, but the browser returned a blank page before it got to the server I think.
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
It's not ideal, but you could disable Jackson's auto-discovery of JSON properties, using @JsonAutoDetect
at the class level. This would prevent it from trying to handle the Javassist stuff (and failing).
This means that you then have to annotate each getter manually (with @JsonProperty
), but that's not necessarily a bad thing, since it keeps things explicit.
var="a b c"
for i in $var
do
p=`echo -e "$p"'\n'$i`
done
echo "$p"
The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.
The reason is that for deleting an object, Hibernate requires that the object is in persistent state. Thus, Hibernate first fetches the object (SELECT) and then removes it (DELETE).
Why Hibernate needs to fetch the object first? The reason is that Hibernate interceptors might be enabled (http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html), and the object must be passed through these interceptors to complete its lifecycle. If rows are delete directly in the database, the interceptor won't run.
On the other hand, it's possible to delete entities in one single SQL DELETE statement using bulk operations:
Query q = session.createQuery("delete Entity where id = X");
q.executeUpdate();
I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.
In your view template, set a default value:
f.text_field :password, :value => "password"
In your Javascript (assuming jquery here):
$(document).ready(function() {
//add a handler to remove the text
});
Change the key of the component.
<Component key="1" />
<Component key="2" />
Component will be unmounted and a new instance of Component will be mounted since the key has changed.
edit: Documented on You Probably Don't Need Derived State:
When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.
@RequestParam
annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type.
This annotation indicates that a method parameter should be bound to a web request parameter.
For example Angular request for Spring RequestParam(s) would look like that:
$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
.success(function (data, status, headers, config) {
...
})
Endpoint with RequestParam:
@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
@RequestParam String username,
@RequestParam String password,
@RequestParam boolean auth,
HttpServletRequest httpServletRequest) {...
@RequestBody
annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters.
This annotation indicates a method parameter should be bound to the body of the web request.
For example Angular request for Spring RequestBody would look like that:
$scope.user = {
username: "foo",
auth: true,
password: "bar"
};
$http.post('http://localhost:7777/scan/l/register', $scope.user).
success(function (data, status, headers, config) {
...
})
Endpoint with RequestBody:
@RequestMapping(method = RequestMethod.POST, produces = "application/json",
value = "/register")
public Map<String, String> register(Model uiModel,
@RequestBody User user,
HttpServletRequest httpServletRequest) {...
Hope this helps.
In recent versions of major browsers you can use backdrop-filter property.
HTML
<div>backdrop blur</div>
CSS
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
}
or if you need different background color for browsers without support:
div {
background-color: rgba(255, 255, 255, 0.9);
}
@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
background-color: rgba(255, 255, 255, 0.5);
}
}
Demo: JSFiddle
Docs: Mozilla Developer: backdrop-filter
Is it for me?: CanIUse
If you are inside of Spring bean (in this case @Controller
bean) you shouldn't use Spring context instance at all. Just autowire className
bean directly.
BTW, avoid using field injection as it's considered as bad practice.
You need to use an undocumented trick with Excel's LINEST
function:
=LINEST(known_y's, [known_x's], [const], [stats])
A regular linear regression is calculated (with your data) as:
=LINEST(B2:B21,A2:A21)
which returns a single value, the linear slope (m
) according to the formula:
which for your data:
is:
You can also use Excel to calculate a regression with a formula that uses an exponent for x
different from 1
, e.g. x1.2:
using the formula:
=LINEST(B2:B21, A2:A21^1.2)
which for you data:
is:
Excel's LINEST
function can also calculate multiple regressions, with different exponents on x
at the same time, e.g.:
=LINEST(B2:B21,A2:A21^{1,2})
Note: if locale is set to European (decimal symbol ","), then comma should be replaced by semicolon and backslash, i.e.
=LINEST(B2:B21;A2:A21^{1\2})
Now Excel will calculate regressions using both x1 and x2 at the same time:
The impossibly tricky part there's no obvious way to see the other regression values. In order to do that you need to:
select the cell that contains your formula:
extend the selection the left 2 spaces (you need the select to be at least 3 cells wide):
press F2
press Ctrl+Shift+Enter
You will now see your 3 regression constants:
y = -0.01777539x^2 + 6.864151123x + -591.3531443
I had a function that I wanted to perform a regression using some exponent:
y = m×xk + b
But I didn't know the exponent. So I changed the LINEST
function to use a cell reference instead:
=LINEST(B2:B21,A2:A21^F3, true, true)
With Excel then outputting full stats (the 4th paramter to LINEST
):
I tell the Solver to maximize R2:
And it can figure out the best exponent. Which for you data:
is:
Some of the answers here haven't really helped.
People are showing you how to find stuff, but now how to replace it.
I just had a look, and it looks like it's Ctrl+H for replace, then you get the find dialog as well as a replace dialog. This worked for me.
If you wish to use the bound column value, you can simply refer to the combo:
sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo
You can also refer to the column property:
sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"
Dim rs As DAO.Recordset
Set rs = CurrentDB.OpenRecordset(sSQL)
strText = rs!AText
strText = rs.Fields(1)
In a textbox:
= DlookUp("AText","MyTable","ID=" & MyCombo)
*edited
Using Bootstrap, This is what you can do. Using class "text-hide", the disabled option will be shown at first but not on the list.
<select class="form-control" >
<option selected disabled class="text-hide">Title</option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C
). Now a program can use SIG_IGN
to ignore all signals or SIG_DFL
to restore the default action.
Now if you do $ command &
then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.
I think the best way is to use a good Map. Using a dictionary you can map almost any input to some other value/object/function.
your code would look something(psuedo) like this:
void InitMap(){
Map[key1] = Object/Action;
Map[key2] = Object/Action;
}
Object/Action DoStuff(Object key){
return Map[key];
}
If you are branch master
and you do a git checkout <SHA>
I'm fairly certain that this causes git to load that commit in a detached state, changing you out of the current branch.
If you want to make changes you can and then you can do a git checkout -b <mynewbranch>
to create a new branch based off that commit and any changes you have made.
$('.date-pick').datePicker().val(new Date()).trigger('change')
finally, that what i look for the last few hours! I need initiate changes, not just setup date in text field!
When working with Visual Studio 2013 and VB.NET I found that you can quite easily customize the menu and add the "New Window" command - there is no need to mess with the registry!
God only knows why Microsoft chose not to include the command for some languages...?
$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});
<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>
In case you need the answer to be a member of the input numpy array:
Just to add that the percentile function in numpy by default calculates the output as a linear weighted average of the two neighboring entries in the input vector. In some cases people may want the returned percentile to be an actual element of the vector, in this case, from v1.9.0 onwards you can use the "interpolation" option, with either "lower", "higher" or "nearest".
import numpy as np
x=np.random.uniform(10,size=(1000))-5.0
np.percentile(x,70) # 70th percentile
2.075966046220879
np.percentile(x,70,interpolation="nearest")
2.0729677997904314
The latter is an actual entry in the vector, while the former is a linear interpolation of two vector entries that border the percentile
This is just an Improvement of @soulcheck 's answer, and fix of the typo in forEach (missing closing bracket);
server.get('/usersList', (req, res) =>
User.find({}, (err, users) =>
res.send(users.reduce((userMap, item) => {
userMap[item.id] = item
return userMap
}, {}));
);
);
cheers!
You can use Stack
to make the image stretch to the full screen.
Stack(
children: <Widget>
[
Positioned.fill( //
child: Image(
image: AssetImage('assets/placeholder.png'),
fit : BoxFit.fill,
),
),
...... // other children widgets of Stack
..........
.............
]
);
Note: Optionally if are using a Scaffold
, you can put the Stack
inside the Scaffold
with or without AppBar
according to your needs.
The fact that the first digit has to be in the range 5-9
only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:
^([5-9]\d|\d{3,})$
This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The |
means "or", so either [5-9]\d
or any number with 3 or more digits. \d
is simply a shortcut for [0-9]
.
Edit: To disallow numbers like 001
:
^([5-9]\d|[1-9]\d{2,})$
This forces the first digit to be not a zero in the case of 3 or more digits.
Just a quick check as well if you keep your js files separately: make sure to reload your resources properly. Browsers will usually cache files, so just assure that i.e. a former typo is corrected in your loaded resources.
See this answer for permanent cache disabling in Chrome/Chromium. Otherwise you can generally force a full reload with Ctrl+F5 or Shift+F5 as mentioned in this answer.
As already mentioned, they are the same, but I use either the one or the other depending on the language in which the corresponding framework was written.
For everything related to Objective-C, I use nil. For example:
- (BOOL)doSomethingWithObjectsInArray:(NSArray *)anArray {
if (anArray == nil) return NO;
// process elements
...
}
However, when checking validity of data models from a C-framework (like AddressBook framework and CoreFoundation), I use NULL. For example:
- (BOOL)showABUnknownPersonVCForABRecordRef:(ABRecordRef)aRecord {
if (aRecord == NULL) return NO;
// set-up the ABUnknownPersonViewController and display it on screen
..
}
This way, I have subtle clues in my code if I'm dealing with Obj-C or C based code.
WordUtils.capitalizeFully(str)
from apache commons-lang has the exact semantics as required.
This worked for me on Safari 5 on Mac OSX, jQuery 1.4:
$("Selector")[elementIx].selectionStart = desiredStartPos;
$("Selector")[elementIx].selectionEnd = desiredEndPos;
And make sure you download the Windows7.1 SDK, not just the Windows 7 one. That caused me a lot of head pounding.
mysql_real_escape_string() or str_replace() function will help you to solve your problem.
var rangeFromLimits = arc4random_uniform( (UPPerBound - LOWerBound) + 1)) + LOWerBound;
/**
* @param num The number to round
* @param precision The number of decimal places to preserve
*/
function roundUp(num, precision) {
precision = Math.pow(10, precision)
return Math.ceil(num * precision) / precision
}
roundUp(192.168, 1) //=> 192.2
Check your compileSdkVersion on app build.gradle. Set it to 21:
compileSdkVersion 21
/usr/bin/hive --version worked for me.
[qa@ip-10-241-1-222 ~]$ /usr/bin/hive --version
Hive 0.13.1-cdh5.3.1
Subversion file:///data/1/jenkins/workspace/generic-package-rhel64-6-0/topdir/BUILD/hive-0.13.1-cdh5.3.1 -r Unknown
Compiled by jenkins on Tue Jan 27 16:38:55 PST 2015
From source with checksum 1bb86e4899928ce29cbcaec8cf43c9b6
[qa@ip-10-241-1-222 ~]$
In dplyr 0.3 this can be easily achieved using the distinct()
method.
Here is an example:
distinct_df = df %>% distinct(field1)
You can get a vector of the distinct values with:
distinct_vector = distinct_df$field1
You can also select a subset of columns at the same time as you perform the distinct()
call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:
distinct_df = df %>% distinct(field1) %>% select(field1)
distinct_vector = distinct_df$field1
Ternary operators are just shorthand. They compile into the equivalent if-else
statement, meaning they will be exactly the same.
In my case, I was doing:
curl <blabla> | jq | grep <blibli>
With jq .
it worked: curl <blabla> | jq . | grep <blibli>
We're all working around some old bugs that haven't been fixed likely because it's "by design." I ran into the freezing problem @iwasrobbed described elsewhere when trying to nil the interactivePopGestureRecognizer
's delegate which seemed like it should've worked. If you want swipe behavior reconsider using backBarButtonItem
which you can customize.
I also ran into interactivePopGestureRecognizer
not working when the UINavigationBar
is hidden. If hiding the navigation bar is a concern for you, reconsider your design before implementing a workaround for a bug.
You may try adding an additional argument of type HttpServletRequest
to the getUrlValue()
method:
@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}
information is discarded in the compiling process. Even if a decompiler could produce the logical equivalent code with classes and everything (it probably can't), the self-documenting part is gone in optimized release code. No variable names, no routine names, no class names - just addresses.
Use IIF.
<asp:Label ID="Label18" Text='<%# IIF(Eval("item") Is DBNull.Value,"0", Eval("item") %>'
runat="server"></asp:Label>
A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}
-block can throw (or a super class of that).
try {
//do something that throws ExceptionA, e.g.
throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
//do something to handle the exception, e.g.
System.out.println("Message: " + e.getMessage());
}
What you are trying to do is this:
try {
throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
System.out.println("Message: " + e.getMessage());
}
This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement
.
for me work this:
<input type="text"required id="autocomplete">_x000D_
_x000D_
<script>_x000D_
function initAutocomplete() {_x000D_
new google.maps.places.Autocomplete(_x000D_
(document.getElementById('autocomplete')),_x000D_
{types: ['geocode']}_x000D_
);_x000D_
}_x000D_
</script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"_x000D_
async defer></script>
_x000D_
When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:
<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />
or the same with image/vnd.microsoft.icon
, and it will work with all browsers.
Note: There is no IANA specification for the MIME-type image/x-icon
, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon
.
The only case in which there is a difference is if you were trying to use an .ico file in an <img>
tag (which is pretty unusual).
Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon
. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico
files as images, use png
.
Just for sake of completeness, you can also use the same technique above with excel tables.
In the example below, I'm looking of a text in any cell of a Excel Table named "tblConfig", place in the sheet named Config that normally is set to be hidden. I'm accepting the defaults of the Find method.
Dim list As ListObject
Dim config As Worksheet
Dim cell as Range
Set config = Sheets("Config")
Set list = config.ListObjects("tblConfig")
'search in any cell of the data range of excel table
Set cell = list.DataBodyRange.Find(searchTerm)
If cell Is Nothing Then
'when information is not found
Else
'when information is found
End If
If you are on Windows, you just need to do only one step as 'rails restart' and then again type 'rails s' You are good to go.
If the url is in a cell in your workbook, you can simply copy the value from that cell:
Private Sub CommandButton1_Click()
Sheets("Sheet1").Range("A1").Copy
End Sub
(Add a button by using the developer tab. Customize the ribbon if it isn't visible.)
If the url isn't in the workbook, you can use the Windows API. The code that follows can be found here: http://support.microsoft.com/kb/210216
After you've added the API calls below, change the code behind the button to copy to the clipboard:
Private Sub CommandButton1_Click()
ClipBoard_SetData ("http:\\stackoverflow.com")
End Sub
Add a new module to your workbook and paste in the following code:
Option Explicit
Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) _
As Long
Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) _
As Long
Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
ByVal dwBytes As Long) As Long
Declare Function CloseClipboard Lib "User32" () As Long
Declare Function OpenClipboard Lib "User32" (ByVal hwnd As Long) _
As Long
Declare Function EmptyClipboard Lib "User32" () As Long
Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
ByVal lpString2 As Any) As Long
Declare Function SetClipboardData Lib "User32" (ByVal wFormat _
As Long, ByVal hMem As Long) As Long
Public Const GHND = &H42
Public Const CF_TEXT = 1
Public Const MAXSIZE = 4096
Function ClipBoard_SetData(MyString As String)
Dim hGlobalMemory As Long, lpGlobalMemory As Long
Dim hClipMemory As Long, X As Long
' Allocate moveable global memory.
'-------------------------------------------
hGlobalMemory = GlobalAlloc(GHND, Len(MyString) + 1)
' Lock the block to get a far pointer
' to this memory.
lpGlobalMemory = GlobalLock(hGlobalMemory)
' Copy the string to this global memory.
lpGlobalMemory = lstrcpy(lpGlobalMemory, MyString)
' Unlock the memory.
If GlobalUnlock(hGlobalMemory) <> 0 Then
MsgBox "Could not unlock memory location. Copy aborted."
GoTo OutOfHere2
End If
' Open the Clipboard to copy data to.
If OpenClipboard(0&) = 0 Then
MsgBox "Could not open the Clipboard. Copy aborted."
Exit Function
End If
' Clear the Clipboard.
X = EmptyClipboard()
' Copy the data to the Clipboard.
hClipMemory = SetClipboardData(CF_TEXT, hGlobalMemory)
OutOfHere2:
If CloseClipboard() = 0 Then
MsgBox "Could not close Clipboard."
End If
End Function
Full code example..
Try it once..
<?php
// Multiple recipients
$to = '[email protected], [email protected]'; // note the comma
// Subject
$subject = 'Birthday Reminders for August';
// Message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Johny</td><td>10th</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Mary <[email protected]>, Kelly <[email protected]>';
$headers[] = 'From: Birthday Reminder <[email protected]>';
$headers[] = 'Cc: [email protected]';
$headers[] = 'Bcc: [email protected]';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>
I was able to get past this by making sure all my SDKs were up to date. (Mac OS 10.13.3, Android Studio 3.0.1). I went to Android Studio -> Check for Updates... and let it run. Once my Android 5.0/5.1 (API level 21/22) SDKs were updated to revision 2:
After doing this update, I was able to run the emulator without crashing out immediately with a "Emulator: Process finished with exit code 0" error.
if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
For comparing 2 strings, either use the built in function strcmp()
using header file string.h
if(strcmp(a,b)==0)
printf("Entered strings are equal");
else
printf("Entered strings are not equal");
OR you can write your own function like this:
int string_compare(char str1[], char str2[])
{
int ctr=0;
while(str1[ctr]==str2[ctr])
{
if(str1[ctr]=='\0'||str2[ctr]=='\0')
break;
ctr++;
}
if(str1[ctr]=='\0' && str2[ctr]=='\0')
return 0;
else
return -1;
}
If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query
INSERT INTO TABLE tweet_table
SELECT "my_data" AS my_column
FROM pre_loaded_tbl
LIMIT 5;
Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.
However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.
This method orderBy
does not change the input array,
you have to assign the result to your array :
var chars = this.state.characters;
chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'
this.setState({characters: chars})
You can use following script :
Declare @Cons_Name NVARCHAR(100)
Declare @Str NVARCHAR(500)
SELECT @Cons_Name=name
FROM sys.objects
WHERE type='UQ' AND OBJECT_NAME(parent_object_id) = N'TableName';
---- Delete the unique constraint.
SET @Str='ALTER TABLE TableName DROP CONSTRAINT ' + @Cons_Name;
Exec (@Str)
GO
Try this:
dict = {0:{1:'a'}, 1:{2:'b'}, 2:{3:'c'}}
for (var key in dict){
console.log( key, dict[key] );
}
0 Object { 1="a"}
1 Object { 2="b"}
2 Object { 3="c"}
I've profiled Justins two solutions. a.Any(a => b.Contains(a))
is fastest.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AnswersOnSO
{
public class Class1
{
public static void Main(string []args)
{
// How to check if list A contains any value from list B?
// e.g. something like A.contains(a=>a.id = B.id)?
var a = new List<int> {1,2,3,4};
var b = new List<int> {2,5};
var times = 10000000;
DateTime dtAny = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Any(b.Contains);
}
var timeAny = (DateTime.Now - dtAny).TotalSeconds;
DateTime dtIntersect = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Intersect(b).Any();
}
var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;
// timeAny: 1.1470656 secs
// timeIn.: 3.1431798 secs
}
}
}
If you're using SWT, you might want to look at adding a MouseMoveListener as explained here.
Press Alt and click. This works on Windows and Linux*, and it should work on Mac, too.
More multi-cursor features are now available in Visual Studio Code 0.2:
Multi cursor improvements
Ctrl+D (Cmd+D on Mac) selects next occurrence of word under cursor or of the current selection
Ctrl+K Ctrl+D moves last added cursor to next occurrence of word under cursor or of the current selection
The commands use matchCase by default. If the find widget is open, then the find widget settings (matchCase / matchWholeWord) will be used for determining the next occurrence
Ctrl+U (Cmd+U on Mac) undoes the last cursor action, so if you added a cursor too many or made a mistake, you can press Ctrl+U (Cmd+U on Mac) to go back to the previous cursor state. Adding cursor up or down (Ctrl+Alt+Up / Ctrl+Alt+Down) (Cmd+Alt+Up / Cmd+Alt+Down on Mac) now reveals the last added cursor to make it easier to work with multiple cursors on more than 1 viewport height at a time (i.e. select 300 lines and only 80 fit in the viewport).This makes it a lot easier to introduce multiple cursors
* Linux drag-window conflict:
Some distros (e.g. Ubuntu) assign window dragging to Alt+LeftMouse, which will conflict with VSCode.
So, recent versions of VSCode let you toggle between Alt+LeftMouse and Ctrl+LeftMouse under the Selection menu, as detailed in another answer.
Alternately, you could change your OS key bindings using
gsettings
as mentioned in another answer.
Typically for dynamic lists of items, you use a std::vector
.
Generally I use memset or a loop for raw memory dynamic allocation, depending on how variable I anticipate that area of code to be in the future.
It's not a problem with JDK. In Eclipse Helios, it allows the @Override annotation for implemented interface methods, whichever JDK 5 or 6. As for Eclipse Galileo, the @Override annotation is not allowed, whichever JDK 5 or 6.
A more "C++"ish version
#include <iostream>
#include <sstream>
#include "openssl/sha.h"
using namespace std;
string to_hex(unsigned char s) {
stringstream ss;
ss << hex << (int) s;
return ss.str();
}
string sha256(string line) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, line.c_str(), line.length());
SHA256_Final(hash, &sha256);
string output = "";
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
output += to_hex(hash[i]);
}
return output;
}
int main() {
cout << sha256("hello, world") << endl;
return 0;
}
If you’re running JQuery on a production site, which library should you load? JQuery.js or JQuery.min.js? The short answer is, they are essentially the same, with the same functionality.
One version is long, while the other is the minified version. The minified is compressed to save space and page load time. White spaces have been removed in the minified version making them jibberish and impossible to read.
If you’re going to run the JQuery library on a production site, I recommend that you use the minified version, to decrease page load time, which Google now considers in their page ranking.
Another good option is to use Google’s online javascript library. This will save you the hassle of downloading the library, as well as uploading to your site. In addition, your site also does not use resources when JQuery is loaded.
The latest JQuery minified version from Google is available here.
You can link to it in your pages using:
http://ulyssesonline.com/2010/12/03/jquery-js-or-jquery-min-js/
You should probably start with a little theory and simple examples such as the midpoint displacement algorithm. You should also learn a little about Perlin Noise if you are interested in generating graphics. I used this to get me started with my final year project on procedural generation.
Fractals are closely related to procedural generation.
Terragen and SpeedTree will show you some amazing possibilities of procedural generation.
Procedural generation is a technique that can be used in any language (it is definitely not restricted to procedural languages such as C, as it can be used in OO languages such as Java, and Logic languages such as Prolog). A good understanding of recursion in any language will strengthen your grasp of Procedural Generation.
As for 'serious' or non-game code, procedural generation techniques have been used to:
After having to tackle this issue myself, I would like to build upon user854301's answer.
Mongoose ^4.13.8 I was able to use a function called toConstructor()
which allowed me to avoid building the query multiple times when filters are applied. I know this function is available in older versions too but you'll have to check the Mongoose docs to confirm this.
The following uses Bluebird promises:
let schema = Query.find({ name: 'bloggs', age: { $gt: 30 } });
// save the query as a 'template'
let query = schema.toConstructor();
return Promise.join(
schema.count().exec(),
query().limit(limit).skip(skip).exec(),
function (total, data) {
return { data: data, total: total }
}
);
Now the count query will return the total records it matched and the data returned will be a subset of the total records.
Please note the () around query() which constructs the query.
I got tired of forgetting the system_profiler SPUSBDataType
syntax, so I made an lsusb
alternative. You can find it here , or install it with homebrew:
brew install lsusb
Use config.to_prepare to load you monkey patches/extensions for every request in development mode.
config.to_prepare do |action_dispatcher|
# More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
Rails.logger.info "\n--- Loading extensions for #{self.class} "
Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
Rails.logger.info "Loading extension(s): #{entry}"
require_dependency "#{entry}"
end
Rails.logger.info "--- Loaded extensions for #{self.class}\n"
end
Like Johan pointed out many times its .bashrc that's needed:
ln -s .bash_profile .bashrc
I did small research regarding this topic and found different behavior for the browsers:
See my blog post "Behind refresh button" for more details.
This is taken from Romain Guy's presentation at Devoxx, pdf found here.
Paint mShadow = new Paint();
// radius=10, y-offset=2, color=black
mShadow.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// in onDraw(Canvas)
canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
Hope this helps.
NOTES
The restrict option is typically set to:
Here is the documentation link.
The complete solution I found that worked was:
@echo off
cd /D "%~dp0"
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
"Put your command here"
credit for: https://stackoverflow.com/a/51472107/15087068
var total = 0; $.each(someArray,function() { total += parseInt(this, 10); });
const countryResolver = (data = [{}]) => {
const countrySelecter = document.createElement('select');
countrySelecter.className = `custom-select`;
countrySelecter.id = `countrySelect`;
countrySelecter.setAttribute("aria-label", "Example select with button addon");
let opt = document.createElement("option");
opt.text = "Select language";
opt.disabled = true;
countrySelecter.add(opt, null);
let i = 0;
for (let item of data) {
let opt = document.createElement("option");
opt.value = item.Id;
opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
countrySelecter.add(opt, null);
}
return countrySelecter;
};
I just change the type of input to the text and back to the file :D
Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.
interface IName {
firstName: string
lastName?: string
}
function sayName(params: IName) {
const { firstName, lastName = "Smith" } = params
const fullName = `${firstName} ${lastName}`
console.log("FullName-> ", fullName)
}
sayName({ firstName: "Bob" })
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
1.include
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
2.add your youtube iframe.
<iframe id="player" src="http://www.youtube.com/embed/YOURID?rel=0&wmode=Opaque&enablejsapi=1" frameborder="0"></iframe>
3.magic time.
<script>
var player;
function onYouTubePlayerAPIReady() {player = new YT.Player('player');}
//so on jquery event or whatever call the play or stop on the video.
//to play player.playVideo();
//to stop player.stopVideo();
</script>
Here's a step by step explanation how to install MySQL and JDBC and how to use it:
Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306
.
Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).
If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.
If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp
or -classpath
argument when executing your Java application.
java -cp .;/path/to/mysql-connector.jar com.example.YourClass
The .
is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass
and the ;
is the classpath separator as it is in Windows. In Unix and clones :
should be used.
Create a database in MySQL. Let's create a database javabase
. You of course want World Domination, so let's use UTF-8 as well.
CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Create an user for Java and grant it access. Simply because using root
is a bad practice.
CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';
Yes, java
is the username and password
is the password here.
Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:
jdbc:mysql://hostname:port/databasename
hostname
: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost
. It can also be an IP address like 127.0.0.1
. If you encounter connectivity problems and using 127.0.0.1
instead of localhost
solved it, then you've a problem in your network/DNS/hosts config.
port
: The TCP/IP port where MySQL server listens on. This is by default 3306
.
databasename
: The name of the database you'd like to connect to. That's javabase
.
So the final URL should look like:
jdbc:mysql://localhost:3306/javabase
Test the connection to MySQL using Java. Create a simple Java class with a main()
method to test the connection.
String url = "jdbc:mysql://localhost:3306/javabase";
String username = "java";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
If you get a SQLException: No suitable driver
, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
Note that the newInstance()
call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver
. Explanation here. If this line throws ClassNotFoundException
, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.
Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.
If you get a SQLException: Connection refused
or Connection timed out
or a MySQL specific CommunicationsException:
Communications link failure
, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
To solve the one or the other, follow the following advices:
ping
.my.cnf
of MySQL DB.--skip-networking option
.finally
.Note that closing the Connection
is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection
in a try-with-resources
statement. Or if you're not on Java 7 yet, explicitly close it in finally
of a try-finally
block. Closing in finally
is just to ensure that it get closed as well in case of an exception. This also applies to Statement
, PreparedStatement
and ResultSet
.
That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.
Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.
I know that I'm too late for this party, but maybe - it will help to someone..
Here you can find my implementation of ObservableCollectionEx. It has some features:
Of course, any comments are appreciated ;)
Very good, clean and simple directive with shift + enter support:
app.directive('enterSubmit', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.bind('keydown', function(event) {
var code = event.keyCode || event.which;
if (code === 13) {
if (!event.shiftKey) {
event.preventDefault();
scope.$apply(attrs.enterSubmit);
}
}
});
}
}
});
It seems that the setBackground() method doesn't work well on some platforms (I'm using Windows 7). I found this answer to this question helpful. However, I didn't entirely use it to solve my problem. Instead, I decided it'd be much easier and almost as aesthetic to color a panel next to the button.
Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]
Use .AddRange
to append any Enumrable collection to the list.
You don't need jquery inside the iframe to do this, but I use it cause the code is so much simpler...
Put this in the document inside your iframe.
$(document).ready(function() {
parent.set_size(this.body.offsetHeight + 5 + "px");
});
added five above to eliminate scrollbar on small windows, it's never perfect on size.
And this inside your parent document.
function set_size(ht)
{
$("#iframeId").css('height',ht);
}
Update as of August 2020:
This is what worked for me recently -
Upload your file and get a shareable link which anyone can see(Change permission from "Restricted" to "Anyone with the Link" in the share link options)
Then run:
SHAREABLE_LINK=<google drive shareable link>
curl -L https://drive.google.com/uc\?id\=$(echo $SHAREABLE_LINK | cut -f6 -d"/")
I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].
function myFunction() {
console.log('It works!');
}
var name = 'myFunction';
window[name].call();
IDE: The MS Office of Programming. It's where you type your code, plus some added features to make you a happier programmer. (e.g. Eclipse, Netbeans). Car body: It's what you really touch, see and work on.
Library: A library is a collection of functions, often grouped into multiple program files, but packaged into a single archive file. This contains programs created by other folks, so that you don't have to reinvent the wheel. (e.g. junit.jar, log4j.jar). A library generally has a key role, but does all of its work behind the scenes, it doesn't have a GUI. Car's engine.
API: The library publisher's documentation. This is how you should use my library. (e.g. log4j API, junit API). Car's user manual - yes, cars do come with one too!
What is a kit? It's a collection of many related items that work together to provide a specific service. When someone says medicine kit, you get everything you need for an emergency: plasters, aspirin, gauze and antiseptic, etc.
SDK: McDonald's Happy Meal. You have everything you need (and don't need) boxed neatly: main course, drink, dessert and a bonus toy. An SDK is a bunch of different software components assembled into a package, such that they're "ready-for-action" right out of the box. It often includes multiple libraries and can, but may not necessarily include plugins, API documentation, even an IDE itself. (e.g. iOS Development Kit).
Toolkit: GUI. GUI. GUI. When you hear 'toolkit' in a programming context, it will often refer to a set of libraries intended for GUI development. Since toolkits are UI-centric, they often come with plugins (or standalone IDE's) that provide screen-painting utilities. (e.g. GWT)
Framework: While not the prevalent notion, a framework can be viewed as a kit. It also has a library (or a collection of libraries that work together) that provides a specific coding structure & pattern (thus the word, framework). (e.g. Spring Framework)
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as @eumiro has pointed out in comments - strftime
$("tr.item").each(function() {
$this = $(this);
var value = $this.find("span.value").html();
var quantity = $this.find("input.quantity").val();
});
I got a lot of trouble trying to reload something inside Sublime Text, but finally I could wrote this utility to reload modules on Sublime Text based on the code sublime_plugin.py
uses to reload modules.
This below accepts you to reload modules from paths with spaces on their names, then later after reloading you can just import as you usually do.
def reload_module(full_module_name):
"""
Assuming the folder `full_module_name` is a folder inside some
folder on the python sys.path, for example, sys.path as `C:/`, and
you are inside the folder `C:/Path With Spaces` on the file
`C:/Path With Spaces/main.py` and want to re-import some files on
the folder `C:/Path With Spaces/tests`
@param full_module_name the relative full path to the module file
you want to reload from a folder on the
python `sys.path`
"""
import imp
import sys
import importlib
if full_module_name in sys.modules:
module_object = sys.modules[full_module_name]
module_object = imp.reload( module_object )
else:
importlib.import_module( full_module_name )
def run_tests():
print( "\n\n" )
reload_module( "Path With Spaces.tests.semantic_linefeed_unit_tests" )
reload_module( "Path With Spaces.tests.semantic_linefeed_manual_tests" )
from .tests import semantic_linefeed_unit_tests
from .tests import semantic_linefeed_manual_tests
semantic_linefeed_unit_tests.run_unit_tests()
semantic_linefeed_manual_tests.run_manual_tests()
if __name__ == "__main__":
run_tests()
If you run for the first time, this should load the module, but if later you can again the method/function run_tests()
it will reload the tests files. With Sublime Text (Python 3.3.6
) this happens a lot because its interpreter never closes (unless you restart Sublime Text, i.e., the Python3.3
interpreter).
You can put the image in the div:after or div:before and set the opacity on that "virtual div"
div:after {
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
opacity: 0.25;
}
found here http://css-tricks.com/snippets/css/transparent-background-images/
I think you are intended to contain ALL YOUR LOGIC under your if
statement. Basically:
' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
' you want to say
' If i = 4 CONTINUE but VBScript has no continue
If i <> 4 Then ' just invert the logic
WSH.Echo( i )
End If
Next
This can make the code a bit longer, but some people don't like break
or continue
anyway.
See tables from Python string formatting to select the proper format layout. In your case it's %.2E
.
Probably the easiest and most efficient way is to use boost and the boost::filesystem functions. This way you can build a directory simply and ensure that it is platform independent.
const char* path = _filePath.c_str();
boost::filesystem::path dir(path);
if(boost::filesystem::create_directory(dir))
{
std::cerr<< "Directory Created: "<<_filePath<<std::endl;
}
I ran into this recently and running the following fixed all the problems
mvn -fae install
I've just had a very similar problem, where I couldn't get npm to work behind our proxy server.
My username is of the form "domain\username" - including the slash in the proxy configuration resulted in a forward slash appearing. So entering this:
npm config set proxy "http://domain\username:password@servername:port/"
then running this npm config get proxy
returns this:
http://domain/username:password@servername:port/
Therefore to fix the problem I instead URL encoded the backslash, so entered this:
npm config set proxy "http://domain%5Cusername:password@servername:port/"
and with this the proxy access was fixed.
Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...
Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.
With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer.
These declarations are very similar (but not the same - e.g., sizeof
will return different values):
char* a = "Hello";
char a[] = "Hello";
You can reach any element in the array like this
printf("Second char is: %c", a[1]);
Index 1 since the array starts with element 0. :-)
Or you could equally do this
printf("Second char is: %c", *(a+1));
The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:
printf("Second char is: %s", (a+1)); /* WRONG */
But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?
char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);
This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).
Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:
char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);
Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.
The to_char()
function is there to format numbers:
select to_char(column_1, 'fm000') as column_2
from some_table;
The fm
prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000
simply defines the number of digits you want to have.
psql (9.3.5) Type "help" for help. postgres=> with sample_numbers (nr) as ( postgres(> values (1),(11),(100) postgres(> ) postgres-> select to_char(nr, 'fm000') postgres-> from sample_numbers; to_char --------- 001 011 100 (3 rows) postgres=>
For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html
I was asking the same too. Another solution is you could overload your method:
void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);
in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself
void remove_id(EmployeeClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(ProductClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(DepartmentClass _obj) {
int saveId = _obj->id;
...
};
ESLint defaults to ES5 syntax-checking. You'll want to override to the latest well-supported version of JavaScript.
Try adding a .eslintrc
file to your project. Inside it:
{
"parserOptions": {
"ecmaVersion": 2017
},
"env": {
"es6": true
}
}
Hopefully this helps.
EDIT: I also found this example .eslintrc
which might help.
A void* can point to anything (it's a raw pointer without any type info).
This function will return a converted java date from SQL date object.
public static java.util.Date convertFromSQLDateToJAVADate(
java.sql.Date sqlDate) {
java.util.Date javaDate = null;
if (sqlDate != null) {
javaDate = new Date(sqlDate.getTime());
}
return javaDate;
}
I had an applicationhost.config inside my project folder. It seems IISExpress uses this folder, even though it displays a different file in my c:\users folder
.vs\config\applicationhost.config
if you are calling from static
method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
Package: System.IO.FileSystem
System.IO.File.ReadAllText("MyTextFile.txt"); ?
If you want to solve it in a two-liner you can do it like this:
with open('data.json') as f:
data = [json.loads(line) for line in f]
You have to do two steps:
url({{ URL::asset('images/slides/2.jpg') }})
where images/slides/2.jpg
is path of your content.Similarly you can call js, css etc.
Just add a new datafile for the existing tablespace
ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;
To find out the location and size of your data files:
SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';
You should not call .get() directly. Optional<>, that Stream::max
returns, was designed to benefit from .orElse... inline handling.
If you are sure your arguments have their size of 2+:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));
If you support empty lists, then return some default value, for example:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElse(new Date(Long.MIN_VALUE));
CREDITS to: @JimmyGeers, @assylias from the accepted answer.
Use the system
function.
system("myfile.sh"); // myfile.sh should be chmod +x
<script>
var listh = document.getElementById( 'list-home-list' );
var hb = document.getElementsByTagName('hb');
$("#list-home-list").click(function(){
$(this).style.color = '#2C2E33';
hb.style.color = 'white';
});
</script>
I don't think there's any way you can do it in XML layout file, and I don't think android:scaleType
attribute will work like you want it to be.
The only way would be to do it programmatically. You can set the width to fill_parent and can either take screen width as the height of the View
or can use View.getWidth()
method.
Change the Maven preferences for plugin execution from error to ignore
As @Graham42 noted, mouse option has changed in version 2.1. Scrolling now requires for you to enter copy mode first. To enable scrolling almost identical to how it was before 2.1 add following to your .tmux.conf
.
set-option -g mouse on
# make scrolling with wheels work
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M
This will enable scrolling on hover over a pane and you will be able to scroll that pane line by line.
Source: https://groups.google.com/d/msg/tmux-users/TRwPgEOVqho/Ck_oth_SDgAJ
Here the Kotlin version of Arth Tilvas answer:
fun getMacAddr(): String {
try {
val all = Collections.list(NetworkInterface.getNetworkInterfaces())
for (nif in all) {
if (!nif.getName().equals("wlan0", ignoreCase=true)) continue
val macBytes = nif.getHardwareAddress() ?: return ""
val res1 = StringBuilder()
for (b in macBytes) {
//res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:", b))
}
if (res1.length > 0) {
res1.deleteCharAt(res1.length - 1)
}
return res1.toString()
}
} catch (ex: Exception) {
}
return "02:00:00:00:00:00"
}
This will do what you want:
INSERT INTO table2 (st_id,uid,changed,status,assign_status)
SELECT st_id,from_uid,now(),'Pending','Assigned'
FROM table1
If you want to include all rows from table1. Otherwise you can add a WHERE statement to the end if you want to add only a subset of table1.
I hope this helps.
Even, I was looking for the same regex but I wanted to include the all special character and blank spaces too. So here is the regex for that:
^[A-Za-z0-9\s$&+,:;=?@#|'<>.^*()%!-]{0,10}$
WebClient client = new WebClient();
using (Stream data = client.OpenRead(Text))
{
using (StreamReader reader = new StreamReader(data))
{
string content = reader.ReadToEnd();
string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
MatchCollection matches = Regex.Matches(content,pattern);
List<string> urls = new List<string>();
foreach (Match match in matches)
{
urls.Add(match.Value);
}
}
While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.
example:
$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle
$proc.WaitForExit();
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
// This code was tested by me (Helio Barbosa)
// this directory (../backup) is for try only.
// it is necessary create it and put files into him.
$hDir = '../backup';
if ($handle = opendir( $hDir )) {
echo "Manipulador de diretório: $handle\n";
echo "Arquivos:\n";
/* Esta é a forma correta de varrer o diretório */
/* Here is the correct form to do find files into the directory */
while (false !== ($file = readdir($handle))) {
// echo($file . "</br>");
$filepath = $hDir . "/" . $file ;
// echo( $filepath . "</br>" );
if(is_file($filepath))
{
echo("Deleting:" . $file . "</br>");
unlink($filepath);
}
}
closedir($handle);
}
I had a similar problem. I needed to wait until my document was ready but also until all Ajax calls had finished. The second condition proved to be difficult to detect. In the end I checked for active Ajax calls and it worked.
Javascript:
return (document.readyState == 'complete' && jQuery.active == 0)
Full C# method:
private void WaitUntilDocumentIsReady(TimeSpan timeout)
{
var javaScriptExecutor = WebDriver as IJavaScriptExecutor;
var wait = new WebDriverWait(WebDriver, timeout);
// Check if document is ready
Func<IWebDriver, bool> readyCondition = webDriver => javaScriptExecutor
.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
wait.Until(readyCondition);
}
If anybody is looking for an option which handles nested variables, there are several such options in this github issue.
In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"
or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.
zip update.zip $(git diff --name-only commit commit)
sqrt=x**(1/2)
is doing integer division. 1/2 == 0
.
So you're computing x(1/2) in the first instance, x(0) in the second.
So it's not wrong, it's the right answer to a different question.
Guess you just missed the find method in the docs:
my_array.find {|e| e.satisfies_condition? }
My error was that I was also referencing another file in my project, which was also containing a value for the attribute "AssemblyVersion". I removed that attribute from one of the file and it is now working properly.
The key is to make sure that this value is not declared more than once in any file in your project.
To make all images on your website responsive, don't change your inline HTML from correct markup, as width:100%
doesn't work in all browsers and causes problems in Firefox. You want to place your images on your website how you normally should:
<img src="image.jpg" width="1200px" height="600px" />
And then add to your CSS that any image max-width is 100% with height set to auto:
img {
max-width: 100%;
height: auto;
}
That way your code works in all browsers. It will also work with custom CMS clients (i.e. Cushy CMS) that require images to have the actual image size coded into the inline HTML, and it is actually easier this way when all you need to do to make images responsive is simply state in your CSS file that the max-width is 100% with height set to auto. Don't forget height: auto
or your images will not scale properly.
I think the answer is there but only in bits and pieces, which makes it difficult to quickly fix the problem such as
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2818: ordinal not in range(128)
Let's take an example, Suppose I have file which has some data in the following form ( containing ascii and non-ascii chars )
1/10/17, 21:36 - Land : Welcome ��
and we want to ignore and preserve only ascii characters.
This code will do:
import unicodedata
fp = open(<FILENAME>)
for line in fp:
rline = line.strip()
rline = unicode(rline, "utf-8")
rline = unicodedata.normalize('NFKD', rline).encode('ascii','ignore')
if len(rline) != 0:
print rline
and type(rline) will give you
>type(rline)
<type 'str'>
It's not possible to achieve the required level of control over presentation in a regular textarea
.
If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).
From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors
This function will return you image with black border try this.. hope this will help you
- (UIImage *)addBorderToImage:(UIImage *)image frameImage:(UIImage *)blackBorderImage
{
CGSize size = CGSizeMake(image.size.width,image.size.height);
UIGraphicsBeginImageContext(size);
CGPoint thumbPoint = CGPointMake(0,0);
[image drawAtPoint:thumbPoint];
UIGraphicsBeginImageContext(size);
CGImageRef imgRef = blackBorderImage.CGImage;
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width,size.height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGPoint starredPoint = CGPointMake(0, 0);
[imageCopy drawAtPoint:starredPoint];
UIImage *imageC = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageC;
}
I'm sure the original poster's issue has long since been resolved. However, I had this same issue, so I thought I'd explain what was causing this problem for me.
I was doing a union query with two tables -- 'foo' and 'foo_bar'. However, in my SQL statement, I had a typo: 'foo.bar'
So, instead of telling me that the 'foo.bar' table doesn't exist, the error message indicates that the command was denied -- as though I don't have permissions.
Hope this helps someone.
It's possible to change the path fill color of the svg. See below for the CSS snippet:
To apply the color for all the path: svg > path{ fill: red }
To apply for the first d path: svg > path:nth-of-type(1){ fill: green }
To apply for the second d path: svg > path:nth-of-type(2){ fill: green}
To apply for the different d path, change only the path number:
svg > path:nth-of-type(${path_number}){ fill: green}
To support the CSS in Angular 2 to 8, use the encapsulation concept:
:host::ng-deep svg path:nth-of-type(1){
fill:red;
}
This is how to pass the struct
by reference. This means that your function can access the struct
outside of the function and modify its values. You do this by passing a pointer to the structure to the function.
#include <stdio.h>
/* card structure definition */
struct card
{
int face; // define pointer face
}; // end structure card
typedef struct card Card ;
/* prototype */
void passByReference(Card *c) ;
int main(void)
{
Card c ;
c.face = 1 ;
Card *cptr = &c ; // pointer to Card c
printf("The value of c before function passing = %d\n", c.face);
printf("The value of cptr before function = %d\n",cptr->face);
passByReference(cptr);
printf("The value of c after function passing = %d\n", c.face);
return 0 ; // successfully ran program
}
void passByReference(Card *c)
{
c->face = 4;
}
This is how you pass the struct
by value so that your function receives a copy of the struct
and cannot access the exterior structure to modify it. By exterior I mean outside the function.
#include <stdio.h>
/* global card structure definition */
struct card
{
int face ; // define pointer face
};// end structure card
typedef struct card Card ;
/* function prototypes */
void passByValue(Card c);
int main(void)
{
Card c ;
c.face = 1;
printf("c.face before passByValue() = %d\n", c.face);
passByValue(c);
printf("c.face after passByValue() = %d\n",c.face);
printf("As you can see the value of c did not change\n");
printf("\nand the Card c inside the function has been destroyed"
"\n(no longer in memory)");
}
void passByValue(Card c)
{
c.face = 5;
}
Well Lorenz Lo Sauer already have a good question for this. but if you want to resolve this problem through the Pycharm Tuning (without turning off Pycharm code inspection). you can tuning the heap size as you need. since I prefer to use increasing Heap Size solution for slow running Pycharm Application.
You can tune up Heap Size by editing pycharm.exe.vmoptions file. and pycharm64.exe.vmoptions for 64bit application. and then edit -Xmx and -Xms value on it.
So I allocate 2048m for xmx and xms value (which is 2GB) for my Pycharm Heap Size. Here it is My Configuration. I have 8GB memory so I had set it up with this setting:
-server
-Xms2048m
-Xmx2048m
-XX:MaxPermSize=2048m
-XX:ReservedCodeCacheSize=2048m
save the setting, and restart IDE. And I enable "Show memory indicator" in settings->Appearance & Behavior->Appearance. to see it in action :
and Pycharm is quick and running fine now.
Reference : https://www.jetbrains.com/help/pycharm/2017.1/tuning-pycharm.html#d176794e266
Learn about CORS, try crossorigin.me
is work fine
Example: https://crossorigin.me/https://fr.s.us/js/jquery-ui.css
Not show a message error and continue page white, u need see error is try
http://cors.io/?u=https://fr.s.us/js/jquery-ui.css
enjoin us ;-)
The simplest way to sidestep this limitation is to switch to 64 bit R.
When you're working with strings in PHP you'll need to pay special attention to the formation, using "
or '
$string = 'Hello, world!';
$string = "Hello, world!";
Both of these are valid, the following is not:
$string = "Hello, world';
You must also note that '
inside of a literal started with "
will not end the string, and vice versa. So when you have a string which contains '
, it is generally best practice to use double quotation marks.
$string = "It's ok here";
Escaping the string is also an option
$string = 'It\'s ok here too';
More information on this can be found within the documentation
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
For C
/C++
programs there's very good package gpp-compiler.
Shortcuts:
F5
F6
None of these solutions has helped me in my Electron App.
My solution (workaround):
npm install jquery
In your index.js
file:
var jQuery = $ = require('jquery');
In your .js
files write yours jQuery functions in this way:
jQuery(document).ready(function() {
The reason the code isn't working is because lastrow is measured from whatever sheet is currently active, and "A:A500" (or other number) is not a valid range reference.
Private Sub CommandButton1_Click()
Dim lastrow As Long
lastrow = Sheets("Summary Info").Range("A65536").End(xlUp).Row ' or + 1
Range("A3:E3").Copy Destination:=Sheets("Summary Info").Range("A" & lastrow)
End Sub
In Python 3.x, you need to import urllib.parse.quote
:
>>> import urllib.parse
>>> urllib.parse.quote("châteu", safe='')
'ch%C3%A2teu'
According to Python 2.x urllib
module documentation:
NOTE
The
urllib
module has been split into parts and renamed in Python 3 tourllib.request
,urllib.parse
, andurllib.error
.
What about using the Double(String) constructor? So,
protein = new Double(p);
Don't know why it would be different, but might be worth a shot.
You can use the standard HTTP_PROXY
environment var. Simply set it to the URL of your proxy. Many operating systems already set this variable for you.
Just export the variable, then you don't have to type it all the time.
export HTTP_PROXY="http://johndoeproxy.cu:8080"
Then you can do composer update
normally.
An alias will expand to the string it represents. Anything after the alias will appear after its expansion without needing to be or able to be passed as explicit arguments (e.g. $1
).
$ alias foo='/path/to/bar'
$ foo some args
will get expanded to
$ /path/to/bar some args
If you want to use explicit arguments, you'll need to use a function
$ foo () { /path/to/bar "$@" fixed args; }
$ foo abc 123
will be executed as if you had done
$ /path/to/bar abc 123 fixed args
To undefine an alias:
unalias foo
To undefine a function:
unset -f foo
To see the type and definition (for each defined alias, keyword, function, builtin or executable file):
type -a foo
Or type only (for the highest precedence occurrence):
type -t foo
If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.
Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.
In your case it could be :
objContentLine = (from q in db.qryContents
where q.LineID == Value
orderby q.RowID descending
select q).FirstOrDefault();
Errors:
Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type
Error 242 Delegate 'System.Func<..>' does not take 1 arguments
Error 243 The name 'Value' does not exist in the current context
Fix the "Value" variable error and the other errors will also disappear.
From the documentation
Note that
filter(function, iterable)
is equivalent to[item for item in iterable if function(item)]
In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3
Clearly, you are getting a filter object, make it a list.
shesaid = list(filter(greetings(), ["hello", "goodbye"]))
You could also type 'conda list' in a command line. This will print out the installed modules with the version numbers. The path within your file structure will be printed at the top of this list.
Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch
from props, do not pass mapDispatchToProps
function to connect
.
class ModalContainer extends React.Component {
handleDelete = () => {
const { dispatch, onClose } = this.props;
dispatch({type: 'DELETE_POST'});
someAsyncOperation().then(() => {
dispatch({type: 'DELETE_POST_SUCCESS'});
onClose();
})
}
render() {
const { onClose } = this.props;
return <Modal onClose={onClose} onSubmit={this.handleDelete} />
}
}
export default connect(/* no map dispatch to props here! */)(ModalContainer);
The App where the modal is rendered and its visibility state is set:
class App extends React.Component {
state = {
isModalOpen: false
}
handleModalClose = () => this.setState({ isModalOpen: false });
...
render(){
return (
...
<ModalContainer onClose={this.handleModalClose} />
...
)
}
}
Have you tried the import text function.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)
.profile-header > div {
display: inline-block;
vertical-align: bottom;
float: none;
margin: -2px;
}
.profile-header {
margin-bottom:20px;
border:2px solid green;
display: table-cell;
}
.profile-pic {
height:300px;
border:2px solid red;
}
.profile-about {
border:2px solid blue;
}
.profile-about2 {
border:2px solid pink;
}
Example here: http://www.bootply.com/125740#
If it is a normal then the port number is always 80 and may be written as http://www.somewhere.com:80 Though you don't need to specify it as :80 is the default of every web browser.
If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin.
If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in https://something.somewhere.com:nn Then your isp or their antivirus will probably notice and disconnect you.
Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:
ImageView iv = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
iv.draw(canvas);
Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.
You need to declare @font-face
like this in your stylesheet
@font-face {
font-family: 'Awesome-Font';
font-style: normal;
font-weight: 400;
src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}
Now if you want to apply this font to a paragraph simply use it like this..
p {
font-family: 'Awesome-Font', Arial;
}
This works:
SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1
Here's yet another solution, using the XOM library, that competes with my dom4j answer. (This is part of my quest to find a good dom4j replacement where XOM was suggested as one option.)
First read the XML fragment into a nu.xom.Document
:
String newNode = "<node>value</node>"; // Convert this to XML
Document newNodeDocument = new Builder().build(newNode, "");
Then, get the Document and the Node under which the fragment is added. Again, for testing purposes I'll create the Document from a string:
Document originalDoc = new Builder().build("<root><given></given></root>", "");
Element givenNode = originalDoc.getRootElement().getFirstChildElement("given");
Now, adding the child node is simple, and similar as with dom4j (except that XOM doesn't let you add the original root element which already belongs to newNodeDocument
):
givenNode.appendChild(newNodeDocument.getRootElement().copy());
Outputting the document yields the correct result XML (and is remarkably easy with XOM: just print the string returned by originalDoc.toXML()
):
<?xml version="1.0"?>
<root><given><node>value</node></given></root>
(If you wanted to format the XML nicely (with indentations and linefeeds), use a Serializer
; thanks to Peter Štibraný for pointing this out.)
So, admittedly this isn't very different from the dom4j solution. :) However, XOM may be a little nicer to work with, because the API is better documented, and because of its design philosophy that there's one canonical way for doing each thing.
Appendix: Again, here's how to convert between org.w3c.dom.Document
and nu.xom.Document
. Use the helper methods in XOM's DOMConverter
class:
// w3c -> xom
Document xomDoc = DOMConverter.convert(w3cDoc);
// xom -> w3c
org.w3c.dom.Document w3cDoc = DOMConverter.convert(xomDoc, domImplementation);
// You can get a DOMImplementation instance e.g. from DOMImplementationRegistry
You can use the report process status ps
command:
ps ax | grep '[m]ysqld'
If you want to convert from char to int, why not think about unicode number?
SELECT UNICODE(';') -- 59
This way you can convert any char to int without any error. Cheers.
Use FromResult Method
public async Task<string> GetString()
{
System.Threading.Thread.Sleep(5000);
return await Task.FromResult("Hello");
}