Along with a number of good answers, what specifically distinguishes a bless
-ed reference is that the SV
for it picks up an additional FLAGS
(OBJECT
) and a STASH
perl -MDevel::Peek -wE'
package Pack { sub func { return { a=>1 } } };
package Class { sub new { return bless { A=>10 } } };
$vp = Pack::func(); print Dump $vp; say"---";
$obj = Class->new; print Dump $obj'
Prints, with the same (and irrelevant for this) parts suppressed
SV = IV(0x12d5530) at 0x12d5540 REFCNT = 1 FLAGS = (ROK) RV = 0x12a5a68 SV = PVHV(0x12ab980) at 0x12a5a68 REFCNT = 1 FLAGS = (SHAREKEYS) ... SV = IV(0x12a5ce0) at 0x12a5cf0 REFCNT = 1 FLAGS = (IOK,pIOK) IV = 1 --- SV = IV(0x12cb8b8) at 0x12cb8c8 REFCNT = 1 FLAGS = (PADMY,ROK) RV = 0x12c26b0 SV = PVHV(0x12aba00) at 0x12c26b0 REFCNT = 1 FLAGS = (OBJECT,SHAREKEYS) STASH = 0x12d5300 "Class" ... SV = IV(0x12c26b8) at 0x12c26c8 REFCNT = 1 FLAGS = (IOK,pIOK) IV = 10
With that it's known that 1) it is an object 2) what package it belongs to, and this informs its use.
For example, when dereferencing on that variable is encountered ($obj->name
), a sub with that name is sought in the package (or hierarchy), the object is passed as the first argument, etc.
None of these solutions worked for me in 3.6, with a folder structure like:
package1/
subpackage1/
module1.py
package2/
subpackage2/
module2.py
My goal was to import from module1 into module2. What finally worked for me was, oddly enough:
import sys
sys.path.append(".")
Note the single dot as opposed to the two-dot solutions mentioned so far.
Edit: The following helped clarify this for me:
import os
print (os.getcwd())
In my case, the working directory was (unexpectedly) the root of the project.
Find your own local android-SDK, if you download the relevant SDK of ndk, there will be a folder called "ndk-bundle"
There is a folder called "toolchains" inside.
We noticed that there are no mips64el related files inside.
The solution is as follows:
Click here to download the NDK package separately through the browser. After unzipping, open the "toolchains" folder, compare it with the android-sdk->ndk-bundle->toolchains folder, find the missing folder, copy the past three. Recompile, the problem is solved.
public static async Task<byte[]> GetBytesAsync(string url) {
var request = (HttpWebRequest)WebRequest.Create(url);
using (var response = await request.GetResponseAsync())
using (var content = new MemoryStream())
using (var responseStream = response.GetResponseStream()) {
await responseStream.CopyToAsync(content);
return content.ToArray();
}
}
public static async Task<string> GetStringAsync(string url) {
var bytes = await GetBytesAsync(url);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.
Set up your variable like this:
IEnumerable<IEnumerable<string>> data = new[] {
new[]{"...", "...", "..."},
... etc ...
};
Then you'd simply go:
var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null);
The Where makes sure it prunes any nulls if you have an empty list as an item inside.
Alternatively you can implement it as:
string[][] = new[] {
new[]{"...","...","..."},
new[]{"...","...","..."},
... etc ...
};
This could be used similarly to a [x,y]
array but it's used like this: [x][y]
Or you could simply write:
ng-href="\#yourAnchorId"
Please notice the backslash in front of the hash symbol
You simply use the destroy()
method to delete the specified widgets like this:
lbl = tk.Label(....)
btn = tk.Button(....., command=lambda: lbl.destroy())
Using this you can completely destroy the specific widgets.
You should use the OpenFileDialog class like this
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Then you can use the File class.
I have just tested this and works fine.
string test = "Testing 1-2-3";
// convert string to stream
byte[] byteArray = Encoding.ASCII.GetBytes(test);
MemoryStream stream = new MemoryStream(byteArray);
// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
If stream
has already been written to, you might want to seek to the beginning before first before reading out the text: stream.Seek(0, SeekOrigin.Begin);
$ file=${$(basename $file_path)%.*}
You can also use sprintf:
char str[1024];
sprintf(str, "somtext %s sometext %s", somevar, somevar);
If the lines in the file end with \r\n\000 then what works is to delete the \n\000 then replace the \r with \n.
tr -d '\n\000' <infile | tr '\r' '\n' >outfile
For my situation, I switched the value of "fork" to false, such as <fork>false</fork>
. I do not understand why, hope someone could explain to me. Thanks in advance.
Use DATE()
function:
select * from follow_queue group by DATE(follow_date)
Working gradle dependency
Try this:
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
As other answers suggest... Some guy (for whatever reason) decided that your old code should not work when you upgrade your PHP, because he knows better than you and don't care about what your code does or how simple it is for you to upgrade.
Well, if you can't upgrade your project overnight you can
downgrade your version of PHP to whatever version that worked
or...
use a shim (kind of polyfill) such as https://github.com/dshafik/php7-mysql-shim or https://github.com/dotpointer/mysql-shim, and then find a place for
include_once("choice_shim.php");
somewhere in your code
That will keep your old PHP code up and running until you are in a mood to update...
You should rather use GROUP BY UNIX_TIMESTAMP(time_stamp) DIV 300
instead of round(../300) because of the rounding I found that some records are counted into two grouped result sets.
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
A form is not allowed to be a child element of a table
, tbody
or tr
. Attempting to put one there will tend to cause the browser to move the form to it appears after the table (while leaving its contents — table rows, table cells, inputs, etc — behind).
You can have an entire table inside a form. You can have a form inside a table cell. You cannot have part of a table inside a form.
Use one form around the entire table. Then either use the clicked submit button to determine which row to process (to be quick) or process every row (allowing bulk updates).
HTML 5 introduces the form
attribute. This allows you to provide one form per row outside the table and then associate all the form control in a given row with one of those forms using its id
.
I had a similar issue and none of the above solutions worked for me. Here's my try (requires jquery):
$(function() {
$('a[data-auto-download]').each(function(){
var $this = $(this);
setTimeout(function() {
window.location = $this.attr('href');
}, 2000);
});
});
Usage: Just add an attribute called data-auto-download
to the link pointing to the download in question:
<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="/your/file/url">here</a>.</p>
It should work in all cases.
select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;
Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.
Thanks @Clint for the great answer:
Just wanted to highlight how easy it was to solve this using the Expando Object:
var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
foreach (var property in properties) {
dynamicObject.Add(property.Key,property.Value);
}
Jar is an archive, you can replace a file in it by yourself in your favourite file manager (Total Commander for example).
As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.
ie:
public class Museo500TextView extends TextView {
public Museo500TextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
}
}
and
<my.package.views.Museo900TextView
android:id="@+id/dialog_error_text_header"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="12sp" />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
The above links need to be included
<context:property-placeholder location="classpath:sport.properties" />
<bean id="myFortune" class="com.kiran.springdemo.HappyFortuneService"></bean>
<bean id="myCoach" class="com.kiran.springdemo.setterinjection.MyCricketCoach">
<property name="fortuner" ref="myFortune" />
<property name="emailAddress" value="${ipl.email}" />
<property name="team" value="${ipl.team}" />
</bean>
</beans>
In my situation it was the error
namespace aspnetcore does not exist .. are you missing a reference?
I have figured it out by adding the -v (or --verbose) flag to the dotnet ef command.
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
Because of the way the function is called (i.e. as a simple call to a function variable), this
is the global object (for which window
is an alias in browsers). Use the obj
parameter instead.
Also, creating a jQuery object and the using its attr()
method for obtaining an element ID is inefficient and unnecessary. Just use the element's id
property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
Take a look at the man page of the pt-deadlock-logger
utility:
brew install percona-toolkit
pt-deadlock-logger --ask-pass server_name
It extracts information from the engine innodb status
mentioned above and also
it can be used to create a daemon
which runs every 30 seconds.
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps
You can find out what library depends on a wrong version of the support library and exclude it like this:
compile ('com.stripe:stripe-android:5.1.1') {
exclude group: 'com.android.support'
}
stripe-android
in my case.
One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:
https://developer.apple.com/videos/play/wwdc2015/407/
Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.
This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8
As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4
As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57
As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6
As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5
As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23
All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)
Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.
I hope this clarifies the subject a bit better!
Take care.
You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:
date.split(/[.,\/ -]/)
Although dashes have special meaning in character classes as a range specifier (ie [a-z]
means the same as [abcdefghijklmnopqrstuvwxyz]
), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.
To explain why your pattern didn't work, /-./
tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".
The main differences are:
1) OFFLINE index rebuild is faster than ONLINE rebuild.
2) Extra disk space required during SQL Server online index rebuilds.
3) SQL Server locks acquired with SQL Server online index rebuilds.
The HTC devices have the PCSII.apk
which allow them to select usb connect mode. For your device, you can set it manually:
Use SQLite Editor to open /data/data/com.android.providers.setting/databases/settings.db
open table secure
turn settings starting with mount_ums_
to 0, then restart devices.
UPDATE: If it still doesn't work, try turning on debug mode.
I frequently stumble upon this issue while bulk moving files to new subdirectories. Ideally, I want to do this:
mv * newdir/
Most of the answers in this thread propose to mkdir
and then mv
, but this results in:
mkdir newdir && mv * newdir
mv: cannot move 'newdir/' to a subdirectory of itself
The problem I face is slightly different in that I want to blanket move everything, and, if I create the new directory before moving then it also tries to move the new directory to itself. So, I work around this by using the parent directory:
mkdir ../newdir && mv * ../newdir && mv ../newdir .
Caveats: Does not work in the root folder (/
).
Use the C Standard Library function getchar()
instead as getch()
is not a standard function, being provided by Borland TURBO C for MS-DOS/Windows only.
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getchar();
Here, getchar()
expects you to press the return key so the printf
statement should be press ENTER to continue
. Even if you press another key, you still need to press ENTER:
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
getchar();
If you are using Windows then you can use getch()
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
//if you press any character it will continue ,
//but this is not a standard c function.
char ch;
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
//here also if you press any other key will wait till pressing ENTER
scanf("%c",&ch); //works as getchar() but here extra variable is required.
You use the modulo operator:
while(score)
{
printf("%d\n", score % 10);
score /= 10;
}
Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.
It's wrong. Use a span.
Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.
The relevant paragraph:
Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.
This makes lots of sense.
For your specific question.. the o
in the <o:p>
means "Office namespace" so anything following the o:
in a tag means "I'm part of Office namespace" - in case of <o:p>
it just means paragraph, the equivalent of the ordinary <p>
tag.
I assume that every HTML tag has its Office "equivalent" and they have more.
We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:
webapi:
[HttpPost]
public string DoJson2(dynamic data)
{
//whole:
var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString());
//or
var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());
var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());
string appName = data.AppName;
int appInstanceID = data.AppInstanceID;
string processGUID = data.ProcessGUID;
int userID = data.UserID;
string userName = data.UserName;
var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());
...
}
The complex object type could be object, array and dictionary.
ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
"AppInstanceID":"100",
"ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
"UserID":"20",
"UserName":"Jack",
"NextActivityPerformers":{
"39??c71004-d822-4c15-9ff2-94ca1068d745":[{
"UserID":10,
"UserName":"Smith"
}]
}}
...
Use:
$path = "C:\temp\"
If (!(test-path $path))
{
md C:\Temp\
}
The first line creates a variable named $path
and assigns it the string value of "C:\temp\"
The second line is an If
statement which relies on the Test-Path cmdlet to check if the variable $path
does not exist. The not exists is qualified using the !
symbol.
Third line: If the path stored in the string above is not found, the code between the curly brackets will be run.
md
is the short version of typing out: New-Item -ItemType Directory -Path $path
Note: I have not tested using the -Force
parameter with the below to see if there is undesirable behavior if the path already exists.
New-Item -ItemType Directory -Path $path
Here's how you can work with a custom schema, a complete demo:
$> shell code,
echo "
Slingo, iOS
Slingo, Android
" > game.csv
Scala code:
import org.apache.spark.sql.types._
val customSchema = StructType(Array(
StructField("game_id", StringType, true),
StructField("os_id", StringType, true)
))
val csv_df = spark.read.format("csv").schema(customSchema).load("game.csv")
csv_df.show
csv_df.orderBy(asc("game_id"), desc("os_id")).show
csv_df.createOrReplaceTempView("game_view")
val sort_df = sql("select * from game_view order by game_id, os_id desc")
sort_df.show
If you do not use the sender
argument, why not refactor the button handler implementation to separate function, and call it from wherever you want (from the button handler and from the other place).
Anyway, it is a better and cleaner design - a code that needs to be called on button handler AND from some other places deserves to be refactored to own function. Plus it will help you separate UI handling from application logic code. You will also have a nice name to the function, not just onDateSelectedButtonClick().
This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.
anaconda
. Latest version can be found hereanaconda-navigator
in terminalcreate
and then choose your python version in that. install
in that. Hope it helps!!
Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.
Use the quotemeta
function:
$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";
print "wee" if ($text_to_search =~ /$search_string/);
Maybe some AJAX page content injection could be used as an alternative, though I still can't get around why your teacher would refuse to rid the website of frames.
Additionally, is there any specific reason you personally want to us HTML5?
But if not, I believe <iframe>
s are still around.
including above solution if still facing issue try as below, Considerign the case where escape is not supported for TS.
blob = new Blob(["\ufeff", csv_content]); // this will make symbols to appears in excel
for csv_content you can try like below.
function b64DecodeUnicode(str: any) {
return decodeURIComponent(atob(str).split('').map((c: any) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).
You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:
Company: Vodafone
------------------
LSE symbol: VOD
in Google: LON:VOD
in Yahoo: VOD.L
NASDAQ symbol: VOD
in Google: NASDAQ:VOD
in Yahoo: VOD
in devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
Use outline:none
to anchor tag class
Suspended. The session is waiting for an event, such as I/O, to complete.
Because you need parentheses around the value your looking for.
So here : document.querySelector('a[data-a="1"]')
If you don't know in advance the value but is looking for it via variable you can use template literals :
Say we have divs with data-price
<div data-price="99">My okay price</div>
<div data-price="100">My too expensive price</div>
We want to find an element but with the number that someone chose (so we don't know it):
// User chose 99
let chosenNumber = 99
document.querySelector(`[data-price="${chosenNumber}"`]
Here is simple CSS rules that put any div in the center
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/
static inline void ut_trim(char * str) {
char * start = str;
char * end = start + strlen(str);
while (--end >= start) { /* trim right */
if (!isspace(*end))
break;
}
*(++end) = '\0';
while (isspace(*start)) /* trim left */
start++;
if (start != str) /* there is a string */
memmove(str, start, end - start + 1);
}
WHAT I HAVE FOUND AFTER HOURS OF MUCKING WITH THIS:
WORKS :
background-image: url(image_path('transparent_2x2.png'));
// how to add attributes like repeat, center, fixed?
The above outputs something like: "/assets/transparent_2x2-ec47061dbe4fb88d51ae1e7f41a146db.png"
Notice the leading "/", and it's within quotes. Also note the scss extension and image_path helper in yourstylesheet.css.scss. The image is in the app/assets/images directory.
Doesn't work:
background: url(image_path('transparent_2x2.png') repeat center center fixed;
doesn't work, invalid property:
background:url(/assets/pretty_photo/default/sprite.png) 2px 1px repeat center fixed;
My last resort was going to be to put these in my public s3 bucket and load from there, but finally got something going.
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
Use the classes found in the java.nio
namespace, in particular, the ByteBuffer
. It can do all the work for you.
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }
Fn + 7 is a solution for keyboards where the num keypad is merged with the main keypad. Here the key with 7 (and &) is the key that has the blue-coloured 7.
The problem was caused by not setting the CUDA_VISIBLE_DEVICES
variable within the shell correctly.
To specify CUDA device 1
for example, you would set the CUDA_VISIBLE_DEVICES
using
export CUDA_VISIBLE_DEVICES=1
or
CUDA_VISIBLE_DEVICES=1 ./cuda_executable
The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.
If you want to specify more than one device, use
export CUDA_VISIBLE_DEVICES=0,1
or
CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable
As android:editable="false"
deprecated
In xml
Use
android:enabled="false"
it's simple. Why use more code?
If you want in java class
you can also use this programmatically
editText.setEnabled(false);
If you had caught the error, you would have seen this:
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.Foo
The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using strconv.Itoa
.
See this post for more details: https://stackoverflow.com/a/24284721/2679935
Some people seem to turn autoescape off which carries security risks to manipulate the string display.
If you only want to insert some linebreaks into a string and convert the linebreaks into <br />
, then you could take a jinja macro like:
{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}
and in your template just call this with
{{ linebreaks_for_string( my_string_in_a_variable ) }}
myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
myDict[k] = A.get(k, 0)+B.get(k, 0)
If you have issues with JAR files not being found I would also ensure your CLASSPATH is set to include the location of those files. I do find however that the CLASSPATH often needs to be set differently for different programs and often ends up being something to set uniquely for individual programs.
With SQL 2014, I changed the SQL Server Service (MSSQL) to run as LocalSystem
. This solved the problem for me.
It used to work as NT_SERVICE\MSSQL$MSSQL
fine under 2008, from what I remember.
md5sum binary1 binary2
If the md5sum is same, binaries are same
E.g
md5sum new*
89c60189c3fa7ab5c96ae121ec43bd4a new.txt
89c60189c3fa7ab5c96ae121ec43bd4a new1.txt
root@TinyDistro:~# cat new*
aa55 aa55 0000 8010 7738
aa55 aa55 0000 8010 7738
root@TinyDistro:~# cat new*
aa55 aa55 000 8010 7738
aa55 aa55 0000 8010 7738
root@TinyDistro:~# md5sum new*
4a7f86919d4ac00c6206e11fca462c6f new.txt
89c60189c3fa7ab5c96ae121ec43bd4a new1.txt
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
One interesting fact about NULL
in PHP: If you set a var equal to NULL
, it is the same as if you had called unset()
on it.
NULL
essentially means a variable has no value assigned to it; false
is a valid Boolean value, 0
is a valid integer value, and PHP has some fairly ugly conversions between 0
, "0"
, ""
, and false
.
You can pass input as ["apple","orange"]
if you want to leave the method as it is.
It worked for me with a similar method signature.
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
I clear my screen using is function that
var clear_body = function (){
var lista = document.body.childNodes;
for (var i = lista.length - 1; i >= 0 ;i--){
document.body.removeChild(lista[i])
}
}
Just use .get(0) to grab the native element, and get its outerHTML property:
var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
While the other answers are correct (int array values are by default initialized to 0), if you wanted to explicitly do so (say for example if you wanted an array filled with the value 42), you can use the fill() method of the Arrays class:
int [] myarray = new int[num_elts];
Arrays.fill(myarray, 42);
Or if you're a fan of 1-liners, you can use the Collections.nCopies()
routine:
Integer[] arr = Collections.nCopies(3, 42).toArray(new Integer[0]);
Would give arr the value:
[42, 42, 42]
(though it's Integer
, and not int
, if you need the primitive type you could defer to the Apache Commons ArrayUtils.toPrimitive()
routine:
int [] primarr = ArrayUtils.toPrimitive(arr);
This is the basic skeleton that I always use for this. It makes it easy to implement timeouts and is able to deal with inevitable hanging processes.
import subprocess
import threading
import Queue
def t_read_stdout(process, queue):
"""Read from stdout"""
for output in iter(process.stdout.readline, b''):
queue.put(output)
return
process = subprocess.Popen(['dir'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
cwd='C:\\',
shell=True)
queue = Queue.Queue()
t_stdout = threading.Thread(target=t_read_stdout, args=(process, queue))
t_stdout.daemon = True
t_stdout.start()
while process.poll() is None or not queue.empty():
try:
output = queue.get(timeout=.5)
except Queue.Empty:
continue
if not output:
continue
print(output),
t_stdout.join()
input[type="button"]{
outline:none;
}
input[type="button"]::-moz-focus-inner {
border: 0;
}
/* Don't forget! User accessibility is important */
input[type="button"]:focus {
/* your custom focused styles here */
}
You can simply use the data-interval
attribute of the carousel
class.
It's default value is set to data-interval="3000"
i.e 3seconds.
All you need to do is set it to your desired requirements.
In Html use:
<b>
text</b>
that I want emboldened.<strong>
text</strong>
that I want emboldened.In CSS use:
<span style="font-weight:bold">
text</span>
that I want emboldened.This will disable/enable the options when you select/remove them, respectively.
$("#theSelect").change(function(){
var value = $(this).val();
if (value === '') return;
var theDiv = $(".is" + value);
var option = $("option[value='" + value + "']", this);
option.attr("disabled","disabled");
theDiv.slideDown().removeClass("hidden");
theDiv.find('a').data("option",option);
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
$(this).data("option").removeAttr('disabled');
});
If:
> char<-c("one", "two", "three")
You can:
> print(char[1],quote = FALSE)
Your result should be:
[1] one
MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ˜ 9.5 hours).
If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed
.
MySQL suggests:
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem.
You could try my wkhtmltopdf wrapper: https://github.com/pruiz/WkHtmlToXSharp ;)
For me, Error has been fixed when activated Billing in google console. (I got 1-year developer trial)
By default, all paths you define will be relative. The question is: relative to what? There are several options:
Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
To get the shape as a list of ints, do tensor.get_shape().as_list()
.
To complete your tf.shape()
call, try tensor2 = tf.reshape(tensor, tf.TensorShape([num_rows*num_cols, 1]))
. Or you can directly do tensor2 = tf.reshape(tensor, tf.TensorShape([-1, 1]))
where its first dimension can be inferred.
Working for me. SpringBoot.
import com.alibaba.fastjson.annotation.JSONField;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
output:
{
"createTime": "2019-06-14 13:07:21"
}
Use update
, stop
and receive
events, check it over here
100% Working!
To send HTML contents in the body of the mail on the go with Sender and Recipient mail address in single line, you may try the below,
export EMAIL="[email protected]" && mutt -e "my_hdr Content-Type: text/html" -s "Test Mail" "[email protected]" < body_html.html
File: body_html.html
<HTML>
<HEAD> Test Mail </HEAD>
<BODY>
<p>This is a <strong><span style="color: #ff0000;">test mail!</span></strong></p>
</BODY>
</HTML>
Note: Tested in RHEL, CentOS, Ubuntu.
Generating locales
Missing locales are generated with locale-gen:
locale-gen en_US.UTF-8
Alternatively a locale file can be created manually with localedef:[1]
localedef -i en_US -f UTF-8 en_US.UTF-8
Setting Locale Settings
The locale settings can be set (to en_US.UTF-8
in the example) as follows:
export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales
The dpkg-reconfigure locales
command will open a dialog under Debian for selecting the desired locale. This dialog will not appear under Ubuntu. The Configure Locales in Ubuntu article shows how to find the information regarding Ubuntu.
A bit more modern way to do it:
const selectedValues = $('input[name="locationthemes"]:checked').map( function () {
return $(this).val();
})
.get()
.join(', ');
We first find all the selected checkboxes with the given name, and then jQuery's map() iterates through each of them, calling the callback on it to get the value, and returning the result as a new jQuery collection that now holds the checkbox values. We then call get() on it to get an array of values, and then join() to concatenate them into a single string - which is then assigned to the constant selectedValues.
This can help you
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
Here is one way (put this in Page_Load):
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>var isPostBack = true;</script>");
}
Then just check that variable in the JS.
Simplest code is DataGridView1.SelectedCells(column_index).Value
As an example, for the first selected cell:
DataGridView1.SelectedCells(0).Value
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
Most terse version I can think of
Len(Trim(TextBox1.Value)) = 0
If you need to do this multiple times, wrap it in a function
Public Function HasContent(text_box as Object) as Boolean
HasContent = (Len(Trim(text_box.Value)) > 0)
End Function
Usage
If HasContent(TextBox1) Then
' ...
You declare the entity like this:
<!ENTITY otherFile SYSTEM "otherFile.xml">
Then you reference it like this:
&otherFile;
A complete example:
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE doc [
<!ENTITY otherFile SYSTEM "otherFile.xml">
]>
<doc>
<foo>
<bar>&otherFile;</bar>
</foo>
</doc>
When the XML parser reads the file, it will expand the entity reference and include the referenced XML file as part of the content.
If the "otherFile.xml" contained: <baz>this is my content</baz>
Then the XML would be evaluated and "seen" by an XML parser as:
<?xml version="1.0" standalone="no" ?>
<doc>
<foo>
<bar><baz>this is my content</baz></bar>
</foo>
</doc>
A few references that might be helpful:
This is probably the longest process to make a singleton in typescript, but in larger applications is the one that has worked better for me.
First you need a Singleton class in, let's say, "./utils/Singleton.ts":
module utils {
export class Singleton {
private _initialized: boolean;
private _setSingleton(): void {
if (this._initialized) throw Error('Singleton is already initialized.');
this._initialized = true;
}
get setSingleton() { return this._setSingleton; }
}
}
Now imagine you need a Router singleton "./navigation/Router.ts":
/// <reference path="../utils/Singleton.ts" />
module navigation {
class RouterClass extends utils.Singleton {
// NOTICE RouterClass extends from utils.Singleton
// and that it isn't exportable.
private _init(): void {
// This method will be your "construtor" now,
// to avoid double initialization, don't forget
// the parent class setSingleton method!.
this.setSingleton();
// Initialization stuff.
}
// Expose _init method.
get init { return this.init; }
}
// THIS IS IT!! Export a new RouterClass, that no
// one can instantiate ever again!.
export var Router: RouterClass = new RouterClass();
}
Nice!, now initialize or import wherever you need:
/// <reference path="./navigation/Router.ts" />
import router = navigation.Router;
router.init();
router.init(); // Throws error!.
The nice thing about doing singletons this way is that you still use all the beauty of typescript classes, it gives you nice intellisense, the singleton logic keeps someway separated and it's easy to remove if needed.
First of all, do a backup of your needed databases with mysqldump
Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).
In total, do this:
sudo service mysql stop #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql
All above commands in single line (just copy and paste):
sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql
This is going to sound stupid but I had a similar problem with a site being developed in VS2010 and hosted in the VS Dev Server. The page in question had a scriptmanager to create the connection to a wcf service. I added an extra method to the service and this error started appearing.
What fixed it for me was changing from 'Auto-assign Port' to 'Specific port' with a different port number in the oroject Web settings.
I wish I knew why...
WHERE MyColumn = COALESCE(@value,MyColumn)
If @value
is NULL
, it will compare MyColumn
to itself, ignoring
@value = no where
clause.
IF @value
has a value (NOT NULL
) it will compare MyColumn
to
@value
.
Reference: COALESCE (Transact-SQL).
You are looking for grep command.
You can read 15 Practical Grep Command Examples In Linux / UNIX for some samples.
If you are using Http Client version 4.3 and above you should be using this:
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).build();
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
in my case, datas
is an objects of Array for more information please Click Here
<% for(let [index,data] of datas.entries() || []){ %>
Index : <%=index%>
Data : <%=data%>
<%} %>
The accepted solution is probably the best bet for your purposes, but to actually answer the question in the subject line:
In my app, I have to get the path from URIs and get the URI from paths. The former:
/**
* Gets the corresponding path to a file from the given content:// URI
* @param selectedVideoUri The content:// URI to find the file path from
* @param contentResolver The content resolver to use to perform the query.
* @return the file path as a string
*/
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for MediaStore.Video):
/**
* Gets the MediaStore video ID of a given file on external storage
* @param filePath The path (on external storage) of the file to resolve the ID of
* @param contentResolver The content resolver to use to perform the query.
* @return the video ID as a long
*/
private long getVideoIdFromFilePath(String filePath,
ContentResolver contentResolver) {
long videoId;
Log.d(TAG,"Loading file " + filePath);
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri videosUri = MediaStore.Video.Media.getContentUri("external");
Log.d(TAG,"videosUri = " + videosUri.toString());
String[] projection = {MediaStore.Video.VideoColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
Log.d(TAG,"Video ID is " + videoId);
cursor.close();
return videoId;
}
Basically, the DATA
column of MediaStore
(or whichever sub-section of it you're querying) stores the file path, so you use that info to look it up.
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"
Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.
If System.IO.File.Exists(SavePath) Then
'The file exists
Else
'the file doesn't exist
End If
You cannot define a variable of an incomplete type. You need to bring the whole definition of Cat
into scope before you can create the local variable in main
. I recommend that you move the definition of the type Cat
to a header and include it from the translation unit that has main
.
stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/icon.png" )));
You can add more than one icon with different sizes using this method.The images should be different sizes of the same image and the best size will be chosen.
eg. 16x16, 32,32
I would store the timespan.TotalSeconds in a float and then retrieve it using Timespan.FromSeconds(totalSeconds).
Depending on the resolution you need you could use TotalMilliseconds, TotalMinutes, TotalDays.
You could also adjust the precision of your float in the database.
It's not an exact value... but the nice thing about this is that it's easy to read and calculate in simple queries.
Add this to your global.asax.cs:
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
Here's how you could do it in Coffee Script (just if anyone is interested).
decodeURIComponent( v.split( "=" )[1] ) if decodeURIComponent( v.split( "=" )[0] ) == name for v in window.location.search.substring( 1 ).split( "&" )
Since this was asked there were a bit of new developments: it is important to know that std::isnan()
is part of C++11
Defined in header <cmath>
bool isnan( float arg ); (since C++11)
bool isnan( double arg ); (since C++11)
bool isnan( long double arg ); (since C++11)
Determines if the given floating point number arg is not-a-number (NaN
).
Parameters
arg
: floating point value
Return value
true
if arg is NaN
, false
otherwise
Reference
http://en.cppreference.com/w/cpp/numeric/math/isnan
Please note that this is incompatible with -fast-math if you use g++, see below for other suggestions.
For C99, in C, this is implemented as a macro isnan(c)
that returns an int value. The type of x
shall be float, double or long double.
Various vendors may or may not include or not a function isnan()
.
The supposedly portable way to check for NaN
is to use the IEEE 754 property that NaN
is not equal to itself: i.e. x == x
will be false for x
being NaN
.
However the last option may not work with every compiler and some settings (particularly optimisation settings), so in last resort, you can always check the bit pattern ...
The thing on the right of <-
is a formula
object. It is often used to denote a statistical model, where the thing on the left of the ~
is the response and the things on the right of the ~
are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".
The myFormula <-
part of that line stores the formula in an object called myFormula
so you can use it in other parts of your R code.
Other common uses of formula objects in R
The lattice
package uses them to specify the variables to plot.
The ggplot2
package uses them to specify panels for plotting.
The dplyr
package uses them for non-standard evaulation.
If getFiles() returns a java.util.Collection
, !getFiles().isEmpty() && size<5 can be OK.
On the other hand, unless you encapsulate the container which provides method such as boolean sizeBetween(int min, int max)
.
Here is a simple solution which handles tabs and/or whitespaces in the filename. If you have to deal with other strange characters in the filename like newlines, pick another answer.
The test directory
ls -F test
Baltimore/ Cherry Hill/ Edison/ New York City/ Philadelphia/ cities.txt
The code to go into the directories
find test -type d | while read f ; do
echo "$f"
done
The filename must be quoted ("$f"
) if used as argument. Without quotes, the spaces act as argument separator and multiple arguments are given to the invoked command.
And the output:
test/Baltimore
test/Cherry Hill
test/Edison
test/New York City
test/Philadelphia
Resolved this issue by using http(s)
when accessing the endpoint. The route I was accessing was not available over http
. So I would say verify the protocols for which the route is available.
I have (Open)JDK 8 and 11 installed on Windows 10 and I had the same problem. For me the following worked:
You can get the values with use of ID
. But ID
should be Unique.
<body>
<h1>Adding 'a' and 'b'</h1>
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
a = $('#a').val();
b = $('#b').val();
var sum = a + b;
alert(sum);
}
</script>
</body>
This is the right answer
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/favorites_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:rowCount="2"
android:columnCount="2">
<Button
android:text="Cell 0"
android:layout_row="0"
android:layout_column="0"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:textSize="14dip"
/>
<Button
android:text="Cell 1"
android:layout_row="0"
android:layout_column="1"
android:textSize="14dip"
android:layout_columnWeight="1"
android:layout_rowWeight="1"/>
<Button
android:text="Cell 2"
android:layout_row="1"
android:layout_column="0"
android:textSize="14dip"
android:layout_columnWeight="1"
android:layout_rowWeight="1"/>
<Button
android:text="Cell 3"
android:layout_row="1"
android:layout_column="1"
android:textSize="14dip"
android:layout_columnWeight="1"
android:layout_rowWeight="1"/>
</GridLayout>
Assign something to your strings. This will definitely help.
>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]
To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser
or the string.Split
method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.
I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.
I deserialize my CSV file with the following method:
public static IEnumerable<T> ReadCsvFileTextFieldParser<T>(string fileFullPath, string delimiter = ";") where T : new()
{
if (!File.Exists(fileFullPath))
{
return null;
}
var list = new List<T>();
var csvFields = GetAllFieldOfClass<T>();
var fieldDict = new Dictionary<int, MemberInfo>();
using (TextFieldParser parser = new TextFieldParser(fileFullPath))
{
parser.SetDelimiters(delimiter);
bool headerParsed = false;
while (!parser.EndOfData)
{
//Processing row
string[] rowFields = parser.ReadFields();
if (!headerParsed)
{
for (int i = 0; i < rowFields.Length; i++)
{
// First row shall be the header!
var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
if (csvField != null)
{
fieldDict.Add(i, csvField);
}
}
headerParsed = true;
}
else
{
T newObj = new T();
for (int i = 0; i < rowFields.Length; i++)
{
var csvFied = fieldDict[i];
var record = rowFields[i];
if (csvFied is FieldInfo)
{
((FieldInfo)csvFied).SetValue(newObj, record);
}
else if (csvFied is PropertyInfo)
{
var pi = (PropertyInfo)csvFied;
pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
}
else
{
throw new Exception("Unhandled case.");
}
}
if (newObj != null)
{
list.Add(newObj);
}
}
}
}
return list;
}
public static IEnumerable<MemberInfo> GetAllFieldOfClass<T>()
{
return
from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
select mi;
}
Assuming you don't have extraneous whitespace:
with open('file') as f:
w, h = [int(x) for x in next(f).split()] # read first line
array = []
for line in f: # read rest of lines
array.append([int(x) for x in line.split()])
You could condense the last for loop into a nested list comprehension:
with open('file') as f:
w, h = [int(x) for x in next(f).split()]
array = [[int(x) for x in line.split()] for line in f]
UPDATE 2020 JULY
Preview version of chromium based WebView 2 is released by the Microsoft. Now you can embed new Chromium Edge browser into a .NET application.
UPDATE 2018 MAY
If you're targeting application to run on Windows 10, then now you can embed Edge browser into your .NET application by using Windows Community Toolkit.
WPF Example:
Install Windows Community Toolkit Nuget Package
Install-Package Microsoft.Toolkit.Win32.UI.Controls
XAML Code
<Window
x:Class="WebViewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPF="clr-namespace:Microsoft.Toolkit.Win32.UI.Controls.WPF;assembly=Microsoft.Toolkit.Win32.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WebViewTest"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<WPF:WebView x:Name="wvc" />
</Grid>
</Window>
CS Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// You can also use the Source property here or in the WPF designer
wvc.Navigate(new Uri("https://www.microsoft.com"));
}
}
WinForms Example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// You can also use the Source property here or in the designer
webView1.Navigate(new Uri("https://www.microsoft.com"));
}
}
Please refer to this link for more information.
If you want to use LinearLayout, you can do alignment with layout_weight
with Space
element.
E.g. following layout places textView
and textView2
next to each other and textView3
will be right-aligned
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView2" />
<Space
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView3" />
</LinearLayout>
you can achieve the same effect without Space
if you would set layout_weight
to textView2
. It's just that I like things more separated, plus to demonstrate Space
element.
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView2" />
Note that you should (not must though) set layout_width
explicitly as it will be recalculated according to it's weight anyway (same way you should set height in elements of vertical LinearLayout
). For other layout performance tips see Android Layout Tricks series.
You could have the value of the input field copied to a hidden field whenever focus leaves the input field (which should do what you want). See code below:
<script>
$(document).ready(function(){
$('#myInputElement').bind('change', function(){
var newvalue = $(this).val();
});
$('#myInputElement').blur(function(){
$('#myHiddenInput').val($(this).val());
});
});
</script>
<input id="myInputElement" type="text">
(untested, but it should work).
create a view for each subquery is the way to go. Got it working like a charm.
For me the problem was wsgi python version mismatch. I was using python 3, so:
$ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi
$ sudo apt-get install libapache2-mod-wsgi-py3
Warning from @alxs before you copy/paste these commands:
If there are python 2 projects running on the server that use wsgi and apache, the above commands will effectively shut them down.
.background{_x000D_
background: -webkit-linear-gradient(top, #2897e0 40%, #F1F1F1 40%);_x000D_
height:200px;_x000D_
_x000D_
}_x000D_
_x000D_
.background2{_x000D_
background: -webkit-linear-gradient(right, #2897e0 50%, #28e09c 50%);_x000D_
_x000D_
height:200px;_x000D_
_x000D_
}
_x000D_
<html>_x000D_
<body class="one">_x000D_
_x000D_
<div class="background">_x000D_
</div>_x000D_
<div class="background2">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
One possible cause of this linker error can also be inline
functions that are declared but not defined in a header file that is then included somewhere else. Inline functions have to be defined in every translation unit they are used in.
MySQL 5.7 and above saves root in MySQL log file.
Please try this:
sudo grep 'temporary password' /var/log/mysqld.log
Or use awk
instead:
awk '/null/ { counter++; printf("%s%s%i\n",$0, " - Line number: ", NR)} END {print "Total null count: " counter}' file
This worked for me
Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
{ "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };
String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };
int noOfColumns = headers.length;
int rowCount = 0;
Row rowZero = sheet.createRow(rowCount++);
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
for (int col = 1; col <= noOfColumns; col++) {
Cell cell = rowZero.createCell(col);
cell.setCellValue(headers[col - 1]);
cell.setCellStyle(style);
}
No. We cannot alter the constraint, only thing we can do is drop and recreate it
ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]
Foreign Key Constraint
Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade
Primary Key constraint
Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)
I will add UMLet which I haven't tried yet, but have been selected at my office to start doing diagrams.
Looks simple, diagrams aren't sexy, but it seems quite complete with regard to the kind of diagrams you can do. Seems to have good export capabilities too (important!), is flexible can support custom components) and can be used as Eclipse plugin.
<div>
<iframe id="myFrame" src="https://player.vimeo.com/video/12345678?autoplay=1" width="640" height="360" frameborder="0" allowfullscreen> .
</iframe>
</div>
<script>
function myFunction() {
var wscreen = window.innerWidth;
var hscreen = window.innerHeight;
document.getElementById("myFrame").width = wscreen ;
document.getElementById("myFrame").height = hscreen ;
}
myFunction();
window.addEventListener('resize', function(){ myFunction(); });
</script>
this works on Vimeo adding an id myFrame
to the iframe
An overlay is, simply put, a div
that stays fixed on the screen (no matter if you scroll) and has some sort of opacity.
This will be your CSS for cross browser opacity of 0.5:
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
z-index: 10000;
}
This will be your jQuery code (no UI needed). You're just going to create a new element with the ID #overlay. Creating and destroying the DIV should be all you need.
var overlay = jQuery('<div id="overlay"> </div>');
overlay.appendTo(document.body)
For performance reasons you might wanna have the DIV hidden and setting the display to block and none as you need it or not.
Hope it helps!
Edit: As @Vitaly so well put it, be sure to check your DocType. Read more on the comments on his findings..
An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.
A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.
So for example:
public abstract class myBase
{
//If you derive from this class you must implement this method. notice we have no method body here either
public abstract void YouMustImplement();
//If you derive from this class you can change the behavior but are not required to
public virtual void YouCanOverride()
{
}
}
public class MyBase
{
//This will not compile because you cannot have an abstract method in a non-abstract class
public abstract void YouMustImplement();
}
This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.
<GridTile
key={video_id}
title={video_title}
containerElement={<Link to={`/player/${video_id}`}/>}
>
ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )
For anyone else having the same problem, I figured it out myself.
<html>_x000D_
<body>_x000D_
<form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
<input type="hidden" name="fullname" value="Sam" />_x000D_
<input type="hidden" name="city" value="Dubai " />_x000D_
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
You need to add:
#include <cstdlib>
in order for the compiler to see the prototype for system()
.
I mixed few answers from answers above and from How to remove the arrows from input[type="number"] in Opera in scss:
input[type=number] {
&,
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: textfield;
appearance: none;
&:hover,
&:focus {
-moz-appearance: number-input;
}
}
}
Tested on chrome, firefox, safari
very easy : use "\n"
String aString1 = "abcd";
String aString2 = "1234";
mSomeTextView.setText(aString1 + "\n" + aString2);
\n corresponds to ASCII char 0xA, which is 'LF' or line feed
\r corresponds to ASCII char 0xD, which is 'CR' or carriage return
this dates back from the very first typewriters, where you could choose to do only a line feed (and type just a line lower), or a line feed + carriage return (which also moves to the beginning of a line)
on Android / java the \n corresponds to a carriage return + line feed, as you would otherwise just 'overwrite' the same line
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Algorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JOptionPane;
/**
*
* @author Mokhtar
*/
public class Anagrams {
//Write aprogram to check if two words are anagrams
public static void main(String[] args) {
Anagrams an=new Anagrams();
ArrayList<String> l=new ArrayList<String>();
String result=JOptionPane.showInputDialog("How many words to test anagrams");
if(Integer.parseInt(result) >1)
{
for(int i=0;i<Integer.parseInt(result);i++)
{
String word=JOptionPane.showInputDialog("Enter word #"+i);
l.add(word);
}
System.out.println(an.isanagrams(l));
}
else
{
JOptionPane.showMessageDialog(null, "Can not be tested, \nYou can test two words or more");
}
}
private static String sortString( String w )
{
char[] ch = w.toCharArray();
Arrays.sort(ch);
return new String(ch);
}
public boolean isanagrams(ArrayList<String> l)
{
boolean isanagrams=true;
ArrayList<String> anagrams = null;
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for(int i=0;i<l.size();i++)
{
String word = l.get(i);
String sortedWord = sortString(word);
anagrams = map.get( sortedWord );
if( anagrams == null ) anagrams = new ArrayList<String>();
anagrams.add(word);
map.put(sortedWord, anagrams);
}
for(int h=0;h<l.size();h++)
{
if(!anagrams.contains(l.get(h)))
{
isanagrams=false;
break;
}
}
return isanagrams;
//}
}
}
You can do this by casting the dict keys and values to list. It can also be be done for items.
Example:
f = {'one': 'police', 'two': 'oranges', 'three': 'car'}
list(f.keys())[0] = 'one'
list(f.keys())[1] = 'two'
list(f.values())[0] = 'police'
list(f.values())[1] = 'oranges'
Either install v23.0.1 of the build tools (the fifth row in your screenshot), or change your code to use the build tools version you already have installed (v23.0.3). This can be specified in your app's build.gradle
file:
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
...
}
}
As per duncanc4's comment below,
The build.gradle file you want to edit is in the android/app folder within your project directory.
To update latest plus one id
ALTER TABLE table_name AUTO_INCREMENT =
(SELECT (id+1) id FROM table_name order by id desc limit 1);
You can query Active directory via JNDI and run LDAP operations
http://docs.oracle.com/javase/tutorial/jndi/ldap/authentication.html
http://docs.oracle.com/javase/tutorial/jndi/ldap/operations.html
http://mhimu.wordpress.com/2009/03/18/active-directory-authentication-using-javajndi/
just disable eslint for the next line;
useEffect(() => {
fetchBusinesses();
// eslint-disable-next-line
}, []);
in this way you are using it just like a component did mount (called once)
updated
or
const fetchBusinesses = useCallback(() => {
// your logic in here
}, [someDeps])
useEffect(() => {
fetchBusinesses();
// no need to skip eslint warning
}, [fetchBusinesses]);
fetchBusinesses will be called everytime someDeps will change
This would do it.
public static void main(String[] args) {
double d = 12.349678;
int r = (int) Math.round(d*100);
double f = r / 100.0;
System.out.println(f);
}
You can short this method, it's easy to understand that's why I have written like this.
According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either "%20
" or "+
". From the section "Query strings" under "Recommendations":
Within the query string, the plus sign is reserved as shorthand notation for a space. Therefore, real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.
According to section 3.4 of RFC2396 which is the official specification on URIs in general, the "query" component is URL-dependent:
3.4. Query Component The query component is a string of information to be interpreted by the resource.
query = *uric
Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.
It is therefore a bug in the other software if it does not accept URLs with spaces in the query string encoded as "+
" characters.
As for the third part of your question, one way (though slightly ugly) to fix the output from URLEncoder.encode()
is to then call replaceAll("\\+","%20")
on the return value.
I was also getting the same error.
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
and when i typed the localhost in the browser, then i was getting
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet. instead of nginx welcome page, apache2 is running on the same port,
find the apache2 ports.conf file
sudo /etc/apache2/ports.conf
change the port other then 80
, i make it as 70
save the file
restart your system
it will works for you also, if you type the localhost in the browser, you will get nginx welcome page
Similar to @craig, I recently built a shortcut library.
https://github.com/blainekasten/shortcut.js
Chainable API with support for multple functions bound to one shortcut.
Try this
frame$twohouses <- ifelse(frame$data>1, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
6 2 2
7 3 2
8 1 1
9 4 2
10 3 2
11 2 2
12 4 2
13 0 1
14 1 1
15 2 2
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
Depending on your ssh client, you can set the StrictHostKeyChecking option to no on the command line, and/or send the key to a null known_hosts file. You can also set these options in your config file, either for all hosts or for a given set of IP addresses or host names.
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
EDIT
As @IanDunn notes, there are security risks to doing this. If the resource you're connecting to has been spoofed by an attacker, they could potentially replay the destination server's challenge back to you, fooling you into thinking that you're connecting to the remote resource while in fact they are connecting to that resource with your credentials. You should carefully consider whether that's an appropriate risk to take on before altering your connection mechanism to skip HostKeyChecking.
Here is a practical addition to the answers of PierreBdR and Moe:
dir()
seems to be enough.For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir()
, look for __class__
, and then to go for its __bases__
:
# code borrowed from the rlcompleter module
# tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
# or: from rlcompleter import get_class_members
def get_class_members(klass):
ret = dir(klass)
if hasattr(klass,'__bases__'):
for base in klass.__bases__:
ret = ret + get_class_members(base)
return ret
def uniq( seq ):
""" the 'set()' way ( use dict when there's no set ) """
return list(set(seq))
def get_object_attrs( obj ):
# code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
ret = dir( obj )
## if "__builtins__" in ret:
## ret.remove("__builtins__")
if hasattr( obj, '__class__'):
ret.append('__class__')
ret.extend( get_class_members(obj.__class__) )
ret = uniq( ret )
return ret
(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs()
as for dir()
, and for old-style classes the main addition to the dir()
output seem to be the __class__
attribute.)
Firstly let us understand the concepts of curl, libcurl and PHP/cURL.
curl: A command line tool for getting or sending files using URL syntax.
libcurl: a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
PHP/cURL: The module for PHP that makes it possible for PHP programs to use libcurl.
How to use it:
step1: Initialize a curl session use curl_init().
step2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to.Append a search term "curl" using parameter "q=".Set option CURLOPT_RETURNTRANSFER, true will tell curl to return the string instead ofprint it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.
step3: Execute the curl session using curl_exec().
step4: Close the curl session we have created.
step5: Output the return string.
Make DEMO :
You will need to create two PHP files and place them into a folder that your web server can serve PHP files from. In my case I put them into /var/www/ for simplicity.
1. helloservice.php and 2. demo.php
helloservice.php is very simple and essentially just echoes back any data it gets:
<?php
// Here is the data we will be sending to the service
$some_data = array(
'message' => 'Hello World',
'name' => 'Anand'
);
$curl = curl_init();
// You can also set the URL you want to communicate with by doing this:
// $curl = curl_init('http://localhost/echoservice');
// We POST the data
curl_setopt($curl, CURLOPT_POST, 1);
// Set the url path we want to call
curl_setopt($curl, CURLOPT_URL, 'http://localhost/demo.php');
// Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Insert the data
curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data);
// You can also bunch the above commands into an array if you choose using: curl_setopt_array
// Send the request
$result = curl_exec($curl);
// Get some cURL session information back
$info = curl_getinfo($curl);
echo 'content type: ' . $info['content_type'] . '<br />';
echo 'http code: ' . $info['http_code'] . '<br />';
// Free up the resources $curl is using
curl_close($curl);
echo $result;
?>
2.demo.php page, you can see the result:
<?php
print_r($_POST);
//content type: text/html; charset=UTF-8
//http code: 200
//Array ( [message] => Hello World [name] => Anand )
?>
This line
secondNumber = Screen.text!.toInt()!
means: Get the Screen object, get the text property and please crash if it doesn't exist, then get the text converted to an integer, and please crash if it doesn't exist.
That's what the !
means: "I am sure this thing exists, so please crash if it doesn't". And crash is what it did.
As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper()
(which implies drug is a string).
But that's not your error, as your function medications_minimum3()
doesn't even use the second argument (something you should fix).
TypeError: unhashable type: 'list'
usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1
-- are you sure that row[11]
is of the right type? Sounds to me it might be a list.
Try:
insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
ts.tax_status_id,
( select r.recipient_id
from recipient r
where r.recipient_code = ?
)
from tax_status ts
where ts.tax_status_code = ?
For the bootstrap 4 beta were some big changes between the alpha and beta versions of bootstrap (and also bootstrap 3), esp. in regards to form validation.
First, to place the icons correctly you'll need to add styling which equates to what was in bootstrap 3 and no longer in bootstrap 4 beta...here's what I'm using
.fa.valid-feedback,
.fa.invalid-feedback {
position: absolute;
right: 25px;
margin-top: -50px;
z-index: 2;
display: block;
pointer-events: none;
}
.fa.valid-feedback {
margin-top: -28px;
}
The classes have also changed as the beta uses the 'state' of the control rather than classes which your posted code doesn't reflect, so your above code may not work. Anyway, you'll need to add 'was-validated' class to the form either in the success or highlight/unhighlight callbacks
$(element).closest('form').addClass('was-validated');
I would also recommend using the new element and classes for form control help text
errorElement: 'small',
errorClass: 'form-text invalid-feedback',
If an item is child of an item that is hidden is(":visible") will return true, which is incorrect.
I just fixed this by added "display:inherit" to the child item. This will fixed it for me:
<div class="parent">
<div class="child">
</div>
<div>
and the CSS:
.parent{
display: hidden;
}
.child{
display: inherit;
}
Now the item can be effectively switched on and off by changing the visibility of the parent, and $(element).is(":visible") will return the visibility of the parent item
Use os.walk
with next
item function:
next(os.walk('.'))[1]
For Python <=2.5 use:
os.walk('.').next()[1]
os.walk
is a generator and calling next
will get the first result in the form of a 3-tuple (dirpath, dirnames, filenames). Thus the [1]
index returns only the dirnames
from that tuple.
Here's a simple example function using python. You can stick in ~/.bashrc
You gotta have a space after the first left curly bracket
The python command needs to be in double quotes to get the variable substitution
Don't forget that semicolon at the end
function count(){ python -c "for num in xrange($1):print num";}
$ count 6
0
1
2
3
4
5
$
You need to install mysql server for your machine first. Once done, you will be able to add local db details to it.
For e.g. IP: 127.0.0.1
port: 3306
user: root
pass: pass of root which you have set
Here is the link on step by step guide for linux.
https://support.rackspace.com/how-to/install-mysql-server-on-the-ubuntu-operating-system/
Updated list as of 6/11/2013
204.15.20.0/22
69.63.176.0/20
66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20
From themomorohoax.com:
A bang can used in the below ways, in order of my personal preference.
1) An active record method raises an error if the method does not do what it says it will.
2) An active record method saves the record or a method saves an object (e.g. strip!)
3) A method does something “extra”, like posts to someplace, or does some action.
The point is: only use a bang when you’ve really thought about whether it’s necessary, to save other developers the annoyance of having to check why you are using a bang.
The bang provides two cues to other developers.
1) that it’s not necessary to save the object after calling the method.
2) when you call the method, the db is going to be changed.
http://www.themomorohoax.com/2009/02/11/when-to-use-a-bang-exclamation-point-after-rails-methods
The most important question is: what do you mean by 'loading'? If you are talking about the physical element being mounted, some of the first answers here are great. However, if the first thing your app does is check for authentication, what you are really loading is data from the backend whether the user passed a cookie that labels them an authorized or unauthorized user.
This is based around redux, but you can do easily change it to plain react state model.
action creator:
export const getTodos = () => {
return async dispatch => {
let res;
try {
res = await axios.get('/todos/get');
dispatch({
type: AUTH,
auth: true
});
dispatch({
type: GET_TODOS,
todos: res.data.todos
});
} catch (e) {
} finally {
dispatch({
type: LOADING,
loading: false
});
}
};
};
The finally part means whether the user is authed or not, the loading screen goes away after a response is received.
Here's what a component that loads it could look like:
class App extends Component {
renderLayout() {
const {
loading,
auth,
username,
error,
handleSidebarClick,
handleCloseModal
} = this.props;
if (loading) {
return <Loading />;
}
return (
...
);
}
...
componentDidMount() {
this.props.getTodos();
}
...
render() {
return this.renderLayout();
}
}
If state.loading is truthy, we will always see a loading screen. On componentDidMount, we call our getTodos function, which is an action creator that turns state.loading falsy when we get a response (which can be an error). Our component updates, calls render again, and this time there is no loading screen because of the if statement.
In the top of the bootstrap.css
you should have comments like the below:
/*!
* Bootstrap v2.3.1
*
* Copyright 2012 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world @twitter by @mdo and @fat.
*/
If they are not there, then they have probably been deleted.
VERSIONS:
You can review version history here. Backward compatibility shouldn't be broken if the source is v2.0.0 (Jan 2012) and above. If it is prior to v2.0.0 there are details on upgrading here.
To declare a string literal as an output column, leave the Table
off and just use Test
. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta()
, the table name will be an empty string because it isn't associated with a table.
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.
If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:
SELECT
field1,
field2,
field3
FROM
/* subquery wraps all fields to put the literal inside a table */
(SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test
Now field3
will come in the output as Test.field3
.
You can use the "extract" or "date_part" functions on intervals as well as timestamps, but I don't think that does what you want. For example, it gives 3 for an interval of '2 days, 3 hours'. However, you can convert an interval to a number of seconds by specifying 'epoch' as the time element you want: extract(epoch from '2 days, 3 hours'::interval)
returns 183600 (which you then divide by 3600 to convert seconds to hours).
So, putting this all together, you get basically Michael's answer: extract(epoch from timestamp1 - timestamp2)/3600
. Since you don't seem to care about which timestamp precedes which, you probably want to wrap that in abs
:
SELECT abs(extract(epoch from timestamp1 - timestamp2)/3600)
instead of try
ing & catch
ing expressions.. its better to run regex on the string to ensure that it is a valid number..
If your concern was only that you making a extra column and deleting it later, just dun use a new column at the first place.
dataframe = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'), 'col3':list('ababb')})
dataframe.col3 = pd.Categorical.from_array(dataframe.col3).codes
You are done. Now as Categorical.from_array
is deprecated, use Categorical
directly
dataframe.col3 = pd.Categorical(dataframe.col3).codes
If you also need the mapping back from index to label, there is even better way for the same
dataframe.col3, mapping_index = pd.Series(dataframe.col3).factorize()
check below
print(dataframe)
print(mapping_index.get_loc("c"))
I'm using SSH to authenticate my GitHub account and have a couple dependencies in my project installed as follows:
"dependencies": {
"<dependency name>": "git+ssh://[email protected]/<github username>/<repository name>.git#<release version | branch>"
}
Ensure these two and it should work:-
Fixes this issue on windows like a charm.
select regexp_replace('This is a test ' || chr(9) || ' foo ', '[[:space:]]', '') from dual;
REGEXP_REPLACE
--------------
Thisisatestfoo
You can catch key event :
function checkEventObj ( _event_ ){
// --- IE explorer
if ( window.event )
return window.event;
// --- Netscape and other explorers
else
return _event_;
}
document.keydown = function(_event) {
var e = checkEventObject(_event);
if( e.ctrlKey && (e.keyCode == 86) )
window.clipboardData.clearData();
}
Not tested but, could help.
Source from comentcamarche and Zakaria
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.
On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.
I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.
We found it practical and useful to put the version in the URL. It makes it easy to tell what you're using at a glance. We do alias /foo to /foo/(latest versions) for ease of use, shorter / cleaner URLs, etc, as the accepted answer suggests.
Keeping backwards compatibility forever is often cost-prohibitive and/or very difficult. We prefer to give advanced notice of deprecation, redirects like suggested here, docs, and other mechanisms.
I found the androidx.appcompat:appcompat:1.1.0
bug can also be fixed by simply calling getResources()
in applyOverrideConfiguration()
@Override public void
applyOverrideConfiguration(Configuration cfgOverride)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// add this to fix androidx.appcompat:appcompat 1.1.0 bug
// which happens on Android 6.x ~ 7.x
getResources();
}
super.applyOverrideConfiguration(cfgOverride);
}
You should never use TortoiseProc.exe as a command-line Subversion client! TortoiseProc should be utilized only for automating TortoiseSVN's GUI. See the note in TortoiseSVN's Manual:
Remember that TortoiseSVN is a GUI client, and this automation guide shows you how to make the TortoiseSVN dialogs appear to collect user input. If you want to write a script which requires no input, you should use the official Subversion command line client instead.
Use the Subversion command-line svn.exe client. With the command-line client, you can
checkout a working copy in REV revision:
svn checkout --revision REV https://svn.example.com/svn/MyRepo/trunk/
svn checkout https://svn.example.com/svn/MyRepo/trunk/@REV
update your local working copy to REV revision:
export (i.e. download) a file or a development branch in REV revision:
svn export --revision REV https://svn.example.com/svn/MyRepo/trunk/
svn export https://svn.example.com/MyRepo/trunk/@REV
You may notice that with svn checkout
and svn export
you can enter REV number as --revision REV
argument and as trailing @REV
after URL. The first one is called operative revision, and the second one is called peg revision. Read SVNBook for more information about peg and operative revisions concept.
You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js
Example code:
phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf
For deleting all data:
HTML FILE
class="btn btn-primary" href="{% url 'delete_product'%}">Delete
Put the above code in an anchor tag. (the a tag!)
url.py
path('delete_product', views.delete_product, name='delete_product')]
views.py
def delete_product(request):
if request.method == "GET":
dest = Racket.objects.all()
dest.delete()
return render(request, "admin_page.html")
On Mac after installing Android Studio IDE android-studio-ide-173.4907809-mac.dmg
and using studio SDK Manager to install SDK Tools
Add to your PATH using ~/.profile
or ~/.bash_profile
and make sure you have $ANDROID_HOME/emulator
in your $PATH
before $ANDROID_HOME/tools
like so:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
alias androidemulator='emulator -avd Nexus_5X_API_28_x86'
First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
urlString.append("&key=YOUR_API_KEY");
return urlString.toString();
}
This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
This parser will return us string. We will call it like that.
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
Now we will send this string to our drawpath function. The drawpath function is
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
}
catch (JSONException e) {
}
}
Above code will draw the path on mMap. The code of decodePoly is
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
drawPath(result);
}
}
}
I hope it will help.
$apply
should be called?TL;DR:
$apply
should be called whenever you want to apply changes made outside of Angular world.
Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.
$apply()
is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.
Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed.
That step that checks to see if any binding values have changed actually has a method, $scope.$digest()
1. We almost never call it directly, as we use $scope.$apply()
instead (which will call $scope.$digest
).
Angular only monitors variables used in expressions and anything inside of a $watch
living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply()
for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.
Another modification of pagewils code... his doesn't print out anything other than strings and leaves the number and boolean fields blank and I fixed the typo on the second typeof just inside the function as created by megaboss.
var print = function( o, maxLevel, level )
{
if ( typeof level == "undefined" )
{
level = 0;
}
if ( typeof maxlevel == "undefined" )
{
maxLevel = 0;
}
var str = '';
// Remove this if you don't want the pre tag, but make sure to remove
// the close pre tag on the bottom as well
if ( level == 0 )
{
str = '<pre>'; // can also be <pre>
}
var levelStr = '<br>';
for ( var x = 0; x < level; x++ )
{
levelStr += ' '; // all those spaces only work with <pre>
}
if ( maxLevel != 0 && level >= maxLevel )
{
str += levelStr + '...<br>';
return str;
}
for ( var p in o )
{
switch(typeof o[p])
{
case 'string':
case 'number': // .tostring() gets automatically applied
case 'boolean': // ditto
str += levelStr + p + ': ' + o[p] + ' <br>';
break;
case 'object': // this is where we become recursive
default:
str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
break;
}
}
// Remove this if you don't want the pre tag, but make sure to remove
// the open pre tag on the top as well
if ( level == 0 )
{
str += '</pre>'; // also can be </pre>
}
return str;
};
Just in case it helps: there is a way to edit a symlink with midnight commander (mc). The menu command is (in French on my mc interface):
Fichier / Éditer le lien symbolique
which may be translated to:
File / Edit symbolic link
The shortcut is C-x C-s
Maybe it internally uses the ln --force
command, I don't know.
Now, I'm trying to find a way to edit a whole lot of symlinks at once (that's how I arrived here).
You can use Rout redirecting.
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.RedirectToRoute("CMS_1");
}
which requires to define your routing logic in Global.asax file that could be like that:
routes.MapPageRoute("CMS_1", "CMS_1", "~/CMS_1.aspx");
where any request by CMS_1 pattern in application scope will be redirecting to CMS_1.aspx, but in URL shows like www.yoursite.com/CMS_1
select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;
Well, the code that renders the button enabled/disabled:
if(name.getText().equals("")) {
loginbt.setEnabled(false);
}else {
loginbt.setEnabled(true);
}
must be written in javax.swing.event.ChangeListener
and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?
View the Inner Exception of the exception to get a more specific error message.
One way to view the Inner Exception would be to catch the exception, and put a breakpoint on it. Then in the Locals window: select the Exception variable > InnerException > Message
And/Or just write to console:
catch (Exception e)
{
Console.WriteLine(e.InnerException.Message);
}