Simply Enter Esc and type m it will convert to text cell.
Check whether you are actually under a github repo.
So, listing of .git/ should give you results..otherwise you may be some level outside your repo.
Now, cd to your repo and you are good to go.
The map
function can be very useful here.
Using map
we can apply any function to each element of an iterable.
Python 3.x
>>> def my_mul(x,y):
... return x*y
...
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>>
>>> list(map(my_mul,a,b))
[2, 6, 12, 20]
>>>
Of course:
map(f, iterable)
is equivalent to
[f(x) for x in iterable]
So we can get our solution via:
>>> [my_mul(x,y) for x, y in zip(a,b)]
[2, 6, 12, 20]
>>>
In Python 2.x map()
means: apply a function to each element of an iterable and construct a new list.
In Python 3.x, map
construct iterators instead of lists.
Instead of my_mul
we could use mul
operator
Python 2.7
>>>from operator import mul # import mul operator
>>>a = [1,2,3,4]
>>>b = [2,3,4,5]
>>>map(mul,a,b)
[2, 6, 12, 20]
>>>
Python 3.5+
>>> from operator import mul
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>> [*map(mul,a,b)]
[2, 6, 12, 20]
>>>
Please note that since map()
constructs an iterator we use *
iterable unpacking operator to get a list.
The unpacking approach is a bit faster then the list
constructor:
>>> list(map(mul,a,b))
[2, 6, 12, 20]
>>>
I suggest using the official pkg on Mac. I guess docker-compose is no longer included with docker by default: https://docs.docker.com/toolbox/toolbox_install_mac/
Just figured out the reason when we type "ng serve" INSIDE OUR PROJECT..
for example C:\Users\EdgeTech1\Desktop\CSharp\WebAPI\MyProject>ng serve
could not resolve module C:\Users\EdgeTech1\Desktop\C
results: failed compiled
root cause:
My folder name was C# Project..
Note: I tried to remove the #
in my Project Name, I rename C# Project
to CSharp
instead and I tried to open cmd
prompt again, typed the same thing..
for example:
C:\Users\EdgeTech1\Desktop\CSharp\WebAPI\MyProject>ng serve
and my project compiled successfully.. so as much as possible avoid ASCII characters in naming projects files.
I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project
. Instead of creating objects using new operator
you can also use static method
to instantiate a class. Code listing:
//instantiating a class using constructor
Vinoth vin = new Vinoth();
//instantiating the class using static method
Class Vinoth{
private Vinoth(){
}
// factory method to instantiate the class
public static Vinoth getInstance(){
if(someCondition)
return new Vinoth();
}
}
Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.
Another example taken from Effective Java.
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean)
method illustrates us, it never creates an object. The ability of static factory methods
to return the same object from repeated invocations
allows classes to maintain strict control over what instances exist at any time.
Static factory methods
is that, unlike constructors
, they can return an object
of any subtype
of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.
Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar
, JapaneseImperialCalendar
or by default one Georgian
.
Another example which i could think is Singleton pattern
, where you make your constructors private create an own getInstance
method where you make sure, that there is always just one instance available.
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
That SSL error is misleading. I am using Anaconda 3, conda version 4.6.11, have the most current version of openssl on a Windows 10 instance. I got the issue resolved by changing the security settings on the Anaconda3 folder to Full Control. Don't think this helped, but I also have modified the ..\Anaconda3\Lib\site-packages\certifi\cacert.pem file to include the company's SSL cert.
Hope this info helps you.
You can use multiple way based on sitaution:
If you Variable is limited to specific Number or String, best way is using ngSwitch or ngIf:
<!-- foo = 3 -->
<div [ngSwitch]="foo">
<div *ngSwitchCase="1">First Number</div>
<div *ngSwitchCase="2">Second Number</div>
<div *ngSwitchCase="3">Third Number</div>
<div *ngSwitchDefault>Other Number</div>
</div>
<!-- foo = 3 -->
<ng-template [ngIf]="foo === 1">First Number</ng-template>
<ng-template [ngIf]="foo === 2">Second Number</ng-template>
<ng-template [ngIf]="foo === 3">Third Number</ng-template>
<!-- foo = 'David' -->
<div [ngSwitch]="foo">
<div *ngSwitchCase="'Daniel'">Daniel String</div>
<div *ngSwitchCase="'David'">David String</div>
<div *ngSwitchCase="'Alex'">Alex String</div>
<div *ngSwitchDefault>Other String</div>
</div>
<!-- foo = 'David' -->
<ng-template [ngIf]="foo === 'Alex'">Alex String</ng-template>
<ng-template [ngIf]="foo === 'David'">David String</ng-template>
<ng-template [ngIf]="foo === 'Daniel'">Daniel String</ng-template>
Above not suitable for if elseif else codes and dynamic codes, you can use below code:
<!-- foo = 5 -->
<ng-container *ngIf="foo >= 1 && foo <= 3; then t13"></ng-container>
<ng-container *ngIf="foo >= 4 && foo <= 6; then t46"></ng-container>
<ng-container *ngIf="foo >= 7; then t7"></ng-container>
<!-- If Statement -->
<ng-template #t13>
Template for foo between 1 and 3
</ng-template>
<!-- If Else Statement -->
<ng-template #t46>
Template for foo between 4 and 6
</ng-template>
<!-- Else Statement -->
<ng-template #t7>
Template for foo greater than 7
</ng-template>
Note: You can choose any format, but notice every code has own problems
You can convert it to a string, and then to an int:
print(int("".join(str(x) for x in [7,7,7,7])))
Here is a sample code
strFileName = "c:\test.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)
objExcel.Quit
The volatile
and transient
modifiers can be applied to fields of classes1 irrespective of field type. Apart from that, they are unrelated.
The transient
modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null
for a reference type, and zero or false
for a primitive type. Note that the JLS (see 8.3.1.3) does not say what transient
means, but defers to the Java Object Serialization Specification. Other serialization mechanisms may pay attention to a field's transient
-ness. Or they may ignore it.
(Note that the JLS permits a static
field to be declared as transient
. This combination doesn't make sense for Java Object Serialization, since it doesn't serialize statics anyway. However, it could make sense in other contexts, so there is some justification for not forbidding it outright.)
The volatile
modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. Similarly, reads and writes to volatile fields are atomic. (This does not apply to >>non-volatile<< long
or double
fields, which may be subject to "word tearing" on some JVMs.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.
1 - But not to local variables or parameters.
The first one generates numbers in the wrong range, while the second one is correct.
To show that the first one is incorrect, let's say min
is 10 and max
is 20. In other words, the result is expected to be greater than or equal to ten, and strictly less than twenty. If Math.random()
returns 0.75
, the result of the first formula is 25
, which is outside the range.
If you simply want to create a new branch without immediately changing to it, you could do the following:
git branch newbranch v1.0
A code that works for any sign in dividend and divisor:
int divRoundClosest(const int n, const int d)
{
return ((n < 0) ^ (d < 0)) ? ((n - d/2)/d) : ((n + d/2)/d);
}
In response to a comment "Why is this actually working?", we can break this apart. First, observe that n/d
would be the quotient, but it is truncated towards zero, not rounded. You get a rounded result if you add half of the denominator to the numerator before dividing, but only if numerator and denominator have the same sign. If the signs differ, you must subtract half of the denominator before dividing. Putting all that together:
(n < 0) is false (zero) if n is non-negative
(d < 0) is false (zero) if d is non-negative
((n < 0) ^ (d < 0)) is true if n and d have opposite signs
(n + d/2)/d is the rounded quotient when n and d have the same sign
(n - d/2)/d is the rounded quotient when n and d have opposite signs
If you prefer a macro:
#define DIV_ROUND_CLOSEST(n, d) ((((n) < 0) ^ ((d) < 0)) ? (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(d)))
The linux kernel macro DIV_ROUND_CLOSEST doesn't work for negative divisors!
EDIT: This will work without overflow:
int divRoundClosest( int A, int B )
{
if(A<0)
if(B<0)
return (A + (-B+1)/2) / B + 1;
else
return (A + ( B+1)/2) / B - 1;
else
if(B<0)
return (A - (-B+1)/2) / B - 1;
else
return (A - ( B+1)/2) / B + 1;
}
All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value;
inside the function function kk()
.
What I suggest is, you may call that variable from another function fun_inside()
function fun_inside()
{
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}
It can be useful when you built complex projects.
You don't encode the entire URL, only parts of it that come from "unreliable sources".
Java:
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
Kotlin:
val query: String = URLEncoder.encode("apples oranges", "utf-8")
val url = "http://stackoverflow.com/search?q=$query"
Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.
Or use something like
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
I'm using the following in VC++ and it works like a charm for me.
CA2CT(charText)
The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:
a) The IP/domain or port is incorrect
b) The IP/domain or port (i.e service) is down
c) The IP/domain is taking longer than your default timeout to respond
d) You have a firewall that is blocking requests or responses on whatever port you are using
e) You have a firewall that is blocking requests to that particular host
f) Your internet access is down
g) Your live-server is down i.e in case of "rest-API call".
Note that firewalls and port or IP blocking may be in place by your ISP
The easiest way is to use os module
>>> import os
>>> clear = lambda: os.system('clear')
>>> clear()
As long as you aren't using the NDK you can just ignore that warning.
By the way: This warning has nothing to do with parallel installations.
Try this
For only ec2:
from skew import scan
arn = scan('arn:aws:ec2:us-west-2:123456789012:instance/i-12345678')
for resource in arn:
print(resource.data)
For all resources:
arn = scan('arn:aws:*:*:<<youraccountId>>:instance*')
for resource in arn:
print(resource.data)
Reference : https://github.com/scopely-devops/skew
There is no inbuilt solution to this problem, this is a problem with your design and coding pattern.
You can use publisher/subscriber pattern. For this you can use jQuery custom events or your own event mechanism.
First,
function changeHtml(selector, html) {
var elem = $(selector);
jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
elem.html(html);
jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
}
Now you can subscribe divhtmlchanging/divhtmlchanged events as follow,
$(document).bind('htmlchanging', function (e, data) {
//your before changing html, logic goes here
});
$(document).bind('htmlchanged', function (e, data) {
//your after changed html, logic goes here
});
Now, you have to change your div content changes through this changeHtml()
function. So, you can monitor or can do necessary changes accordingly because bind callback data argument containing the information.
You have to change your div's html like this;
changeHtml('#mydiv', '<p>test content</p>');
And also, you can use this for any html element(s) except input element. Anyway you can modify this to use with any element(s).
C++11 offers std::normal_distribution
, which is the way I would go today.
Here are some solutions in order of ascending complexity:
Add 12 uniform random numbers from 0 to 1 and subtract 6. This will match mean and standard deviation of a normal variable. An obvious drawback is that the range is limited to ±6 – unlike a true normal distribution.
The Box-Muller transform. This is listed above, and is relatively simple to implement. If you need very precise samples, however, be aware that the Box-Muller transform combined with some uniform generators suffers from an anomaly called Neave Effect1.
For best precision, I suggest drawing uniforms and applying the inverse cumulative normal distribution to arrive at normally distributed variates. Here is a very good algorithm for inverse cumulative normal distributions.
1. H. R. Neave, “On using the Box-Muller transformation with multiplicative congruential pseudorandom number generators,” Applied Statistics, 22, 92-97, 1973
Perhaps this will work?
<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
<c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>
You can use find
and -exec
directly into sed
rather than first locating oldstr
with grep
. It's maybe a bit less efficient, but that might not be important. This way, the sed
replacement is executed over all files listed by find
, but if oldstr
isn't there it obviously won't operate on it.
find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;
strace
The quickest way to see live MySQL/MariaDB queries is to use debugger. On Linux you can use strace
, for example:
sudo strace -e trace=read,write -s 2000 -fp $(pgrep -nf mysql) 2>&1
Since there are lot of escaped characters, you may format strace's output by piping (just add |
between these two one-liners) above into the following command:
grep --line-buffered -o '".\+[^"]"' | grep --line-buffered -o '[^"]*[^"]' | while read -r line; do printf "%b" $line; done | tr "\r\n" "\275\276" | tr -d "[:cntrl:]" | tr "\275\276" "\r\n"
So you should see fairly clean SQL queries with no-time, without touching configuration files.
Obviously this won't replace the standard way of enabling logs, which is described below (which involves reloading the SQL server).
dtrace
Use MySQL probes to view the live MySQL queries without touching the server. Example script:
#!/usr/sbin/dtrace -q
pid$target::*mysql_parse*:entry /* This probe is fired when the execution enters mysql_parse */
{
printf("Query: %s\n", copyinstr(arg1));
}
Save above script to a file (like watch.d
), and run:
pfexec dtrace -s watch.d -p $(pgrep -x mysqld)
Learn more: Getting started with DTracing MySQL
See this answer.
Here are the steps useful for development proposes.
Add these lines into your ~/.my.cnf
or global my.cnf
:
[mysqld]
general_log=1
general_log_file=/tmp/mysqld.log
Paths: /var/log/mysqld.log
or /usr/local/var/log/mysqld.log
may also work depending on your file permissions.
then restart your MySQL/MariaDB by (prefix with sudo
if necessary):
killall -HUP mysqld
Then check your logs:
tail -f /tmp/mysqld.log
After finish, change general_log
to 0
(so you can use it in future), then remove the file and restart SQL server again: killall -HUP mysqld
.
Divide $percentage
by 100 and multiply to $totalWidth
. Simple maths.
This post is right from SAP on Sep 20, 2012.
In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.
If you want to download that version you can find it here.
Further, service packs etc. when released can be found here.
I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
What about:
@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof
:concat
set myvar=%myvar% %1;
goto :eof
All I needed was to expose the keyboard, in a very precise moment. This worked for me! Thanks Benites.
private Handler mHandler= new Handler();
And in the very precise moment:
mHandler.post(
new Runnable() {
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
yourEditText.requestFocus();
}
});
I think you’re misreading the message — your branch isn’t ahead of master
, it is master
. It’s ahead of origin/master
, which is a remote tracking branch that records the status of the remote repository from your last push
, pull
, or fetch
. It’s telling you exactly what you did; you got ahead of the remote and it’s reminding you to push.
Decimal. If you choose double you're leaving yourself open to rounding errors
We are running Linux, a mostly POSIX-compliant OS. POSIX standards it should be: Utility Argument Syntax.
-o
. -o argument
or
-oargument
. -lst
is equivalent to -t -l -s
.-lst
is equivalent to -tls
.-lst
nonoption.--
argument terminates options.-
option is typically used to represent one of the standard input
streams.I found in a class file outside the scope of the Page, the above way (which I always have used) didn't work.
I found a workaround in this "context" as follows:
HttpContext.Current.Session.Add("currentUser", appUser);
and
(AppUser) HttpContext.Current.Session["currentUser"]
Otherwise the compiler was expecting a string when I pointed the object at the session object.
I think vscode is using autopep8 to format .py
by default.
"PEP 8 -- Style Guide for Python Code | Python.org"
According to this website, the following may explain why vscode always use 4 spaces.
Use 4 spaces per indentation level.
Since your list is already in ascending order, we can simply reverse the list.
>>> timestamps.reverse()
>>> timestamps
['2010-04-20 10:25:38',
'2010-04-20 10:12:13',
'2010-04-20 10:12:13',
'2010-04-20 10:11:50',
'2010-04-20 10:10:58',
'2010-04-20 10:10:37',
'2010-04-20 10:09:46',
'2010-04-20 10:08:22',
'2010-04-20 10:08:22',
'2010-04-20 10:07:52',
'2010-04-20 10:07:38',
'2010-04-20 10:07:30']
use the val() function
Even in base Python you can do the computation in generic form
result = sum(x**2 for x in some_vector) ** 0.5
x ** 2
is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).
Using instead x ** 0.5
to take the square root doesn't do the exact same computations as math.sqrt
as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.
I often use x ** 0.5
simply because I don't want to add math
just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.
This one covers all possibilities! (dot in the path or not; with extension or no extension):
tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*});echo $filename_noextension
Notes:
$filename_noextension
variable.$tmp1
and $tmp2
. Make sure you are not using them in your script.examples to test:
filename=.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=.bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=~/.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=~/.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=~/bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
filename=~/bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"
I think the only way is by using internel PHP code like MANOJ and Fernando suggest.
curl post/get in php file on your server --> call this php file with ajax
The PHP file let say (fb.php):
$commentdata=$_GET['commentdata'];
$fbUrl="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
curl_setopt($ch, CURLOPT_URL,$fbUrl);
curl_setopt($ch, CURLOPT_POST, 1);
// POST data here
curl_setopt($ch, CURLOPT_POSTFIELDS,
"message=".$commentdata);
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);
Than use AJAX GET to
fb.php?commentmeta=your comment goes here
from your server.
Or do this with simple HTML and JavaScript from externel server:
Message: <input type="text" id="message">
<input type="submit" onclick='PostMessage()'>
<script>
function PostMessage() {
var comment = document.getElementById('message').value;
window.location.assign('http://yourdomain.tld/fb.php?commentmeta='+comment)
}
</script>
As myJSON
is an object you can just set its properties, for example:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
myJSON.list1.push("3");
put the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t
Based on K3N answer, I rewrite code generally for anyone wants
var oc = document.createElement('canvas'), octx = oc.getContext('2d');
oc.width = img.width;
oc.height = img.height;
octx.drawImage(img, 0, 0);
while (oc.width * 0.5 > width) {
oc.width *= 0.5;
oc.height *= 0.5;
octx.drawImage(oc, 0, 0, oc.width, oc.height);
}
oc.width = width;
oc.height = oc.width * img.height / img.width;
octx.drawImage(img, 0, 0, oc.width, oc.height);
UPDATE JSFIDDLE DEMO
Here is my ONLINE DEMO
How about giving the port number while invoking the command without need to change anything in your application code or environment files? That way it is possible running and serving same code base from several different ports.
like:
$ export PORT=4000 && npm start
You can put the port number you like in place of the example value 4000
above.
In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :
//query is your json
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy=");
StringEntity input = new StringEntity(query, "UTF-8");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response=response = httpClient.execute(postRequest);
Using the simple app.run()
from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.
Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.
That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).
Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.
If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):
#!/bin/bash
TABLES=$(mdb-tables -1 $1)
MUSER="root"
MPASS="yourpassword"
MDB="$2"
MYSQL=$(which mysql)
for t in $TABLES
do
$MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done
mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB
for t in $TABLES
do
mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done
To invoke it simply call it like this:
./mdbconvert.sh accessfile.mdb mysqldatabasename
It will import all tables and all data.
If the script does its job (relatively) well, then it's running okay. Your problem is probably a single line in the file referencing a program that's either not on the path, not installed, misspelled, or something similar.
One way is to place a set -x
at the top of your script or run it with bash -x
instead of just bash
- this will output the lines before executing them and you usually just need to look at the command output immediately before the error to see what's causing the problem
If, as you say, it's the blank lines causing the problems, you might want to check what's actaully in them. Run:
od -xcb testscript.sh
and make sure there's no "invisible" funny characters like the CTRL-M
(carriage return) you may get by using a Windows-type editor.
Don't agree with post above. I have a Hero with only English available and I want Spanish.
I installed MoreLocale 2, and it has lots of different languages (Dutch among them). I choose Spanish, Sense UI restarted and EVERYTHING in my phone changed to Spanish: menus, settings, etc. The keyboard predictive text defaulted to Spanish and started suggesting words in Spanish. This means, somewhere within the OS there is a Spanish dictionary hidden and MoreLocale made it available.
The problem is that English is still the only option available in keyboard input language so I can switch to English but can't switch back to Spanish unless I restart Sense UI, which takes a couple of minutes so not a very practical solution.
Still looking for an easier way to do it so please help.
On my mac running Catalina v10.15.2, I had the following MySQLdb version conflict:
ImportError: this is MySQLdb version (1, 2, 5, 'final', 1), but _mysql is version (1, 4, 6, 'final', 0)
To resolve it, I did the following:
pip uninstall MySQL-python
pip install MySQL-python
As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.
foreach (var tempClass in macroClasses)
{
// using reflection I will be able to run the method as:
tempClass.GetMethod("Run").Invoke(null, null);
}
As the comment points out, you may want to ensure the method is static when calling GetMethod
:
tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
Camel sends messages from A to B:
Why a whole framework for this? Well, what if you have:
ftp
, http
, jms
, etc.)So now you need:
Camel gives you the above (and more) out of the box:
with a cool DSL language for you to define the what and how:
new DefaultCamelContext().addRoutes(new RouteBuilder() {
public void configure() {
from("jms:incomingMessages")
.choice() // start router rules
.when(header("CamelFileName")
.endsWith(".xml"))
.to("jms:xmlMessages")
.when(header("CamelFileName")
.endsWith(".csv"))
.to("ftp:csvMessages");
}
See also this and this and Camel in Action (as others have said, an excellent book!)
Since Bootstrap 3 doesn't have a style for checkboxes I found a custom made that goes really well with Bootstrap style.
.checkbox label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 15%;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default checkbox -->_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="">_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option one_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked checkbox -->_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="" checked>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option two is checked by default_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled checkbox -->_x000D_
<div class="checkbox disabled">_x000D_
<label>_x000D_
<input type="checkbox" value="" disabled>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option three is disabled_x000D_
</label>_x000D_
</div>
_x000D_
.checkbox label:after,_x000D_
.radio label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 13%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default radio -->_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="">_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option one_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked radio -->_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" checked>_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option two is checked by default_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled radio -->_x000D_
<div class="radio disabled">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" disabled>_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option three is disabled_x000D_
</label>_x000D_
</div>
_x000D_
You can choose your own icon between the ones from Bootstrap or Font Awesome by changing [icon name]
with your icon.
<span class="cr"><i class="cr-icon [icon name]"></i>
For example:
glyphicon glyphicon-remove
for Bootstrap, orfa fa-bullseye
for Font Awesome.checkbox label:after,_x000D_
.radio label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 15%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="" checked>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-remove"></i></span>_x000D_
Bootstrap - Custom icon checkbox_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" checked>_x000D_
<span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
Font Awesome - Custom icon radio checked by default_x000D_
</label>_x000D_
</div>_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="">_x000D_
<span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
Font Awesome - Custom icon radio_x000D_
</label>_x000D_
</div>
_x000D_
You can have a look at the EL (expression language) description here.
Both your code are correct, but I prefer the second one, as comparing a boolean to true
or false
is redundant.
For better readibility, you can also use the not
operator:
<c:if test="${not theBooleanVariable}">It's false!</c:if>
Using groupby
you could split into two dataframes like
In [1047]: df1, df2 = [x for _, x in df.groupby(df['Sales'] < 30)]
In [1048]: df1
Out[1048]:
A Sales
2 7 30
3 6 40
4 1 50
In [1049]: df2
Out[1049]:
A Sales
0 3 10
1 4 20
If there is space between the letters of the font, you need to use quote.
font-family:"Calibri (Body)";
I've tried the above answers but could not get them to work. The only code that worked for me was $window.location.search = ''
You can't have duplicated keys in a dictionary. Use a dict of lists:
for line in data_list:
regNumber = line[0]
name = line[1]
phoneExtn = line[2]
carpark = line[3].strip()
details = (name,phoneExtn,carpark)
if not data_dict.has_key(regNumber):
data_dict[regNumber] = [details]
else:
data_dict[regNumber].append(details)
This one worked for me.
public void RestrictNumbersOnly(TextField tf){
tf.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (!newValue.matches("|[-\\+]?|[-\\+]?\\d+\\.?|[-\\+]?\\d+\\.?\\d+")){
tf.setText(oldValue);
}
}
});
}
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
This has worked for me in turning "//"
into just "/"
.
str.replace(/\/\//g, '/');
A short solution without libraries at all. :)
d = "8/16/18"
day_value = d[(d.find('/')+1):d.find('/18')]
tomorrow = f"{d[0:d.find('/')]}/{int(day_value)+1}{d[d.find('/18'):len(d)]}".format()
print(tomorrow)
# 8/17/18
Make sure that "string d" is actually in the form of %m/%d/%Y
so that you won't have problems transitioning from one month to the next.
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Open eclipse go to Servers panel, right click or press F3 to open Overview window and go to Ports (Modify the server ports). You will get the following:
tomcat adminport
HTTP/1.1
AJP/1.3
You can change the port numbers (e.g. HTTP/1.1 port number 8080 to 8082).
Use parse_url()
like this:
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
}
Here is another shorter option:
function url(){
$pu = parse_url($_SERVER['REQUEST_URI']);
return $pu["scheme"] . "://" . $pu["host"];
}
Use below code:
// Variable to check
$email = "[email protected]";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("Email is a valid email address");
} else {
echo("Oppps! Email is not a valid email address");
}
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>
I've simply added
jQuery.browser = {
msie: false,
version: 0
};
after jquery script, because I don't care about IE anymore.
From http://www.sqlite.org/lang_createtable.html:
CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
What about this?
edit user's .bashprofile
adding:
export LAST_DAY_OF_MONTH=$(cal | awk '!/^$/{ print $NF }' | tail -1)
Then add this entry to crontab:
mm hh * * 1-7 [[ $(date +'%d') -eq $LAST_DAY_OF_MONTH ]] && /absolutepath/myscript.sh
Your return string data can be very long.
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
For example:
So if I wanted to return a first name and last name like: Hello Fred Gerbig I would use the code below, this code works but is it actually the most correct way to do it?
import sys
def main():
if len(sys.argv) >= 2:
fname = sys.argv[1]
lname = sys.argv[2]
else:
name = 'World'
print 'Hello', fname, lname
if __name__ == '__main__':
main()
Edit: Found that the above code works with 2 arguments but crashes with 1. Tried to set len to 3 but that did nothing, still crashes (re-read the other answers and now understand why the 3 did nothing). How do I bypass the arguments if only one is entered? Or how would error checking look that returned "You must enter 2 arguments"?
Edit 2: Got it figured out:
import sys
def main():
if len(sys.argv) >= 2:
name = sys.argv[1] + " " + sys.argv[2]
else:
name = 'World'
print 'Hello', name
if __name__ == '__main__':
main()
It's better to avoid any kind of loops, just remove all elements directly like this:
$("#mytable > tbody").html("");
I think the problem is with the user having deny privileges. This error comes when the user which you have created does not have the sufficient privileges to access your tables in the database. Do grant the privilege to the user in order to get what you want.
GRANT the user specific permissions such as SELECT, INSERT, UPDATE and DELETE on tables in that database.
The default shortcut key is Ctrl-Alt-C.
If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.
// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};
// file scope
int arr[4];
// equivalent to
int arr[4] = {0};
Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.
// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};
I wonder why you find as solution the "white-space" with "nowrap" or "pre", it is not doing the correct behaviour: you force your text in a single line! The text should break lines, but not break words as default. This is caused by some css attributes: word-wrap, overflow-wrap, word-break, and hyphens. So you can have either:
word-break: break-all;
word-wrap: break-word;
overflow-wrap: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
So the solution is remove them, or override them with "unset" or "normal":
word-break: unset;
word-wrap: unset;
overflow-wrap: unset;
-webkit-hyphens: unset;
-moz-hyphens: unset;
-ms-hyphens: unset;
hyphens: unset;
UPDATE: i provide also proof with JSfiddle: https://jsfiddle.net/azozp8rr/
You won't believe this, Make sure to add "." at the end of the "url"
I got a similar error with this code:
fetch(https://itunes.apple.com/search?term=jack+johnson)
.then( response => {
return response.json();
})
.then(data => {
console.log(data.results);
}).catch(error => console.log('Request failed:', error))
The error I got:
Access to fetch at 'https://itunes.apple.com/search?term=jack+johnson'
from origin 'http://127.0.0.1:5500' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
But I realized after a lot of research that the problem was that I did not copy the right URL address from the iTunes API documentation.
It should have been
https://itunes.apple.com/search?term=jack+johnson.
not
https://itunes.apple.com/search?term=jack+johnson
Notice the dot at the end
There is a huge explanation about why the dot is important quoting issues about DNS and character encoding but the truth is you probably do not care. Try adding the dot it might work for you too.
When I added the "." everything worked like a charm.
I hope it works for you too.
you can use http://ipinfo.io/ to get details of ip address Its easy to use .
<?php
function ip_details($ip)
{
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
return $details;
}
$details = ip_details(YoUR IP ADDRESS);
echo $details->city;
echo "<br>".$details->country;
echo "<br>".$details->org;
echo "<br>".$details->hostname; /
?>
You can use WScript.Arguments
to access the arguments passed to your script.
Calling the script:
cscript.exe test.vbs "C:\temp\"
Inside your script:
Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)
Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count
property:
if WScript.Arguments.Count = 0 then
WScript.Echo "Missing parameters"
end if
If your script is over after you close the file then there is no need to set the variables to Nothing
. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing
usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing
, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:
Is there a need to set Objects to Nothing inside VBA Functions
const times = 4;
new Array(times).fill().map(() => console.log('test'));
This snippet will console.log
test
4 times.
You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:
$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
fputcsv($f, $line);
}
To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):
header('Content-Disposition: attachment; filename="filename.csv";');
Putting it all together:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
And you can use it like this:
array_to_csv_download(array(
array(1,2,3,4), // this array is going to be the first row
array(1,2,3,4)), // this array is going to be the second row
"numbers.csv"
);
Update:
Instead of the php://memory
you can also use the php://output
for the file descriptor and do away with the seeking and such:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
I found out that the URL of the application conflicted with a module in the Sun GlassFish.
So, in the file sun-web.xml
I renamed the <context-root>/servlets-samples</context-root>.
It is now working.
The best option is to use INSERT...SELECT statement in mysql.
I found that the best way to determine if the service call has timed out is to use a cancellation token and not the HttpClient's timeout property:
var cts = new CancellationTokenSource();
cts.CancelAfter(timeout);
And then handle the CancellationException during the service call...
catch(TaskCanceledException)
{
if(!cts.Token.IsCancellationRequested)
{
// Timed Out
}
else
{
// Cancelled for some other reason
}
}
Of course if the timeout occurs on the service side of things, that should be able to handled by a WebException.
Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.
https://www.npmjs.com/package/ngx-trim-directive https://www.npmjs.com/package/ng2-trim-directive
Thank you.
Update for mid 2016:
The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!
Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!
Google "npm as build tool" result: https://medium.com/@dabit3/introduction-to-using-npm-as-a-build-tool-b41076f488b0#.c33e74tsa
Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!
Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot
Your questions:
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
Everything belongs in package.json now
Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev
(--save-dev updates your package.json by adding an entry to devDependencies)
npm install lodash --save
(--save updates your package.json by adding an entry to dependencies)If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?
Always. Just because of comfort. When you add a flag (--save-dev
or --save
) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name
is npm i -D package-name
and shortcut for npm install --save package-name
is npm i -S package-name
Use this code.
driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");
My first thought for a non-unicode version was to do something like this:
bool caseInsensitiveStringCompare(const string& str1, const string& str2) {
if (str1.size() != str2.size()) {
return false;
}
for (string::const_iterator c1 = str1.begin(), c2 = str2.begin(); c1 != str1.end(); ++c1, ++c2) {
if (tolower(static_cast<unsigned char>(*c1)) != tolower(static_cast<unsigned char>(*c2))) {
return false;
}
}
return true;
}
Here are two approaches:
@echo off
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%
::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%
::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set "" &::
;;set "}}==%%#"" &::
::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%
::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%
Take a look at the @Deprecated
annotation.
There's no built-in command for that because it's illegal. You can't modify the size of an array once declared.
What you're looking for is either std::vector
to simulate a dynamic array, or better yet a std::string
.
std::string first ("The dog jumps ");
std::string second ("over the log");
std::cout << first + second << std::endl;
To pass multiple headers in a curl request you simply add additional -H
or --header
to your curl command.
Example
//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL
//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json' https://www.example.com
Going Further
For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:
For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.
$ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
$ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com
#form {_x000D_
background-color: #FFF;_x000D_
height: 600px;_x000D_
width: 600px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
margin-top: 0px;_x000D_
border-top-left-radius: 10px;_x000D_
border-top-right-radius: 10px;_x000D_
padding: 0px;_x000D_
text-align:center;_x000D_
}_x000D_
label {_x000D_
font-family: Georgia, "Times New Roman", Times, serif;_x000D_
font-size: 18px;_x000D_
color: #333;_x000D_
height: 20px;_x000D_
width: 200px;_x000D_
margin-top: 10px;_x000D_
margin-left: 10px;_x000D_
text-align: right;_x000D_
margin-right:15px;_x000D_
float:left;_x000D_
}_x000D_
input {_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
border: 1px solid #000;_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div id="form">_x000D_
<form action="" method="post" name="registration" class="register">_x000D_
<fieldset>_x000D_
<div class="form-group">_x000D_
<label for="Student">Name:</label>_x000D_
<input name="Student" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Matric_no">Matric number:</label>_x000D_
<input name="Matric_no" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Email">Email:</label>_x000D_
<input name="Email" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Username">Username:</label>_x000D_
<input name="Username" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Password">Password:</label>_x000D_
<input name="Password" type="password" />_x000D_
</div>_x000D_
<input name="regbutton" type="button" class="button" value="Register" />_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>
_x000D_
Now you can do df['column'].dt.date
Note that for datetime objects, if you don't see the hour when they're all 00:00:00, that's not pandas. That's iPython notebook trying to make things look pretty.
Do not forget that you also can pass these use
variables by reference.
The use cases are when you need to change the use
'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).
$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
$newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);
Now $newarray
will comprise (pseudocode here for brevity) [{times2:2},{times2:4}]
.
On the contrary, using $newarray
with no &
modifier would make outer $newarray
variable be read-only accessible from within the closure scope. But $newarray
within closure scope would be a completelly different newly created variable living only within the closure scope.
Despite both variables' names are the same these would be two different variables. The outer $newarray
variable would comprise []
in this case after the code has finishes.
Open Anaconda cmd in base mode:
Then use conda update conda to update Anaconda.
You can then use conda update --all to update all the requirements for Anaconda:
conda update conda
conda update --all
You can get tail as part of Cygwin.
You can also try default values. spring-value-annotation
Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:
@Value("${unknown.param:some default}")
private String someDefault;
If the same property is defined as a system property and in the properties file, then the system property would be applied.
@Html.Raw(Json.Encode(object)) can be used to convert the View Modal Object to JSON
Here's the decoder I've been using for years...
static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const int BASE64_INPUT_SIZE = 57;
BOOL isbase64(char c)
{
return c && strchr(table, c) != NULL;
}
inline char value(char c)
{
const char *p = strchr(table, c);
if(p) {
return p-table;
} else {
return 0;
}
}
int UnBase64(unsigned char *dest, const unsigned char *src, int srclen)
{
*dest = 0;
if(*src == 0)
{
return 0;
}
unsigned char *p = dest;
do
{
char a = value(src[0]);
char b = value(src[1]);
char c = value(src[2]);
char d = value(src[3]);
*p++ = (a << 2) | (b >> 4);
*p++ = (b << 4) | (c >> 2);
*p++ = (c << 6) | d;
if(!isbase64(src[1]))
{
p -= 2;
break;
}
else if(!isbase64(src[2]))
{
p -= 2;
break;
}
else if(!isbase64(src[3]))
{
p--;
break;
}
src += 4;
while(*src && (*src == 13 || *src == 10)) src++;
}
while(srclen-= 4);
*p = 0;
return p-dest;
}
Setting overflow: hidden
hides the scrollbar. Set overflow: scroll
to make sure the scrollbar appears all the time.
To use the ::webkit-scrollbar
property, simply target .scroll
before calling it.
.scroll {
width: 200px;
height: 400px;
background: red;
overflow: scroll;
}
.scroll::-webkit-scrollbar {
width: 12px;
}
.scroll::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}
.scroll::-webkit-scrollbar-thumb {
border-radius: 10px;
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
?
See this live example
There are several options to specify.
Steps: Right on project in project explorer Go to Run-> Run Configuration -> Click Maven Build -> Click on your build config/or create a new config. You will see the window as the given snapshot below, click on JRE tab there.
You see you have 3 options 1) Workspace Default JRE 2)Execution Environment 3)Alternate JRE 1) Workspace Default JRE is set from 'Window' menu on the top -> Preferences -> Java -> Installed JREs -Here you can add your jdk 2) Execution Environment jdk can be set in pom.xml as mentioned by @ksnortum
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<fork>true</fork>
<executable>C:\Program Files\Java\jdk1.7.0_45\bin\javac.exe</executable>
</configuration>
</plugin>
</plugins>
3) Alternate JRE can be used to select a jdk from your directory
Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's logrotate
If you're in local machine then use this command
/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
For remote machine, use below one
/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
I would handle it like so:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'watch-me') {
$('#show-me').show();
}
else {
$('#show-me').hide();
}
});
});
Swift 5.2, UIView+Extension
extension UIView {
public func addViewBorder(borderColor:CGColor,borderWith:CGFloat,borderCornerRadius:CGFloat){
self.layer.borderWidth = borderWith
self.layer.borderColor = borderColor
self.layer.cornerRadius = borderCornerRadius
}
}
You used this extension;
yourView.addViewBorder(borderColor: #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1), borderWith: 1.0, borderCornerRadius: 20)
This might help to understand what is recorded at what level Loggers may be assigned levels. Levels are instances of the log4net.Core.Level class. The following levels are defined in order of increasing severity - Log Level.
Number of levels recorded for each setting level:
ALL DEBUG INFO WARN ERROR FATAL OFF
•All
•DEBUG •DEBUG
•INFO •INFO •INFO
•WARN •WARN •WARN •WARN
•ERROR •ERROR •ERROR •ERROR •ERROR
•FATAL •FATAL •FATAL •FATAL •FATAL •FATAL
•OFF •OFF •OFF •OFF •OFF •OFF •OFF
The error message:
merge: remote/master - not something we can merge
is saying that Git doesn't recognize remote/master
. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".
Think of "remotes" as an alias for the url to your Git server. master
is your locally checked-out version of the branch. origin/master
is the latest version of master
from your Git server that you have fetched (downloaded). A fetch
is always safe because it will only update the "origin/x" version of your branches.
So, to get your master
branch back in sync, first download the latest content from the git server:
git fetch
Then, perform the merge:
git merge origin/master
...But, perhaps the better approach would be:
git pull origin master
The pull
command will do the fetch
and merge
for you in one step.
I don't exactly understand what's the problem. Incomplete type is not the type that's "missing". Incompete type is a type that is declared but not defined (in case of struct types). To find the non-defining declaration is easy. As for the finding the missing definition... the compiler won't help you here, since that is what caused the error in the first place.
A major reason for incomplete type errors in C are typos in type names, which prevent the compiler from matching one name to the other (like in matching the declaration to the definition). But again, the compiler cannot help you here. Compiler don't make guesses about typos.
Update on the Library/Formula/postgresql.rb line 8 to
http://ftp2.uk.postgresql.org/sites/ftp.postgresql.org/source/v8.4.6/postgresql-8.4.6.tar.bz2
And MD5 on line 9 to
fcc3daaf2292fa6bf1185ec45e512db6
Save and exit.
brew install postgres
initdb /usr/local/var/postgres
Now in this stage you might face the postgresql could not create shared memory segment
error, to work around that update the /etc/sysctl.conf
like this:
kern.sysv.shmall=65536
kern.sysv.shmmax=16777216
Try initdb /usr/local/var/postgres
again, and it should run smooth.
To run postgresql on start
launchctl load -w /usr/local/Cellar/postgresql/8.4.6/org.postgresql.postgres.plist
Hope that helps :)
I've found that for my use-cases I don't always want the entire outerHTML. Many nodes just have too many children to show.
Here's a function (minimally tested in Chrome):
/**
* Stringifies a DOM node.
* @param {Object} el - A DOM node.
* @param {Number} truncate - How much to truncate innerHTML of element.
* @returns {String} - A stringified node with attributes
* retained.
*/
function stringifyEl(el, truncate) {
var truncateLen = truncate || 50;
var outerHTML = el.outerHTML;
var ret = outerHTML;
ret = ret.substring(0, truncateLen);
// If we've truncated, add an elipsis.
if (outerHTML.length > truncateLen) {
ret += "...";
}
return ret;
}
https://gist.github.com/kahunacohen/467f5cc259b5d4a85eb201518dcb15ec
If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling
exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");
and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo
and adding the following line to the very end of it
www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2
All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.
rekaszeru
I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..
Im using a EditText as an example
// GIVE TARGET TEXT BOX A NAME
EditText textbox = (EditText) findViewById(R.id.your_textboxID);
// STRING TO REPLACE
String oldText = "hello"
String newText = "Hi";
String textBoxText = textbox.getText().toString();
// REPLACE STRINGS WITH RETURNED STRINGS
String returnedString = textBoxText.replace( oldText, newText );
// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX
textbox.setText(returnedString);
This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !
Obviously this example requires that you have a EditText with the ID set to your_textboxID
The guide linked here will probably answer the original question without the need for programming a custom SSL connector.
Found a very detailed how-to guide on importing root certificates that actually steps you through installing trusted CA certificates on different versions of Android devices (among other devices).
Basically you'll need to:
Download: the cacerts.bks file from your phone.
adb pull /system/etc/security/cacerts.bks cacerts.bks
Download the .crt file from the certifying authority you want to allow.
Modify the cacerts.bks file on your computer using the BouncyCastle Provider
Upload the cacerts.bks file back to your phone and reboot.
Here is a more detailed step by step to update earlier android phones: How to update HTTPS security certificate authority keystore on pre-android-4.0 device
No previous single solution worked for me, I had to mix them and got the issue fixed also on older devices (iphone 3).
First, I had to wrap the html content into an outer div:
<html>
<body>
<div id="wrapper">... old html goes here ...</div>
</body>
</html>
Then I had to apply overflow hidden to the wrapper, because overflow-x was not working:
#wrapper {
overflow: hidden;
}
and this fixed the issue.
Yet another way to use Rscript for *Unix systems is Process Substitution.
Rscript <(zcat a.r)
# [1] "hello"
Which obviously does the same as the accepted answer, but this allows you to manipulate and run your file without saving it the power of the command line, e.g.:
Rscript <(sed s/hello/bye/ a.r)
# [1] "bye"
Similar to Rscript -e "Rcode"
it also allows to run without saving into a file. So it could be used in conjunction with scripts that generate R-code, e.g.:
Rscript <(echo "head(iris,2)")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
Use Diagrams
| Show Diagram...
from the context menu of a package. Invoking it on the project root will show module dependencies diagram.
If you need multiple packages, you can drag & drop them to the already opened diagram for the first package and press e to expand it.
Note: This feature is available in the Ultimate Edition, not the free Community Edition.
Take a look at Google Play Location Samples
Location Updates using a Foreground Service: Get updates about a device's location using a bound and started foreground service.
Location Updates using a PendingIntent: Get updates about a device's location using a PendingIntent
. Sample shows implementation using an IntentService
as well as a BroadcastReceiver
.
You can use AppendDataBoundItems=true
to easily add:
<asp:DropDownList ID="drpList" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="" Value="" />
</asp:DropDownList>
I suggest you check out chunked
and disk.frame
. They both have functions for reading in CSVs chunk-by-chunk.
In particular, disk.frame::csv_to_disk.frame
may be the function you are after?
More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.
In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.
You pick what matters the most to you.
Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
ChangeDetectorRef approach
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
export class MyComponent {
constructor(private cdr: ChangeDetectorRef) { }
selected(item: any) {
if (item == 'Department')
this.isDepartment = true;
else
this.isDepartment = false;
this.cdr.detectChanges();
}
}
use driver.findElement(By.partialLinkText("long")).click();
Lets say, you wanted to have some CGAL-Demos portable. So you'd have a folder "CGAL", and in it, 1 subfolder called "lib": all (common) support-dlls for any programs in the CGAL-folder go here. In our example, this would be the Dll-Download: simply unzip into the "lib" directory. The further you scroll down on the demos-page, the more impressive the content. In my case, the polyhedron-demo seemed about right. If this runs on my 10+ yo notebook, I'm impressed. So I created a folder "demo" in the "CGAL"-directory, alongside "lib". Now create a .cmd-file in that folder. I named mine "Polyhedron.cmd". So we have a directory structure like this:
CGAL - the bag for all the goodies
lib - all libraries for all CGAL-packages
demo - all the demos I'm interested in
[...] - certainly some other collections, several apps per folder...
Polyhedron.cmd - and a little script for every Qt-exe to make it truly portable.
In this little example, "Polyhedron.cmd" contains the following text:
@echo off
set "me=%~dp0"
set PATH=%me%lib
set "QT_PLUGIN_PATH=%me%lib\plugins"
start /b "CGAL Polyhedron Demo" "%me%demo\polyhedron\polyhedron_3.exe"
All scripts can be the same apart from the last line, obviously. The only caveat is: the "DOS-Window" stays open for as long as you use the actual program. Close the shell-window, and you kill the *.exe as well. Whereever you copy the "CGAL"-folder, as the weird "%~dp0"-wriggle represents the full path to the *.cmd-file that we started, with trailing "\". So "%me%lib" is always the full path to the actual library ("CGAL\lib" in my case). The next 2 lines tell Qt where its "runtime" files are. This will be at least the file "qwindows.dll" for Windows-Qt programs plus any number of *.dlls. If I remember rightly, the Dll-library (at least when I downloaded it) had a little "bug" since it contains the "platforms"-directory with qwindows.dll in it. So when you open the lib directory, you need to create a folder "plugins" next to "platforms", and then move into "plugins". If a Qt-app, any Qt-app, doesn't find "qwindows.dll", it cannot find "windows". And it expects it in a directory named "platforms" in the "plugins" directory, which it has to get told by the OS its running on...and if the "QT_PLUGIN_PATH" is not exactly pointing to all the helper-dlls you need, some Qt-programs will still run with no probs. And some complain about missing *.dlls you've never heard off...
Included page:
<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>
Including page:
<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
ui:composition
as shown above.ui:include
in the including xhtml file as also shown above.show variables
Show variables like "`secure_file_priv`";
Note: keep your csv file in location given by the above command.
create table assessments (course_code varchar(5),batch_code varchar(7),id_assessment int, assessment_type varchar(10), date int , weight int);
Note: here the 'date
' column has some blank values in the csv file.
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/assessments.csv'
INTO TABLE assessments
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY ''
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(course_code,batch_code,id_assessment,assessment_type,@date,weight)
SET date = IF(@date = '', NULL, @date);
If you're desperate (like i was) for tooltips on checkboxes, textboxes and the like, then here is my hackey workaround:
$('input:disabled, button:disabled').after(function (e) {
d = $("<div>");
i = $(this);
d.css({
height: i.outerHeight(),
width: i.outerWidth(),
position: "absolute",
})
d.css(i.offset());
d.attr("title", i.attr("title"));
d.tooltip();
return d;
});
Working examples: http://jsfiddle.net/WB6bM/11/
For what its worth, I believe tooltips on disabled form elements is very important to the UX. If you're preventing somebody from doing something, you should tell them why.
Faced the same problem in Android Studio 3.1.3
Just go to style.xml file
and replace Theme name
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
with
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
Then clean and rebuild the project.This will solve the error.
You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:
Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
.thenComparingInt(SomeEntity::getProperty2)
.thenComparing(SomeEntity::getProperty3, reverseOrder());
Try this, I found it from my old codes, which shows the correct Result
function ago($datefrom, $dateto = -1) {
// Defaults and assume if 0 is passed in that
// its an error rather than the epoch
if ($datefrom == 0) {
return "A long time ago";
}
if ($dateto == -1) {
$dateto = time();
}
// Make the entered date into Unix timestamp from MySQL datetime field
$datefrom = strtotime($datefrom);
// Calculate the difference in seconds betweeen
// the two timestamps
$difference = $dateto - $datefrom;
// Based on the interval, determine the
// number of units between the two dates
// From this point on, you would be hard
// pushed telling the difference between
// this function and DateDiff. If the $datediff
// returned is 1, be sure to return the singular
// of the unit, e.g. 'day' rather 'days'
switch (true) {
// If difference is less than 60 seconds,
// seconds is a good interval of choice
case(strtotime('-1 min', $dateto) < $datefrom):
$datediff = $difference;
$res = ($datediff == 1) ? $datediff . ' second' : $datediff . ' seconds';
break;
// If difference is between 60 seconds and
// 60 minutes, minutes is a good interval
case(strtotime('-1 hour', $dateto) < $datefrom):
$datediff = floor($difference / 60);
$res = ($datediff == 1) ? $datediff . ' minute' : $datediff . ' minutes';
break;
// If difference is between 1 hour and 24 hours
// hours is a good interval
case(strtotime('-1 day', $dateto) < $datefrom):
$datediff = floor($difference / 60 / 60);
$res = ($datediff == 1) ? $datediff . ' hour' : $datediff . ' hours';
break;
// If difference is between 1 day and 7 days
// days is a good interval
case(strtotime('-1 week', $dateto) < $datefrom):
$day_difference = 1;
while (strtotime('-' . $day_difference . ' day', $dateto) >= $datefrom) {
$day_difference++;
}
$datediff = $day_difference;
$res = ($datediff == 1) ? 'yesterday' : $datediff . ' days';
break;
// If difference is between 1 week and 30 days
// weeks is a good interval
case(strtotime('-1 month', $dateto) < $datefrom):
$week_difference = 1;
while (strtotime('-' . $week_difference . ' week', $dateto) >= $datefrom) {
$week_difference++;
}
$datediff = $week_difference;
$res = ($datediff == 1) ? 'last week' : $datediff . ' weeks';
break;
// If difference is between 30 days and 365 days
// months is a good interval, again, the same thing
// applies, if the 29th February happens to exist
// between your 2 dates, the function will return
// the 'incorrect' value for a day
case(strtotime('-1 year', $dateto) < $datefrom):
$months_difference = 1;
while (strtotime('-' . $months_difference . ' month', $dateto) >= $datefrom) {
$months_difference++;
}
$datediff = $months_difference;
$res = ($datediff == 1) ? $datediff . ' month' : $datediff . ' months';
break;
// If difference is greater than or equal to 365
// days, return year. This will be incorrect if
// for example, you call the function on the 28th April
// 2008 passing in 29th April 2007. It will return
// 1 year ago when in actual fact (yawn!) not quite
// a year has gone by
case(strtotime('-1 year', $dateto) >= $datefrom):
$year_difference = 1;
while (strtotime('-' . $year_difference . ' year', $dateto) >= $datefrom) {
$year_difference++;
}
$datediff = $year_difference;
$res = ($datediff == 1) ? $datediff . ' year' : $datediff . ' years';
break;
}
return $res;
}
Example: echo ago('2020-06-03 00:14:21 AM');
Output: 6 days
Go to any page you want to see it in browser right click--> view in browser. this way working with me.
If you want to use a single value in bash use:
companyid=$(mysql --user=$Username --password=$Password --database=$Database -s --execute="select CompanyID from mytable limit 1;"|cut -f1)
echo "$companyid"
also, with wmode=opaque
and with IE, the Flash gets the keyboard events, but also the html page receives them, so it can't be use for something like embedding a flash game. Very annoying
In my case, I just created a header file to define constant strings like this:
NSString *const AppDescriptionString = @"Healthy is the best way to keep fit";
I solved this scenario by using static
:
static NSString *const AppDescriptionString = @"Healthy is the best way to keep fit";
In the Documentation it says there are no import statements in Swift.
Simply use:
let primNumber = PrimeNumberModel()
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
Another thing on linux is:
send
does not allow to operate on non-socket fd. Thus, for example to write on usb port, write
is necessary.
This is a great example of using the wrong tool for the job. Regular expressions do not handle arbitrarily nested sub-matches very well. What you should do instead is use a real lexer and parser (a grammar for C++ should be easy to find) and look for unexpectedly empty loop bodies.
Use Flexbox:
.outerDiv {
display: flex;
flex-direction: column;
justify-content: center; /* Centering y-axis */
align-items :center; /* Centering x-axis */
}
With @Lob
I always end up with a LONGTEXT
in MySQL.
To get TEXT
I declare it that way (JPA 2.0):
@Column(columnDefinition = "TEXT")
private String text
Find this better, because I can directly choose which Text-Type the column will have in database.
For columnDefinition
it is also good to read this.
EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT"
.
You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.
However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table"
it emits code which actually creates a StringBuilder
behind the scenes and appends to it, so the end result is not that bad afterall.
But of course anyone looking at that code is bound to think that it is kind of retarded.
You can use .scrollIntoView()
for this. It will bring a specific element into the viewport.
Example:
document.getElementById( 'bottom' ).scrollIntoView();
Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/
Script:
function top() {
document.getElementById( 'top' ).scrollIntoView();
};
function bottom() {
document.getElementById( 'bottom' ).scrollIntoView();
window.setTimeout( function () { top(); }, 2000 );
};
bottom();
HTML:
<div id="top">top</div>
<div id="bottom">bottom</div>
CSS:
#top {
border: 1px solid black;
height: 3000px;
}
#bottom {
border: 1px solid red;
}
Probably easiest way is to PInvoke LogonUser Win32 API.e.g.
MSDN Reference here...
Definitely want to use logon type
LOGON32_LOGON_NETWORK (3)
This creates a lightweight token only - perfect for AuthN checks. (other types can be used to build interactive sessions etc.)
Your best bet is probably waitForCondition
and writing a javascript function that returns true when the map is loaded.
check this fiddle , and if you want to move the overlapped div you set its position to absolute
then change it's top
and left
values
In my case i haven't given the
orientation of LinearLayout(ScrollView's Child)
So by default it takes horizontal, but scrollview scrols vertically, so please check if 'android:orientation="vertical"' is set to your ScrollView's Child(In the case of LinearLayout).
This was my case hopes it helps somebody
.
Filter your log to just Error and look for FATAL EXCEPTION
I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.
I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.
/**
* Performs an in-place complex FFT.
*
* Released under the MIT License
*
* Copyright (c) 2010 Gerald T. Beauregard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
public class FFT2
{
// Element for linked list in which we store the
// input/output data. We use a linked list because
// for sequential access it's faster than array index.
class FFTElement
{
public double re = 0.0; // Real component
public double im = 0.0; // Imaginary component
public FFTElement next; // Next element in linked list
public uint revTgt; // Target position post bit-reversal
}
private uint m_logN = 0; // log2 of FFT size
private uint m_N = 0; // FFT size
private FFTElement[] m_X; // Vector of linked list elements
/**
*
*/
public FFT2()
{
}
/**
* Initialize class to perform FFT of specified size.
*
* @param logN Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
*/
public void init(
uint logN )
{
m_logN = logN;
m_N = (uint)(1 << (int)m_logN);
// Allocate elements for linked list of complex numbers.
m_X = new FFTElement[m_N];
for (uint k = 0; k < m_N; k++)
m_X[k] = new FFTElement();
// Set up "next" pointers.
for (uint k = 0; k < m_N-1; k++)
m_X[k].next = m_X[k+1];
// Specify target for bit reversal re-ordering.
for (uint k = 0; k < m_N; k++ )
m_X[k].revTgt = BitReverse(k,logN);
}
/**
* Performs in-place complex FFT.
*
* @param xRe Real part of input/output
* @param xIm Imaginary part of input/output
* @param inverse If true, do an inverse FFT
*/
public void run(
double[] xRe,
double[] xIm,
bool inverse = false )
{
uint numFlies = m_N >> 1; // Number of butterflies per sub-FFT
uint span = m_N >> 1; // Width of the butterfly
uint spacing = m_N; // Distance between start of sub-FFTs
uint wIndexStep = 1; // Increment for twiddle table index
// Copy data into linked complex number objects
// If it's an IFFT, we divide by N while we're at it
FFTElement x = m_X[0];
uint k = 0;
double scale = inverse ? 1.0/m_N : 1.0;
while (x != null)
{
x.re = scale*xRe[k];
x.im = scale*xIm[k];
x = x.next;
k++;
}
// For each stage of the FFT
for (uint stage = 0; stage < m_logN; stage++)
{
// Compute a multiplier factor for the "twiddle factors".
// The twiddle factors are complex unit vectors spaced at
// regular angular intervals. The angle by which the twiddle
// factor advances depends on the FFT stage. In many FFT
// implementations the twiddle factors are cached, but because
// array lookup is relatively slow in C#, it's just
// as fast to compute them on the fly.
double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
if (inverse == false)
wAngleInc *= -1;
double wMulRe = Math.Cos(wAngleInc);
double wMulIm = Math.Sin(wAngleInc);
for (uint start = 0; start < m_N; start += spacing)
{
FFTElement xTop = m_X[start];
FFTElement xBot = m_X[start+span];
double wRe = 1.0;
double wIm = 0.0;
// For each butterfly in this stage
for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
{
// Get the top & bottom values
double xTopRe = xTop.re;
double xTopIm = xTop.im;
double xBotRe = xBot.re;
double xBotIm = xBot.im;
// Top branch of butterfly has addition
xTop.re = xTopRe + xBotRe;
xTop.im = xTopIm + xBotIm;
// Bottom branch of butterly has subtraction,
// followed by multiplication by twiddle factor
xBotRe = xTopRe - xBotRe;
xBotIm = xTopIm - xBotIm;
xBot.re = xBotRe*wRe - xBotIm*wIm;
xBot.im = xBotRe*wIm + xBotIm*wRe;
// Advance butterfly to next top & bottom positions
xTop = xTop.next;
xBot = xBot.next;
// Update the twiddle factor, via complex multiply
// by unit vector with the appropriate angle
// (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
double tRe = wRe;
wRe = wRe*wMulRe - wIm*wMulIm;
wIm = tRe*wMulIm + wIm*wMulRe;
}
}
numFlies >>= 1; // Divide by 2 by right shift
span >>= 1;
spacing >>= 1;
wIndexStep <<= 1; // Multiply by 2 by left shift
}
// The algorithm leaves the result in a scrambled order.
// Unscramble while copying values from the complex
// linked list elements back to the input/output vectors.
x = m_X[0];
while (x != null)
{
uint target = x.revTgt;
xRe[target] = x.re;
xIm[target] = x.im;
x = x.next;
}
}
/**
* Do bit reversal of specified number of places of an int
* For example, 1101 bit-reversed is 1011
*
* @param x Number to be bit-reverse.
* @param numBits Number of bits in the number.
*/
private uint BitReverse(
uint x,
uint numBits)
{
uint y = 0;
for (uint i = 0; i < numBits; i++)
{
y <<= 1;
y |= x & 0x0001;
x >>= 1;
}
return y;
}
}
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');
It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"
You already specified the culture, so try escaping the slashes.
Use .rsplit()
or .rpartition()
instead:
s.rsplit(',', 1)
s.rpartition(',')
str.rsplit()
lets you specify how many times to split, while str.rpartition()
only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.
Demo:
>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')
Both methods start splitting from the right-hand-side of the string; by giving str.rsplit()
a maximum as the second argument, you get to split just the right-hand-most occurrences.
You can run from Java code.
try {
File file = new File(keystore location);
InputStream is = new FileInputStream(file);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "password";
keystore.load(is, password.toCharArray());
Enumeration<String> enumeration = keystore.aliases();
while(enumeration.hasMoreElements()) {
String alias = enumeration.nextElement();
System.out.println("alias name: " + alias);
Certificate certificate = keystore.getCertificate(alias);
System.out.println(certificate.toString());
}
} catch (java.security.cert.CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null != is)
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Certificate class holds all information about the keystore.
UPDATE- OBTAIN PRIVATE KEY
Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);
@prateek Hope this is what you looking for!
Worked for me only when path
was set, i.e.:
$.cookie('name', null, {path:'/'})
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.
Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.
To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
I had similar problem and please note that we need not set JAVA_HOME unless we are going to use debug mode. tomcat in windows 7 can handle spaces in environment variables the problem is because of "bin" in the path. setting JRE_HOME to C:\Program Files (x86)\Java\jre1.8.0_65 solved my problem and tomcat is up and running without any trouble
Moreover, you can still use the "ordinary" if
syntax and conflate it into one line with a colon.
if i > 3: print("We are done.")
or
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
From stringr library you could try this:
Remove fill blank
library(stringr)
2. 1.
| |
V V
str_replace_all(str_trim(" xx yy 11 22 33 "), " ", "")
With MongoDB version 4.2+, updates are more flexible as it allows the use of aggregation pipeline in its update
, updateOne
and updateMany
. You can now transform your documents using the aggregation operators then update without the need to explicity state the $set
command (instead we use $replaceRoot: {newRoot: "$$ROOT"}
)
Here we use the aggregate query to extract the timestamp from MongoDB's ObjectID "_id" field and update the documents (I am not an expert in SQL but I think SQL does not provide any auto generated ObjectID that has timestamp to it, you would have to automatically create that date)
var collection = "person"
agg_query = [
{
"$addFields" : {
"_last_updated" : {
"$toDate" : "$_id"
}
}
},
{
$replaceRoot: {
newRoot: "$$ROOT"
}
}
]
db.getCollection(collection).updateMany({}, agg_query, {upsert: true})
I would use .Equals()
for comparison instead of ==
.
Like so:
MyClass item = MyList.Find(item => item.name.Equals("foo"));
Particularly because it gives you options like StringComparison, which is awesome. Example:
MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);
This enables your code to ignore special characters, upper and lower case. There are more options.
If you are using underscoreJs then you can simply use _.isEqual function and it compares all keys and values at each and every level of hierarchy like below example.
var object = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};
var object1 = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};
console.log(_.isEqual(object, object1));//return true
If all the keys and values for those keys are same in both the objects then it will return true, otherwise return false.
If you are running the MySQL other than default port:
mysqldump.exe -u username -p -P PORT_NO database > backup.sql
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
import itertools
import collections
dictA = {'a':1, 'b':2, 'c':3}
dictB = {'b':3, 'c':4, 'd':5}
new_dict = collections.defaultdict(int)
# use dict.items() instead of dict.iteritems() for Python3
for k, v in itertools.chain(dictA.iteritems(), dictB.iteritems()):
new_dict[k] += v
print dict(new_dict)
# OUTPUT
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
OR
Alternative you can use Counter as @Martijn has mentioned above.
jquery ui has a great datepicker you can find it here
http://jqueryui.com/demos/datepicker/
you can use
http://jqueryui.com/demos/datepicker/#event-onSelect
to make your own actions when a date is picked
and if you want it to open without a form you could create a form that's hidden and then bind a click event to it like this
$("button").click(function() {
$(inputselector).datepicker('show');
});
We don't know what server.properties file is that, we neither know what SimocoPoolSize means (do you?)
Let's guess you are using some custom pool of database connections. Then, I guess the problem is that your pool is configured to open 100 or 120 connections, but you Postgresql server is configured to accept MaxConnections=90
. These seem conflictive settings. Try increasing MaxConnections=120
.
But you should first understand your db layer infrastructure, know what pool are you using, if you really need so many open connections in the pool. And, specially, if you are gracefully returning the opened connections to the pool
You must declare
int add(int a, int b);
(note to the semicolon)
in a header file and include the file into both files.
Including it into Main.c will tell compiler how the function should be called.
Including into the second file will allow you to check that declaration is valid (compiler would complain if declaration and implementation were not matched).
Then you must compile both *.c files into one project. Details are compiler-dependent.
Just complementing @Jonsmoke's answer.
For API level 21 and above you can use :
android:backgroundTint="@android:color/white"
in XML for the button layout.
For API level below 21 use an AppCompatButton using app namespace instead of android for backgroundTint.
For example:
<android.support.v7.widget.AppCompatButton
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Button"
app:backgroundTint="@android:color/white" />
This worked for me in Xcode 6.3.2, Swift 1.2 :
import UIKit
class ViewController: UIViewController
{
var splashScreen:UIImageView!
override func viewDidLoad()
{
super.viewDidLoad()
self.splashScreen = UIImageView(frame: self.view.frame)
self.splashScreen.image = UIImage(named: "Default.png")
self.view.addSubview(self.splashScreen)
var removeSplashScreen = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "removeSP", userInfo: nil, repeats: false)
}
func removeSP()
{
println(" REMOVE SP")
self.splashScreen.removeFromSuperview()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
ViewController is the first app VC that is being loaded.
It is hard to figure out exactly what you are trying to do from the question. I'll take a guess and say that you want to add an extra compile task in addition to those provided out of the box by the java plugin.
The easiest way to do this is probably to specify a new sourceSet
called 'speedTest'. This will generate a configuration
called 'speedTest' which you can use to specify your dependencies within a dependencies
block. It will also generate a task called compileSpeedTestJava
for you.
For an example, take a look at defining new source sets in the Java plugin documentation
In general it seems that you have some incorrect assumptions about how dependency management works with Gradle. I would echo the advice of the others to read the 'Dependency Management' chapters of the user guide again :)
My problem was dotnet got hung up and whenever VS would try to make a new dll, or access an old one, the dotnet process would latch onto the dll and stop visual studio from cloning the dll. Solution is just to end all dotnet tasks in task manager(it will only actually remove the dead one, if you are trying to end one and it won't shut down, that means it's working).
I have edited the function for you,
void readFile()
{
ifstream file;
file.open ("program.txt");
if (!file.is_open()) return;
string word;
while (file >> word)
{
cout<< word << '\n';
}
}
What you are looking for are Linked Servers. You can get to them in SSMS from the following location in the tree of the Object Explorer:
Server Objects-->Linked Servers
or you can use sp_addlinkedserver.
You only have to set up one. Once you have that, you can call a table on the other server like so:
select
*
from
LocalTable,
[OtherServerName].[OtherDB].[dbo].[OtherTable]
Note that the owner isn't always dbo
, so make sure to replace it with whatever schema you use.
Just get rid of the parenthesis and that will give you an array with one element and:
var test = tesst.match(/a(.*)j/);
var test = tesst.match(/a.*j/);
If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis
If you only want the first match found, you might want to use RegExp.exec() instead.
You can use the below code:
RegExp(/a.*j/).exec("afskfsd33j")
Try something like this:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
Java didn't provide multiple inheritance.
When you say A extends B then it means that A extends B and B extends Object.
It doesn't mean A extends B, Object.
class A extends Object
class B extends A
You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.
Did some testing with the following script, on both PS 2 and PS 4 and had the same result. I hope this helps people.
$PSVersionTable.PSVersion
function PSscript {
$PSscript = Get-Item $MyInvocation.ScriptName
Return $PSscript
}
""
$PSscript = PSscript
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
""
$PSscript = Get-Item $MyInvocation.InvocationName
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
Results -
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
Another solution is to set the window type to a system dialog:
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
This requires the SYSTEM_ALERT_WINDOW
permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
As the docs say:
Very few applications should use this permission; these windows are intended for system-level interaction with the user.
This is a solution you should only use if you require a dialog that's not attached to an activity.
It's been a while since I C++'d but these answers are off a bit.
As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.
So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.
It's never polite to discuss the size of your bits in public.
When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.
So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.
Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder
A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html
use int if you really don't care how large your bits are; it can change.
Use size_t and ssize_t if you want to know how large something is.
If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.
I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.
It's crappy coding when you mix int.
use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
If they are in the same directory as your script that contains:
./a.sh > /dev/null 2>&1 &
./b.sh > /dev/null 2>&1 &
The &
at the end is what makes your script run in the background.
The > /dev/null 2>&1
part is not necessary - it redirects the stdout and stderr streams so you don't have to see them on the terminal, which you may want to do for noisy scripts with lots of output.
Instead of use set_userdata you should use set_flashdata.
According to CI user guide:
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
You can use Date.UTC method to get the time stamp at the UTC timezone.
Usage:
var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() ,
now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
Live demo here http://jsfiddle.net/naryad/uU7FH/1/
Despite the fact that this question has been asked long time ago but I feel a comprehensive description would clarify why there is no need to use public abstract before methods and public static final before constants of an interface.
First of all Interfaces are used to specify common methods for a set of unrelated classes for which every class will have a unique implementation. Therefore it is not possible to specify the access modifier as private since it cannot be accessed by other classes to be overridden.
Second, Although one can initiate objects of an interface type but an interface is realized by the classes which implement it and not inherited. And since an interface might be implemented (realized) by different unrelated classes which are not in the same package therefore protected access modifier is not valid as well. So for the access modifier we are only left with public choice.
Third, an interface does not have any data implementation including the instance variables and methods. If there is logical reason to insert implemented methods or instance variables in an interface then it must be a superclass in an inheritance hierarchy and not an interface. Considering this fact, since no method can be implemented in an interface therefore all the methods in interface must be abstract.
Fourth, Interface can only include constant as its data members which means they must be final and of course final constants are declared as static to keep only one instance of them. Therefore static final also is a must for interface constants.
So in conclusion although using public abstract before methods and public static final before constants of an interface is valid but since there is no other options it is considered redundant and not used.
Use a do-while to design re-try block.
boolean successful = false;
int maxTries = 3;
do{
try {
something();
success = true;
} catch(Me ifUCan) {
maxTries--;
}
} while (!successful || maxTries > 0)
Here is a simple function with filter
demonstrating one way to take care of beginning and ending NAs with padding, and computing a weighted average (supported by filter
) using custom weights:
wma <- function(x) {
wts <- c(seq(0.5, 4, 0.5), seq(3.5, 0.5, -0.5))
nside <- (length(wts)-1)/2
# pad x with begin and end values for filter to avoid NAs
xp <- c(rep(first(x), nside), x, rep(last(x), nside))
z <- stats::filter(xp, wts/sum(wts), sides = 2) %>% as.vector
z[(nside+1):(nside+length(x))]
}
i was looking for the same problem and stumbled upon the following code.
How to get Client MAC address(Web):
To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.
This script is for IE only:
function showMacAddress() {_x000D_
var obj = new ActiveXObject("WbemScripting.SWbemLocator");_x000D_
var s = obj.ConnectServer(".");_x000D_
var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");_x000D_
var e = new Enumerator(properties);_x000D_
var output;_x000D_
output = '<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';_x000D_
output = output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';_x000D_
while (!e.atEnd()) {_x000D_
e.moveNext();_x000D_
var p = e.item();_x000D_
if (!p) continue;_x000D_
output = output + '<tr bgColor="#FFFFFF">';_x000D_
output = output + '<td>' + p.Caption; +'</td>';_x000D_
output = output + '<td>' + p.MACAddress + '</td>';_x000D_
output = output + '</tr>';_x000D_
}_x000D_
output = output + '</table>';_x000D_
document.getElementById("box").innerHTML = output;_x000D_
}_x000D_
_x000D_
showMacAddress();
_x000D_
<div id='box'></div>
_x000D_
Preconditions: adb and wireshark are installed on your computer and you have a rooted android device.
adb push ~/Downloads/tcpdump /sdcard/
adb shell
su root
mv /sdcard/tcpdump /data/local/
cd /data/local/
chmod +x tcpdump
./tcpdump -vv -i any -s 0 -w /sdcard/dump.pcap
Ctrl+C
once you've captured enough data.exit
exit
adb pull /sdcard/dump.pcap ~/Downloads/
Now you can open the pcap file using Wireshark.
As for your question about monitoring specific processes, find the bundle id of your app, let's call it com.android.myapp
ps | grep com.android.myapp
/data/local
using the same way you did for tcpdump
above. cd /data/local
./strace -p 1234 -f -e trace=network -o /sdcard/strace.txt
Now you can look at strace.txt for ip addresses, and filter your wireshark log for those IPs.
I followed the below Steps. It worked for me.
In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.
Download Git Publisher Plugin and Configure as shown below snapshot.
Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.
You can use the function stat.desc from pastec package.
library(pastec)
stat.desc(x, BASIC =TRUE, NORMAL =TRUE)
you can find more about it from here: https://www.rdocumentation.org/packages/pastecs/versions/1.3.21/topics/stat.desc
You can use any of the two based on your need:
Field[] fields = ClassName.class.getFields(); // returns inherited members but not private members.
Field[] fields = ClassName.class.getDeclaredFields(); // returns all members including private members but not inherited members.
To filter only the public fields from the above list (based on requirement) use below code:
List<Field> fieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPublic(field.getModifiers())).collect(
Collectors.toList());