2**2 means 2 squared (2^2)
2*2 mean 2 times 2 (2x2)
In this case they happen to have the same value, but...
3**3*4 != 3*3*4
I got this exception too. MY error code is below
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("Content-type", "JSON");
I found "Content-type" should not be "JSON",is wrong! I solved this exception by update this line to below
connection.setRequestProperty("Content-type", "application/json");
you can check up your "Content-type"
After activating the virtual environment and installing Flask, I created an app.py file. I run it like this : python -m flask run
. Hope this will help!
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
If you don't want to touch stdin and simulate as if you had passed "python cmdfile.py", you can do the following from a bash shell:
$ python <(printf "word=raw_input('Enter word: ')\nimport sys\nfor i in range(5):\n print(word)")
As you can see, it allows you to use stdin for reading input data. Internally the shell creates the temporary file for the input command contents.
I had similar issue recently. Regional settings were properly setup both in app and database server. However, execution of SQL resulted in
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value".
The problem was the default language of the db user.
To check or change it in SSMS go to Security -> Logins and right-click the username of the user that runs the queries. Select properties -> general and make sure the default language at the bottom of the dialog is what you expect.
Repeat this for all users that run queries.
Use the double-star (aka double-splat?) operator:
func(**{'type':'Event'})
is equivalent to
func(type='Event')
I have uninstalled jupyter, notebook and ipython, and installed jupyterlab. It is working for now (with just a few libraries installed and Python 3.6.8.
Something to discard: Uninstalling Python 3.7 completely with his libraries and reverting to 3.6 doesn't fix it, although it improves it, it works intermittently now (but once sth doesn't work properly, things start to get worse and worse, so I did the above).
As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");
The man page for checkout: http://git-scm.com/docs/git-checkout
The man page for clone: http://git-scm.com/docs/git-clone
To sum it up, clone is for fetching repositories you don't have, checkout is for switching between branches in a repository you already have.
Note: for those who have a SVN/CVS background and new to Git, the equivalent of git clone
in SVN/CVS is checkout
. The same wording of different terms is often confusing.
In my case I wasn't sure what had caused this to happen, but I knew I just wanted the submodules to be reset to their latest remote commit and be done with it. This involved combining answers from a couple of different questions on here:
git submodule update --recursive --remote --init
Sources:
You can use textract module in python
Textract
for install
pip install textract
for read pdf
import textract
text = textract.process('path/to/pdf/file', method='pdfminer')
For detail Textract
For vue 3, there is https://github.com/SortableJS/vue.draggable.next
For vue 2, it's https://github.com/SortableJS/Vue.Draggable
The latter you can use like this:
<draggable v-model="myArray" group="people" @start="drag=true" @end="drag=false">
<div v-for="element in myArray" :key="element.id">{{element.name}}</div>
</draggable>
These are based on sortable.js
One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.
I am just going to show as a static example which you can accommodate in your real world.
On each of your <tr>
's add a data attribute for id
(i.e. data-id
) with the corresponding id value and specify a data-target
, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal
to make this a trigger for modal.
<tr data-toggle="modal" data-id="1" data-target="#orderModal">
<td>1</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="2" data-target="#orderModal">
<td>2</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="3" data-target="#orderModal">
<td>3</td>
<td>24234234</td>
<td>A</td>
</tr>
And now in the javascript just set up the modal just once and event listen to its events so you can do your work.
$(function(){
$('#orderModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show', function(){ //subscribe to show method
var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
//make your ajax call populate items or what even you need
$(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow + '</b>'))
});
});
Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.
Alternative ways here:
This is because gcc
calls many other executables to complete the processing of the input, and cc1
is not in the included path.
On shell type whereis cc1
. If cc1
is found, it's better go ahead and create a softlink in the directory of gcc
; otherwise, cc1
is not installed and you have to install gcc-c++ using the package manager.
You should use a hashmap for such problems. it will take O(n) time to enter each element into the hashmap and o(1) to retrieve the element. In the given code, I am basically taking a global max and comparing it with the value received on 'get' from the hashmap, each time I am entering an element into it, have a look:
hashmap has two parts, one is the key, the second is the value when you do a get operation on the key, its value is returned.
public static int mode(int []array)
{
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
int max = 1;
int temp = 0;
for(int i = 0; i < array.length; i++) {
if (hm.get(array[i]) != null) {
int count = hm.get(array[i]);
count++;
hm.put(array[i], count);
if(count > max) {
max = count;
temp = array[i];
}
}
else
hm.put(array[i],1);
}
return temp;
}
Also check if you have installed the Mongo as a windows service and if its running. That's also important. There might port conflict because of that.
Another portable POSIX
compliant way to do in bash
, which can be defined as a function in .bashrc
for all the arithmetic operators of convenience.
addNumbers () {
local IFS='+'
printf "%s\n" "$(( $* ))"
}
and just call it in command-line as,
addNumbers 1 2 3 4 5 100
115
The idea is to use the Input-Field-Separator(IFS), a special variable in bash
used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator +
.
Remember the IFS
is changed locally and does NOT take effect on the default IFS
behaviour outside the function scope. An excerpt from the man bash
page,
The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.
The "$(( $* ))"
represents the list of arguments passed to be split by +
and later the sum value is output using the printf
function. The function can be extended to add scope for other arithmetic operations also.
Here are two WORKAROUNDS to the problem of triggering downloads from the client only. In later browsers you should look at "blob"
1. Drag and drop the table
Did you know you can simply DRAG your table into excel?
Here is how to select the table to either cut and past or drag
Select a complete table with Javascript (to be copied to clipboard)
2. create a popup page from your div
Although it will not produce a save dialog, if the resulting popup is saved with extension .csv, it will be treated correctly by Excel.
The string could be
w.document.write("row1.1\trow1.2\trow1.3\nrow2.1\trow2.2\trow2.3");
e.g. tab-delimited with a linefeed for the lines.
There are plugins that will create the string for you - such as http://plugins.jquery.com/project/table2csv
var w = window.open('','csvWindow'); // popup, may be blocked though
// the following line does not actually do anything interesting with the
// parameter given in current browsers, but really should have.
// Maybe in some browser it will. It does not hurt anyway to give the mime type
w.document.open("text/csv");
w.document.write(csvstring); // the csv string from for example a jquery plugin
w.document.close();
DISCLAIMER: These are workarounds, and does not fully answer the question which currently has the answer for most browser: not possible on the client only
In Eclipse:
Window -> Preferences -> Android -> Lint Error Checking.
In the list find an entry with ID = ProtectedPermission
. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.
In Android Studio:
File -> Settings -> Editor -> Inspections
Under Android Lint
, locate Using system app permission
. Either uncheck the checkbox or choose a Severity lower than Error.
You can use jQuery's $.map
.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
For Ubuntu 16.04.5, it is noticed that MongoDB installations does not auto enable the mongod.service file after installation in my case after I have installed on several servers, so we need to enable it like below:
Issue below to check whether mongod is enabled
systemctl list-unit-files --type=service
If it shows as "disabled", then you need to enable it.
sudo systemctl enable mongod.service
If we want to see whether mongod.service file exists in case this file is missing, check in
ls /lib/systemd/system
You will see a file
/lib/systemd/system/mongod.service
You can use tee
to write the result of your query to a file:
tee somepath\filename.txt
BTW, in my case it was that I needed to specify the user/pwd in the url, not as independent properties, they were ignored and my OS user was used to connect
My config is in a WebSphere 8.5.5 server.xml file
<dataSource
jndiName="jdbc/tableauPostgreSQL"
type="javax.sql.ConnectionPoolDataSource">
<jdbcDriver
javax.sql.ConnectionPoolDataSource="org.postgresql.ds.PGConnectionPoolDataSource"
javax.sql.DataSource="org.postgresql.ds.PGPoolingDataSource"
libraryRef="PostgreSqlJdbcLib"/>
<properties
url="jdbc:postgresql://server:port/mydb?user=fred&password=secret"/>
</dataSource>
This would not work and was getting the error:
<properties
user="fred"
password="secret"
url="jdbc:postgresql://server:port/mydb"/>
add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate.
float x = 55; // stored as 54.999999...
x = x + 0.5 - (x<0); // x is now 55.499999...
int y = (int)x; // truncated to 55
C++11 also introduces std::round, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.
A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer.
LocalDate.parse(
"January 08, 2017" ,
DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US )
).format( DateTimeFormatter.BASIC_ISO_DATE )
The Question and other Answers use troublesome old date-time classes, now legacy, supplanted by the java.time classes.
You have date-only values, so use a date-only class. The LocalDate
class represents a date-only value without time-of-day and without time zone.
String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );
Your desired output format is defined by the ISO 8601 standard. For a date-only value, the “expanded” format is YYYY-MM-DD such as 2017-01-08
and the “basic” format that minimizes the use of delimiters is YYYYMMDD such as 20170108
.
I strongly suggest using the expanded format for readability. But if you insist on the basic format, that formatter is predefined as a constant on the DateTimeFormatter
class named BASIC_ISO_DATE
.
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );
See this code run live at IdeOne.com.
ld.toString(): 2017-01-08
output: 20170108
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
javax.servlet.Filter
.doFilter()
method, cast the incoming ServletRequest
to HttpServletRequest
.HttpServletRequest#getRequestURI()
to grab the path.java.lang.String
methods like substring()
, split()
, concat()
and so on to extract the part of interest and compose the new path.ServletRequest#getRequestDispatcher()
and then RequestDispatcher#forward()
to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse
to HttpServletResponse
and then HttpServletResponse#sendRedirect()
to redirect the response to the new URL (client side redirect, reflected in browser address bar).web.xml
on an url-pattern
of /*
or /Check_License/*
, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilter
annotation for that instead.Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter()
, else it will call itself in an infinite loop.
Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite
.
/^[a-z]{0,10}$/
should work. /^[a-z]{1,10}$/
if you want to match at least one character, like /^[a-z]+$/
does.
For those who want a non-zero cellspacing value, the following CSS worked for me, but I'm only able to test it in Firefox.
See the Quirksmode link posted elsewhere for compatibility details. It seems it may not work with older Internet Explorer versions.
table {
border-collapse: separate;
border-spacing: 2px;
}
It's not called a tag; what you're looking for is called an html attribute.
$('div[imageId="imageN"]').each(function(i,el){
$(el).html('changes');
//do what ever you wish to this object :)
});
I experienced this on a div
that had a click event and after 20 some searches I found this snippet that saved my day.
-webkit-tap-highlight-color: rgba(0,0,0,0);
This disables the default button highlighting in webkit mobile browsers
As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items
returns a list, while iteritems
returns a iterator.
In python 3, items
returns a view, which is pretty much the same as an iterator.
If you are using python 2, you may want to user iteritems
if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)
Just override the default max-width
to whatever fits your needs.
.tooltip-inner {
max-width: 350px;
}
When max-width doesn't work (option 1)
If max-width does not work, you could use a set width instead. This is fine, but your tooltips will no longer resize to fit the text. If you don't like that, skip to option 2.
.tooltip-inner {
width: 350px;
}
Correctly dealing with small containers (option 2)
Since Bootstrap appends the tooltip as a sibling of the target, it is constrained by the containing element. If the containing element is smaller than your max-width
, then max-width
won't work.
So, when max-width
doesn't work, you just need to change the container
:
<div class="some-small-element">
<a data-container="body" href="#" title="Your boxed-in tooltip text">
</div>
Pro Tip: the container can be any selector, which is nice when you only want to override styles on a few tooltips.
Another solution I have found to a similar error but the same error message is to increase the number of service handlers found. (My instance of this error was caused by too many connections in the Weblogic Portal Connection pools.)
SQL*Plus
and login as SYSTEM
. You should know what password you’ve used during the installation of Oracle DB XE.alter system set processes=150 scope=spfile;
in SQL*PlusFrom here:
Short answer: You can't.
Long answer:
Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:
public class Foo<T>
{
private Class<T> type;
public Foo(Class<T> type) { this.type = type; }
}
Usage example:
Foo<Integer> test = new Foo<Integer>(Integer.class);
You can try this:
var b = str.match(/[^\x00-\xff]/g);
return (str.length + (!b ? 0: b.length));
It worked for me.
Some of the columns in MySQL have an "on update" clause, see:
mysql> SHOW COLUMNS FROM your_table_name;
I'm not sure how to update this but will post an edit when I find out.
You can use bash. Note for very large files in terms of GB, use awk/wc
. However it should still be manageable in performance for files with a few MB.
declare -i count=0
while read
do
((count++))
done < file
echo "line count: $count"
After playing with scp for a while I have found the most robust solution:
(Beware of the single and double quotation marks)
Local to remote:
scp -r "FILE1" "FILE2" HOST:'"DIR"'
Remote to local:
scp -r HOST:'"FILE1" "FILE2"' "DIR"
Notice that whatever after "HOST:" will be sent to the remote and parsed there. So we must make sure they are not processed by the local shell. That is why single quotation marks come in. The double quotation marks are used to handle spaces in the file names.
If files are all in the same directory, we can use * to match them all, such as
scp -r "DIR_IN"/*.txt HOST:'"DIR"'
scp -r HOST:'"DIR_IN"/*.txt' "DIR"
Compared to using the "{}" syntax which is supported only by some shells, this one is universal
One way you can achieve this is setting display: inline-block;
on the div
. It is by default a block
element, which will always fill the width it can fill (unless specifying width
of course).
inline-block
's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline
elements, but there are hacks to solve this problem.
There are other options you have, you can either float
it, or set position: absolute
on it, but these also have other effects on layout, you need to decide which one fits your situation better.
Array
(
[0] => Array
(
[id] => 1
[name] => john
)
[1] => Array
(
[id] => 2
[name] => smith
)
[2] => Array
(
[id] => 3
[name] => john
)
[3] => Array
(
[id] => 4
[name] => robert
)
)
$temp = array_unique(array_column($array, 'name'));
$unique_arr = array_intersect_key($array, $temp);
This will remove the duplicate names from array. unique by key
<?= $form->field($model, 'hidden_Input')->hiddenInput(['id'=>'hidden_Input','class'=>'form-control','value'=>$token_name])->label(false)?>
or
<input type="hidden" name="test" value="1" />
Use This.
1- Login as default PostgreSQL user (postgres)
sudo -u postgres -i
2- As postgres user. Add a new database user using the createuser
command
[postgres]$ createuser --interactive
3-exit
[postgres]$ exit
Problem 2 is OK, because " System.out.println(set);" means "System.out.println(set.toString());" set is an instance of List, so complier will call List.toString();
public static void test(List<?> set){
set.add(new Long(2)); //--> Error
set.add("2"); //--> Error
System.out.println(set);
}
Element ? will not promise Long and String, so complier will not accept Long and String Object
public static void test(List<String> set){
set.add(new Long(2)); //--> Error
set.add("2"); //--> Work
System.out.println(set);
}
Element String promise it a String, so complier will accept String Object
Problem 3: these symbols are same, but you can give them differet specification. For example:
public <T extends Integer,E extends String> void p(T t, E e) {}
Problem 4: Collection does not allow type parameter covariance. But array does allow covariance.
Lot of the information above led me to further research and ultimately my answer so I wanted to contribute what I wound up doing in hopes it helps someone else:
I also wanted to pass a varied number of variables to a batch file so that they could be processed within the file.
I was ok with passing them to the batch file using quotes
I would want them processed similar to the below - but using a loop instead of writing out manually:
So I wanted to execute this:
prog_ZipDeleteFiles.bat "_appPath=C:\Services\Logs\PCAP" "_appFile=PCAP*.?"
And via the magic of for loops do this within the batch file:
set "_appPath=C:\Services\Logs\PCAP"
set "_appFile=PCAP*.?"
Problem I was having is that all my attempts to use a for loop weren't working. The below example:
for /f "tokens* delims= " in %%A (%*) DO (
set %%A
)
would just do:
set "_appPath=C:\Services\Logs\PCAP"
and not:
set "_appPath=C:\Services\Logs\PCAP"
set "_appFile=PCAP*.?"
even after setting
SETLOCAL EnableDelayedExpansion
Reason was that the for loop read the whole line and assigned my second parameter to %%B during the first iteration of the loop. Because %* represents all arguments, there is only a single line to process - ergo only one pass of the for loop happens. This is by design it turns out, and my logic was wrong.
So I stopped trying to use a for loop and simplified what I was trying to do by using if, shift, and a goto statement. Agreed its a bit of a hack but it's more suited to my needs. I can loop through all of the arguments and then use an if statement to drop out of the loop once I process them all.
The winning statement for what I was trying to accomplish:
echo on
:processArguments
:: Process all arguments in the order received
if defined %1 then (
set %1
shift
goto:processArguments
) ELSE (
echo off
)
UPDATE - I had to modify to the below instead, I was exposing all of the environment variables when trying to reference %1 and using shift in this manner:
echo on
shift
:processArguments
:: Process all arguments in the order received
if defined %0 then (
set %0
shift
goto:processArguments
) ELSE (
echo off
)
>ssh user@serverip -p portnumber
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys
Posting my answer to help someone, the top rated answer didn't solve my qualm.
When I implemented the following [from the top answer], my vertical scroll animation just jittered back and forth:
$(function () {
$("#first").animate({
width: '200px'
}, { duration: 200, queue: false });
$("#second").animate({
width: '600px'
}, { duration: 200, queue: false });
});
I referred to: W3 Schools Set Interval and it solved my issue, namely the 'Syntax' section:
setInterval(function, milliseconds, param1, param2, ...)
Having my parameters of the form { duration: 200, queue: false }
forced a duration of zero and it only looked at the parameters for guidance.
The long and short, here's my code, if you want to understand why it works, read the link or analyse the interval expected parameters:
var $scrollDiv = '#mytestdiv';
var $scrollSpeed = 1000;
var $interval = 800;
function configureRepeats() {
window.setInterval(function () {
autoScroll($scrollDiv, $scrollSpeed);
}, $interval, { queue: false });
};
Where 'autoScroll' is:
$($scrollDiv).animate({
scrollTop: $($scrollDiv).get(0).scrollHeight
}, { duration: $scrollSpeed });
//Scroll to top immediately
$($scrollDiv).animate({
scrollTop: 0
}, 0);
Happy coding!
You can remove any package by typing following command in terminal, and just remove the providers and alias you provided at the time of installing the package and update the composer
composer remove <package_name>
composer update
Unfortunately, it doesn't look like file_get_contents()
really offers that degree of control. The cURL extension is usually the first to come up, but I would highly recommend the PECL_HTTP extension (http://pecl.php.net/package/pecl_http) for very simple and straightforward HTTP requests. (it's much easier to work with than cURL)
See example here: Input and Output binary streams using JERSEY?
Pseudo code would be something like this (there are a few other similar options in above mentioned post):
@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
//
// 1. Get Stream to file from first server
//
while(<read stream from first server>) {
output.write(<bytes read from first server>)
}
} catch (Exception e) {
throw new WebApplicationException(e);
} finally {
// close input stream
}
}
}
You can put the condition after the WHEN
clause, like so:
SELECT
CASE
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
WHEN DS.DES = 'N' THEN 'Early Term'
WHEN DS.DES = 'Y' THEN 'Complete'
END
FROM
....
Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...
I ran into the same problem, but I found a simple way to fix it.
It appears to be spawn()
errors if the program has been added to the PATH by the user (e.g. normal system commands work).
To fix this, you can use the which module (npm install --save which
):
// Require which and child_process
const which = require('which');
const spawn = require('child_process').spawn;
// Find npm in PATH
const npm = which.sync('npm');
// Execute
const noErrorSpawn = spawn(npm, ['install']);
There are many ways to do this, one is reject
noEmptyCities = cities.reject { |c| c.empty? }
You can also use reject!
, which will modify cities
in place. It will either return cities
as its return value if it rejected something, or nil
if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).
You could use TimeZoneInfo class
The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:
Retrieving a time zone that is already defined by the operating system.
Enumerating the time zones that are available on a system.
Converting times between different time zones.
Creating a new time zone that is not already defined by the operating system.
Serializing a time zone for later retrieval.
If you're using .NET 4.5.1 or higher checkout Dapper.FluentColumnMapping for mapping the LINQ style. It lets you fully separate the db mapping from your model (no need for annotations)
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');_x000D_
_x000D_
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {_x000D_
if (err) throw new Error(err);_x000D_
console.log(res);_x000D_
});
_x000D_
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:
make sure you have correclty set the keys
modelBuilder.Entity<Foo>()
.HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
OR you can achieve it using data annotation as well
public class Foo
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key, Column(Order = 0)]
public int Id { get; set; }
[Key, Column(Order = 1)]
public string Name{ get; set; }
}
If the data is populated from the database, you might consider not using an <input>
tag to display it. Nevertheless, you can disable it right in the tag:
<input type='text' value='${magic.database.value}' disabled>
If you need to disable it with Javascript later, you can set the "disabled" attribute:
document.getElementById('theInput').disabled = true;
The reason I suggest not showing the value as an <input>
is that, in my experience, it causes layout issues. If the text is long, then in an <input>
the user will need to try and scroll the text, which is not something normal people would guess to do. If you just drop it into a <span>
or something, you have more styling flexibility.
$ svn copy http://svn.example.com/repos/calc/trunk@192 \
http://svn.example.com/repos/calc/branches/my-calc-branch \
-m "Creating a private branch of /calc/trunk."
Where 192 is the revision you specify
You can find this information from the SVN Book, specifically here on the page about svn copy
You can modify a sheet via code by taking these actions
In code this would be:
Sub UnProtect_Modify_Protect()
ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password"
'Unprotect
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password"
'Protect
End Sub
The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.
The code could be improved by taking these actions
The code to do this would be:
Sub Re-Protect_Modify()
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
UserInterfaceOnly:=True
'Protect, even if already protected
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
End Sub
This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.
This setting is lost when the workbook is closed and re-opened. The worksheet protection is still maintained.
So the 'Re-protection' code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
I think for is marginally faster than foreach in most cases, but this is really missing the point. One thing I haven't seen mentioned is that, in the scenario you're talking about (i.e., a high volume web app), the difference in performance between for and foreach is going to have no bearing on the site's performance. You're going to be limited by request/response time and DB time, not for v. foreach.
That said, I don't understand your aversion to foreach. In my opinion, foreach is usually clearer in situation where either could be used. I usually reserve for for situations where I need to traverse a collection in some ugly, non-standard way.
I find this method saves a lot of typing, and prevents a lot of typos.
string nl = "\r\n";
txtOutput.Text = "First line" + nl + "Second line" + nl + "Third line";
Here is an updated version of Fattie's very helpful answer. It adds 2 important lines that helped me get the layout working on iOS 10 and 11 (and probably on lower ones, too):
@IBDesignable class UITextViewFixed: UITextView {
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
func setup() {
translatesAutoresizingMaskIntoConstraints = true
textContainerInset = UIEdgeInsets.zero
textContainer.lineFragmentPadding = 0
translatesAutoresizingMaskIntoConstraints = false
}
}
The important lines are the two translatesAutoresizingMaskIntoConstraints = <true/false>
statements!
This surprisingly removes all margins in all my circumstances!
While the textView
is not the first responder it could happen that there is some strange bottom margin that could not be solved using the sizeThatFits
method that is mentioned in the accepted answer.
When tapping into the textView suddenly the strange bottom margin disappeared and everything looked like it should, but only as soon as the textView has got firstResponder
.
So I read here on SO that enabling and disabling translatesAutoresizingMaskIntoConstraints
does help when setting the frame/bounds manually in between the calls.
Fortunately this not only works with frame setting but with the 2 lines of setup()
sandwiched between the two translatesAutoresizingMaskIntoConstraints
calls!
This for example is very helpful when calculating the frame of a view using systemLayoutSizeFitting
on a UIView
. Gives back the correct size (which previously it didn't)!
As in the original answer mentioned:
Don't forget to turn off scrollEnabled in the Inspector!
That solution does work properly in storyboard, as well as at runtime.
That's it, now you're really done!
Since API 21 there is an option set letter spacing. You can call method setLetterSpacing or set it in XML with attribute letterSpacing.
You should not rely on a hash code being equal to a specific value. Just that it will return consistent results within the same execution. The API docs say the following :
The general contract of hashCode is:
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
EDIT Since the javadoc for String.hashCode() specifies how a String's hash code is computed, any violation of this would violate the public API specification.
Best solution
open XAMPP control panel,click on config for Apache, then click on Apache(httpd.config).now in the text editor . ctrl+f --> find "Listen 80" and replace it with "Listen 8079" wtihout the quotations :) but now you have to use it like this http://localhost:8079/
P.S, I tried to change port settings for skype , stopping the Web Deployment Agent Service which I could not find in windows 10,cmd--> net stop http, and other methods but nothing worked except this .
Did you restart the server after you changed the config file?
Can you telnet to the server from a different machine?
Can you telnet to the server from the server itself?
telnet <ip address> 80
telnet localhost 80
Simple regex for any number of digits at the end of a string:
'xxx_456'.match(/\d+$/)[0]; //456
'xxx_4567890'.match(/\d+$/)[0]; //4567890
or use split/pop indeed:
('yyy_xxx_45678901').split(/_/).pop(); //45678901
REST is an architecture, SOAP is a protocol.
That's the first problem.
You can send SOAP envelopes in a REST application.
SOAP itself is actually pretty basic and simple, it's the WSS-* standards on top of it that make it very complex.
If your consumers are other applications and other servers, there's a lot of support for the SOAP protocol today, and the basics of moving data is essentially a mouse-click in modern IDEs.
If your consumers are more likely to be RIAs or Ajax clients, you will probably want something simpler than SOAP, and more native to the client (notably JSON).
JSON packets sent over HTTP is not necessarily a REST architecture, it's just messages to URLs. All perfectly workable, but there are key components to the REST idiom. It is easy to confuse the two however. But just because you're talking HTTP requests does not necessarily mean you have a REST architecture. You can have a REST application with no HTTP at all (mind, this is rare).
So, if you have servers and consumers that are "comfortable" with SOAP, SOAP and WSS stack can serve you well. If you're doing more ad hoc things and want to better interface with web browsers, then some lighter protocol over HTTP can work well also.
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) {
return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);
// assuming the current url is `/team/33/user/11` and the route points to `user/11`
// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});
// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});
// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts:
constructor(private route: ActivatedRoute, private router: Router) {}
// Example call
onNavigateClick() {
// Navigates to a parent component
this.router.navigate([..], { relativeTo: this.route })
}
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"
// if the string parameter is passed it will be wrapped into an array
routerLink="../.."
I modified my response to include the code for a test app I did.
Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).
First the javascript:
function test()
{
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };
$.ajax({
type: "POST",
url: "/Home/SaveList",
data: postData,
success: function(data){
alert(data.Result);
},
dataType: "json",
traditional: true
});
}
And here's the code in my controller class:
public JsonResult SaveList(List<String> values)
{
return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}
When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!
protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
{
GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = " ";
gvRow.Cells.Add(tCell);
Table tbl = e.Row.Parent as Table;
tbl.Rows.Add(gvRow);
}
}
}
An alternative for multiline texts or links, you can wrap your texts in a span inside a block element.
<a href="#">
<span>insert multiline texts here</span>
</a>
then you can just add border-bottom and padding on the <span>
.
a {
width: 300px;
display: block;
}
span {
padding-bottom: 10px;
border-bottom: 1px solid #0099d3;
line-height: 48px;
}
You may refer to this fiddle. https://jsfiddle.net/Aishaterr/vrpb2ey7/2/
This is for using a single directory for multiple projects. I use this technique for some closely related projects where I often need to pull changes from one project into another. It's similar to the orphaned branches idea but the branches don't need to be orphaned. Simply start all the projects from the same empty directory state.
Don't expect wonders from this solution. As I see it, you are always going to have annoyances with untracked files. Git doesn't really have a clue what to do with them and so if there are intermediate files generated by a compiler and ignored by your .gitignore file, it is likely that they will be left hanging some of the time if you try rapidly swapping between - for example - your software project and a PH.D thesis project.
However here is the plan. Start as you ought to start any git projects, by committing the empty repository, and then start all your projects from the same empty directory state. That way you are certain that the two lots of files are fairly independent. Also, give your branches a proper name and don't lazily just use "master". Your projects need to be separate so give them appropriate names.
Git commits (and hence tags and branches) basically store the state of a directory and its subdirectories and Git has no idea whether these are parts of the same or different projects so really there is no problem for git storing different projects in the same repository. The problem is then for you clearing up the untracked files from one project when using another, or separating the projects later.
cd some_empty_directory
git init
touch .gitignore
git add .gitignore
git commit -m empty
git tag EMPTY
Start your projects from empty.
git branch software EMPTY
git checkout software
echo "array board[8,8] of piece" > chess.prog
git add chess.prog
git commit -m "chess program"
whenever you like.
git branch thesis EMPTY
git checkout thesis
echo "the meaning of meaning" > philosophy_doctorate.txt
git add philosophy_doctorate.txt
git commit -m "Ph.D"
Go back and forwards between projects whenever you like. This example goes back to the chess software project.
git checkout software
echo "while not end_of_game do make_move()" >> chess.prog
git add chess.prog
git commit -m "improved chess program"
You will however be annoyed by untracked files when swapping between projects/branches.
touch untracked_software_file.prog
git checkout thesis
ls
philosophy_doctorate.txt untracked_software_file.prog
Sort of by definition, git doesn't really know what to do with untracked files and it's up to you to deal with them. You can stop untracked files from being carried around from one branch to another as follows.
git checkout EMPTY
ls
untracked_software_file.prog
rm -r *
(directory is now really empty, apart from the repository stuff!)
git checkout thesis
ls
philosophy_doctorate.txt
By ensuring that the directory was empty before checking out our new project we made sure there were no hanging untracked files from another project.
$ GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01T01:01:01' git commit -m empty
If the same dates are specified whenever committing an empty repository, then independently created empty repository commits can have the same SHA1 code. This allows two repositories to be created independently and then merged together into a single tree with a common root in one repository later.
# Create thesis repository.
# Merge existing chess repository branch into it
mkdir single_repo_for_thesis_and_chess
cd single_repo_for_thesis_and_chess
git init
touch .gitignore
git add .gitignore
GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01:T01:01:01' git commit -m empty
git tag EMPTY
echo "the meaning of meaning" > thesis.txt
git add thesis.txt
git commit -m "Wrote my PH.D"
git branch -m master thesis
# It's as simple as this ...
git remote add chess ../chessrepository/.git
git fetch chess chess:chess
It may also help if you keep your projects in subdirectories where possible, e.g. instead of having files
chess.prog
philosophy_doctorate.txt
have
chess/chess.prog
thesis/philosophy_doctorate.txt
In this case your untracked software file will be chess/untracked_software_file.prog
. When working in the thesis
directory you should not be disturbed by untracked chess program files, and you may find occasions when you can work happily without deleting untracked files from other projects.
Also, if you want to remove untracked files from other projects, it will be quicker (and less prone to error) to dump an unwanted directory than to remove unwanted files by selecting each of them.
So you might want to name your branches something like
project1/master
project1/featureABC
project2/master
project2/featureXYZ
I am running VS 2012, and SQL Server 2008 R2 SP2, Developer Edition. I ended up having to install items from the Microsoft® SQL Server® 2012 Feature Pack. I think that the install instructions noted that these items work for SQL Server 2005 through 2012. I don't know what the exact requirements are to fix this error, but I installed the three items, and the error stopped appearing.
Microsoft® SQL Server® 2012 Feature Pack Items
Based on threads elsewhere, you may not end up needing the last item or two. Good luck!
In Haskell...
To get it back as a POSIXTime type:
import Data.Time.Clock.POSIX
getPOSIXTime
As an integer:
import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime
Update your constraint layout dependency to the relevant version from '1.0.0-alpha2'. In my case, I changed to the following. compile 'com.android.support.constraint:constraint-layout:2.0.0-alpha5'
This is assuming a list of YourClass
instead of Object
, as explained by amit.
You can use this bit from the Google Guava library:
Collections.sort(list, Ordering.natural()
.onResultOf(new Function<String,YourClass>() {
public String call(YourClass o) {
return o.getName();
}))
.nullsLast();
The other answers which mention Comparator
are not incorrect, since Ordering
implements Comparator
. This solution is, in my opinion, a little easier, though it may be harder if you're a beginner and not used to using libraries and/or "functional programming".
Copied shamelessly from this answer on my own question.
Check this has everything you need
http://www.html5rocks.com/en/mobile/fullscreen/
The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.
<meta name="mobile-web-app-capable" content="yes">
It's possible to redirect to another view with angular-ui-router. For this purpose, we have the method $state.go("target_view")
. For example:
---- app.js -----
var app = angular.module('myApp', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
// Otherwise
$urlRouterProvider.otherwise("/");
$stateProvider
// Index will decide if redirects to Login or Dashboard view
.state("index", {
url: ""
controller: 'index_controller'
})
.state('dashboard', {
url: "/dashboard",
controller: 'dashboard_controller',
templateUrl: "views/dashboard.html"
})
.state('login', {
url: "/login",
controller: 'login_controller',
templateUrl: "views/login.html"
});
});
// Associate the $state variable with $rootScope in order to use it with any controller
app.run(function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
});
app.controller('index_controller', function ($scope, $log) {
/* Check if the user is logged prior to use the next code */
if (!isLoggedUser) {
$log.log("user not logged, redirecting to Login view");
// Redirect to Login view
$scope.$state.go("login");
} else {
// Redirect to dashboard view
$scope.$state.go("dashboard");
}
});
----- HTML -----
<!DOCTYPE html>
<html>
<head>
<title>My WebSite</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="MyContent">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/libs/angular.min.js" type="text/javascript"></script>
<script src="js/libs/angular-ui-router.min.js" type="text/javascript"></script>
<script src="js/app.js" type="text/javascript"></script>
</head>
<body ng-app="myApp">
<div ui-view></div>
</body>
</html>
When you are building a new image you often want to run a new container each time and with the same name. I found the easiest way was to start the container with the --rm option:
--rm Automatically remove the container when it exits
e.g.
docker run --name my-micro-service --rm <image>
Sadly it's used almost randomly in the examples from the docs
Below code work for me in web.xml file
<servlet>
<servlet-name>WebService</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.example.demo.webservice</param-value>
//Package
</init-param>
<init-param>
<param-name>unit:WidgetPU</param-name>
<param-value>persistence/widget</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WebService</servlet-name>
<url-pattern>/webservices/*</url-pattern>
</servlet-mapping>
another way, not using regex, is to use fields/delimiter method eg
string="http://www.suepearson.co.uk/product/174/71/3816/"
echo $string | awk -F"/" '{print $1,$2,$3}' OFS="/"
I have been working on to write a custom module in Drupal 7 and got the same error:
Notice: Trying to get property of non-object
My code is something like this:
function example_node_access($node, $op, $account) {
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes to it.','error');
return NODE_ACCESS_DENY;
}
}
Solution:
I just added a condition if (is_object($sqlResult))
, and everything went fine.
Here is my final code:
function mediaten_node_access($node, $op, $account) {
if (is_object($node)){
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes.','error');
return NODE_ACCESS_DENY;
}
}
}
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
Inspired by @mtrw's answer, but improved to strip out punctuation at word boundaries only:
import re
import string
def extract_words(s):
return [re.sub('^[{0}]+|[{0}]+$'.format(string.punctuation), '', w) for w in s.split()]
>>> str = 'This is a string, with words!'
>>> extract_words(str)
['This', 'is', 'a', 'string', 'with', 'words']
>>> str = '''I'm a custom-built sentence with "tricky" words like https://stackoverflow.com/.'''
>>> extract_words(str)
["I'm", 'a', 'custom-built', 'sentence', 'with', 'tricky', 'words', 'like', 'https://stackoverflow.com']
Additionally, if your application uses SQL SERVER you can use the SQL Agent to schedule your tasks. This is where we commonly put re-occurring code that is data driven (email reminders, scheduled maintenance, purges, etc...). A great feature that is built in with the SQL Agent is failure notification options, which can alert you if a critical task fails.
In WinForm, we can always get the Control Key status by:
bool IsCtrlPressed = (Control.ModifierKeys & Keys.Control) != 0;
Use this.
<script>
function openFileOption()
{
document.getElementById("file1").click();
}
</script>
<input type="file" id="file1" style="display:none">
<a href="#" onclick="openFileOption();return;">open File Dialog</a>
With SemaphoreSlim
you can achieve parallelism control.
var bag = new ConcurrentBag<object>();
var maxParallel = 20;
var throttler = new SemaphoreSlim(initialCount: maxParallel);
var tasks = myCollection.Select(async item =>
{
try
{
await throttler.WaitAsync();
var response = await GetData(item);
bag.Add(response);
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks);
var count = bag.Count;
A lot of good responses here; I especially like the lambda expressions...very clean. I was remiss, however, in not specifying the type of Collection. This is a SPRoleAssignmentCollection (from MOSS) that only has Remove(int) and Remove(SPPrincipal), not the handy RemoveAll(). So, I have settled on this, unless there is a better suggestion.
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
if (spAssignment.Member.Name != shortName) continue;
workspace.RoleAssignments.Remove((SPPrincipal)spAssignment.Member);
break;
}
data.reshape((50,1104,-1))
works for me
Python Implementation for @dhanushka's solution:
def process_rgb(rgb):
hasText = False
gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
morphKernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
grad = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, morphKernel)
# binarize
_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# connect horizontally oriented regions
morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, morphKernel)
# find contours
mask = np.zeros(bw.shape[:2], dtype="uint8")
_,contours, hierarchy = cv2.findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# filter contours
idx = 0
while idx >= 0:
x,y,w,h = cv2.boundingRect(contours[idx])
# fill the contour
cv2.drawContours(mask, contours, idx, (255, 255, 255), cv2.FILLED)
# ratio of non-zero pixels in the filled region
r = cv2.contourArea(contours[idx])/(w*h)
if(r > 0.45 and h > 5 and w > 5 and w > h):
cv2.rectangle(rgb, (x,y), (x+w,y+h), (0, 255, 0), 2)
hasText = True
idx = hierarchy[0][idx][0]
return hasText, rgb
For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.
Basically this works:
<connectionStrings>
<add name="MyConnectionString"
connectionString="data source=ServerName;
Initial Catalog=DatabaseName;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.
It is also working different according which provider you are using.
SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.
OleDb it is Integrated Security=SSPI;
Integrated Security=true throws an exception when used with the OleDb provider.
You can remove the warning by adding a '@' before the mysql_connect.
@mysql_connect('localhost','root','');
but as the warning is telling you, use mysqli or PDO since the mysql extension will be removed in the future.
You can use Collections.sort
and pass your own Comparator<ActiveAlarm>
Here is a generic solution that assigns dense rank over partition to rows. It uses user variables:
CREATE TABLE person (
id INT NOT NULL PRIMARY KEY,
firstname VARCHAR(10),
gender VARCHAR(1),
age INT
);
INSERT INTO person (id, firstname, gender, age) VALUES
(1, 'Adams', 'M', 33),
(2, 'Matt', 'M', 31),
(3, 'Grace', 'F', 25),
(4, 'Harry', 'M', 20),
(5, 'Scott', 'M', 30),
(6, 'Sarah', 'F', 30),
(7, 'Tony', 'M', 30),
(8, 'Lucy', 'F', 27),
(9, 'Zoe', 'F', 30),
(10, 'Megan', 'F', 26),
(11, 'Emily', 'F', 20),
(12, 'Peter', 'M', 20),
(13, 'John', 'M', 21),
(14, 'Kate', 'F', 35),
(15, 'James', 'M', 32),
(16, 'Cole', 'M', 25),
(17, 'Dennis', 'M', 27),
(18, 'Smith', 'M', 35),
(19, 'Zack', 'M', 35),
(20, 'Jill', 'F', 25);
SELECT person.*, @rank := CASE
WHEN @partval = gender AND @rankval = age THEN @rank
WHEN @partval = gender AND (@rankval := age) IS NOT NULL THEN @rank + 1
WHEN (@partval := gender) IS NOT NULL AND (@rankval := age) IS NOT NULL THEN 1
END AS rnk
FROM person, (SELECT @rank := NULL, @partval := NULL, @rankval := NULL) AS x
ORDER BY gender, age;
Notice that the variable assignments are placed inside the CASE
expression. This (in theory) takes care of order of evaluation issue. The IS NOT NULL
is added to handle datatype conversion and short circuiting issues.
PS: It can easily be converted to row number over partition by by removing all conditions that check for tie.
| id | firstname | gender | age | rank |
|----|-----------|--------|-----|------|
| 11 | Emily | F | 20 | 1 |
| 20 | Jill | F | 25 | 2 |
| 3 | Grace | F | 25 | 2 |
| 10 | Megan | F | 26 | 3 |
| 8 | Lucy | F | 27 | 4 |
| 6 | Sarah | F | 30 | 5 |
| 9 | Zoe | F | 30 | 5 |
| 14 | Kate | F | 35 | 6 |
| 4 | Harry | M | 20 | 1 |
| 12 | Peter | M | 20 | 1 |
| 13 | John | M | 21 | 2 |
| 16 | Cole | M | 25 | 3 |
| 17 | Dennis | M | 27 | 4 |
| 7 | Tony | M | 30 | 5 |
| 5 | Scott | M | 30 | 5 |
| 2 | Matt | M | 31 | 6 |
| 15 | James | M | 32 | 7 |
| 1 | Adams | M | 33 | 8 |
| 18 | Smith | M | 35 | 9 |
| 19 | Zack | M | 35 | 9 |
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
I liked @rich.kelly's answer, but I wanted to use the same nomenclature as classList.add()
(comma seperated strings), so a slight deviation.
DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function() {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function() {
for (var i = 0; i < arguments.length; i++) {
this.remove(arguments[i]);
}
}
So you can then use:
document.body.classList.addMany('class-one','class-two','class-three');
I need to test all browsers, but this worked for Chrome.
Should we be checking for something more specific than the existence of DOMTokenList.prototype.addMany
? What exactly causes classList.add()
to fail in IE11?
Just insert the argument between a double square bracket:
regressor.predict([[values]])
that worked for me
After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.
The important parts for me was:
This is the solution i came up with. And hope it can be of use to others as well.
Change the width of .file_input_textbox to change the width of the textbox.
Change the width of both .file_input_div, .file_input_button and .file_input_button_hover to change the width of the button. You might need to tweak a bit on the positions also. I never figured out why...
To test this solution, make a new html file and paste the content into it.
<html>
<head>
<style type="text/css">
.file_input_textbox {height:25px;width:200px;float:left; }
.file_input_div {position: relative;width:80px;height:26px;overflow: hidden; }
.file_input_button {width: 80px;position:absolute;top:0px;
border:1px solid #F0F0EE;padding:2px 8px 2px 8px; font-weight:bold; height:25px; margin:0px; margin-right:5px; }
.file_input_button_hover{width:80px;position:absolute;top:0px;
border:1px solid #0A246A; background-color:#B2BBD0;padding:2px 8px 2px 8px; height:25px; margin:0px; font-weight:bold; margin-right:5px; }
.file_input_hidden {font-size:45px;position:absolute;right:0px;top:0px;cursor:pointer;
opacity:0;filter:alpha(opacity=0);-ms-filter:"alpha(opacity=0)";-khtml-opacity:0;-moz-opacity:0; }
</style>
</head>
<body>
<input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
<div class="file_input_div">
<input id="fileInputButton" type="button" value="Browse" class="file_input_button" />
<input type="file" class="file_input_hidden"
onchange="javascript: document.getElementById('fileName').value = this.value"
onmouseover="document.getElementById('fileInputButton').className='file_input_button_hover';"
onmouseout="document.getElementById('fileInputButton').className='file_input_button';" />
</div>
</body>
</html>
as of august 2020 (works for kali linux as well)
sh -c "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/install/master/install.sh)"
export brew=/home/linuxbrew/.linuxbrew/bin
test -d ~/.linuxbrew && eval $(~/.linuxbrew/bin/brew shellenv)
test -d /home/linuxbrew/.linuxbrew && eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)
test -r ~/.profile && echo "eval \$($(brew --prefix)/bin/brew shellenv)" >>~/.profile // for ubuntu and debian
Make sure that novalidate attribute is not set to your form tag
urllib
is a standard python library (built-in) so you don't have to install it. just import it if you need to use request
by:
import urllib.request
if it's not work maybe you compiled python in wrong way, so be kind and give us more details.
CSS cannot disable the textbox, you can however turn off display or visibility.
display: none;
visibility: hidden;
Or you can also set the HTMLattribute:
disabled="disabled"
There are multiple ways to do it. However, the quickest way I know is to use the Express.js library with body-parser.
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended : true}));
app.post("/pathpostdataissentto", function(request, response) {
console.log(request.body);
//Or
console.log(request.body.fieldName);
});
app.listen(8080);
That can work for strings, but I would change bodyParser.urlencoded to bodyParser.json instead if the POST data contains a JSON array.
More info: http://www.kompulsa.com/how-to-accept-and-parse-post-requests-in-node-js/
You can achieve this with Collections framework. Put all your options in a Collection say something like Collection<String> options
;
Then loop throgh this to compare your string with the list elements and if it is you can return a boolean value true and otherwise false.
Tom - I made a schoolboy error initially as I didn't watch the byte size and instead I copied and pasted from the "CMG" set up to the subsequent entry. This was two different text sizes between the two files, though, and I lost the VBA project just as Stewbob warned.
Using HxD, there is a counter tracking how much file you're selecting. Copy starting from CMG until the counter reads 8F (hex for 143) and likewise when pasting into the locked file - I ended up with twice the number of "..." at the end of the paste, which looked odd somehow and felt almost unnatural, but it worked.
I don't know if it is crucial, but I made sure I shut both the hex editor and excel down before reopening the file in Excel. I then had to go through the menus to open the VB Editor, into VBProject Properties and entered in the 'new' password to unlock the code.
I hope this helps.
If you're interested in how an open source project does stuff like this, you can check out the Terracotta class (Os.java) that handles this junk here:
And you can see a similar class to handle JVM versions (Vm.java and VmVersion.java) here:
Another way is to setup an alias in Config Manager. Then simply type that alias name when you want to connect. This makes it much easier and is more prefereable when you have to manage several servers/instances and/or servers on multiple ports and/or multiple protocols. Give them friendly names and it becomes much easier to remember them.
Same info, just in table form
| r r+ w w+ a a+
------------------|--------------------------
read | + + + +
write | + + + + +
write after seek | + + +
create | + + + +
truncate | + +
position at start | + + + +
position at end | + +
where meanings are: (just to avoid any misinterpretation)
write - writing to file is allowed
create - file is created if it does not exist yet
trunctate - during opening of the file it is made empty (all content of the file is erased)
position at start - after file is opened, initial position is set to the start of the file
Note: a
and a+
always append to the end of file - ignores any seek
movements.
BTW. interesting behavior at least on my win7 / python2.7, for new file opened in a+
mode:
write('aa'); seek(0, 0); read(1); write('b')
- second write
is ignored
write('aa'); seek(0, 0); read(2); write('b')
- second write
raises IOError
With Angular 5 the RxJS import is improved.
Instead of
import 'rxjs/add/operator/map';
We can now
import { map } from 'rxjs/operators';
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
The easiest way to serve static files is to use "harp". It can be found here. You can serve up your files from the location you want via node is:
var harp = require("harp")
harp.server(projectPath [,args] [,callback])
Hope this helps.
Using the otherwise pointless ? : operator to initialise a const variable
const int bytesPerPixel = isAlpha() ? 4 : 3;
sudo apt-get install php-mbstring
# if your are using php 7.1
sudo apt-get install php7.1-mbstring
# if your are using php 7.2
sudo apt-get install php7.2-mbstring
The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
Output:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
It also supports adding to an already-made node, e.g. after the above you could say
the_doc.append(FIELD2('another value again', name='hithere'))
The problem is that you forgot to import os. Add this line of code:
import os
And everything should be fine. Hope this helps!
First day of next month:
from datetime import datetime
class SomeClassName(models.Model):
if datetime.now().month == 12:
new_start_month = 1
else:
new_start_month = datetime.now().month + 1
Then we replace the month and the day
start_date = models.DateField(default=datetime.today().replace(month=new_start_month, day=1, hour=0, minute=0, second=0, microsecond=0))
Just summarizing an answer that was helpful to me (noting @erasmospunk's comment about using base-64 encoding). My goal was to have a short string that was mostly unique...
I'm no expert, so please correct this if it has any glaring errors (in Python again like the accepted answer):
import base64
import hashlib
import uuid
unique_id = uuid.uuid4()
# unique_id = UUID('8da617a7-0bd6-4cce-ae49-5d31f2a5a35f')
hash = hashlib.sha1(str(unique_id).encode("UTF-8"))
# hash.hexdigest() = '882efb0f24a03938e5898aa6b69df2038a2c3f0e'
result = base64.b64encode(hash.digest())
# result = b'iC77DySgOTjliYqmtp3yA4osPw4='
The result
here is using more than just hex characters (what you'd get if you used hash.hexdigest()
) so it's less likely to have a collision (that is, should be safer to truncate than a hex digest).
Note: Using UUID4 (random). See http://en.wikipedia.org/wiki/Universally_unique_identifier for the other types.
One way would be:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.values()))
EDIT: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:
country, capital = random.choice(list(d.items()))
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 ) }}
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
[k for (k, v) in i.iteritems() if v == 0]
Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0}
is perfectly legal.
If you want ordering you either need to use a list or a OrderedDict instance instead:
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
Everybody did explain why this problem occurs, but it's still very easy to forget about it and then scratching your head why you got wrong results. Especially when you're working on big sets of data when the results seem to be fine at first glance.
Using Object.entries
you ensure to go trough all properties:
var arr = [3, 5, 7];
arr.foo = "hello";
for ( var [key, val] of Object.entries( arr ) ) {
console.log( val );
}
/* Result:
3
5
7
hello
*/
I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")
train_set = ["president of India",doc1, doc2, doc3]
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set) #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train) #here the first element of tfidf_matrix_train is matched with other three elements
Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.
Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III
the output will be as follows :
[[ 1. 0.07102631 0.02731343 0.06348799]]
here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.
No.
The only API browsers give you for handling cookies is getting and setting them via key-value pairs. All browsers handle cookies by domain name only.
Accessing all cookies for current domain is done via document.cookie
.
Both methods do the same functionally - they compare values.
As is written on MSDN:
String.Equals
method - Determines whether this instance and
another specified String object have the same value. (http://msdn.microsoft.com/en-us/library/858x0yyx.aspx)==
- Although string is a reference type, the equality operators (==
and
!=
) are defined to compare the values of string objects, not
references. This makes testing for string equality more intuitive. (http://msdn.microsoft.com/en-en/library/362314fe.aspx)But if one of your string instances is null, these methods are working differently:
string x = null;
string y = "qq";
if (x == y) // returns false
MessageBox.Show("true");
else
MessageBox.Show("false");
if (x.Equals(y)) // returns System.NullReferenceException: Object reference not set to an instance of an object. - because x is null !!!
MessageBox.Show("true");
else
MessageBox.Show("false");
Usually, the following command does the trick:
sudo service docker restart
This, instead of docker start
for the cases where Docker seems to already be running.
If that works then, as suggested and in another answer and on this GitHub issue, if you haven't added yourself in the docker group do it by running:
sudo usermod -aG docker <your-username>
And you're most likely good to go.
As for anybody else bumping into this, in some OS's docker doesn't start right after you install it and, as a result, the same can't connect to daemon message
appears. In this case you can first verify that Docker is indeed not running by checking the status of your docker service by executing:
sudo service docker status
If the output looks something like: docker stop/waiting
instead of docker start/running, process 15378
then it obviously means Docker is not active. In this case make sure you start it with:
sudo service docker start
And, as before, you'll most likely be good to go.
First of all, there are two possible 'versions' that you might be interested in:
Windows filesystem file version, applicable to all executable files
Assembly build version, which is embedded in a .NET assembly by the compiler (obviously only applicable to .NET assembly dll and exe files)
In the former case, you should use Ben Anderson's answer; in the latter case, use AssemblyName.GetAssemblyName(@"c:\path\to\file.dll").Version
, or Tataro's answer, in case the assembly is referenced by your code.
Note that you can ignore all the answers that use .Load()
/.LoadFrom()
methods, since these actually load the assembly in the current AppDomain - which is analogous to cutting down a tree to see how old it is.
You can add this in your onCreate Method
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// going to next activity
Intent i=new Intent(SplashScreenActivity.this,MainActivity.class);
startActivity(i);
finish();
}
},time);
And initialize your time value in milliseconds as yo want...
private static int time=5000;
for more detail download full code from this link...
Thomas Becker wrote a useful article on the subject here.
There was also this (perhaps simpler) approach that appeared previously on SO: How to correctly implement custom iterators and const_iterators?
mod_php
means PHP, as an Apache module.
Basically, when loading mod_php
as an Apache module, it allows Apache to interpret PHP files (those are interpreted by mod_php
).
EDIT : There are (at least) two ways of running PHP, when working with Apache :
mod_php
) : the PHP interpreter is then kind of "embedded" inside the Apache process : there is no external PHP process -- which means that Apache and PHP can communicate better.
And re-edit, after the comment : using CGI or mod_php
is up to you : it's only a matter of configuration of your webserver.
To know which way is currently used on your server, you can check the output of phpinfo()
: there should be something indicating whether PHP is running via mod_php
(or mod_php5
), or via CGI.
You might also want to take a look at the php_sapi_name()
function : it returns the type of interface between web server and PHP.
If you check in your Apache's configuration files, when using mod_php
, there should be a LoadModule
line looking like this :
LoadModule php5_module modules/libphp5.so
(The file name, on the right, can be different -- on Windows, for example, it should be a .dll
)
You may find OpenJDK 6 and 7 binaries for Windows in openjdk-unofficial-builds github project.
Update: OpenJDK 8 and 11 LTS binaries for Windows x86_64 can be found in ojdkbuild github project.
Disclaimer: I've built them myself.
Update (2019): OpenJDK Updates Project Builds for 8 and 11 are available now.
Here is a regex I made which extracts the different parts from an URL:
^((?:https?|ftp):\/\/?)?([^:/\s.]+\.[^:/\s]|localhost)(:\d+)?((?:\/\w+)*\/)?([\w\-.]+[^#?\s]+)?([^#]+)?(#[\w-]+)?$
((?:https?|ftp):\/\/?)?
(group 1): extracts the protocol
([^:/\s.]+\.[^:/\s]|localhost)
(group 2): extracts the hostname
(:\d+)?
(group 3): extracts the port number
((?:\/\w+)*\/)?([\w\-.]+[^#?\s]+)?
(groups 4 & 5): extracts the path part
([^#]+)?
(group 6): extracts the query part
(#[\w-]+)?
(group 7): extracts the hash part
For every part of the regex listed above, you can remove the ending ?
to force it (or add one to make it facultative). You can also remove the ^
at the beginning and $
at the end of the regex so it won't need to match the whole string.
See it on regex101.
Note: this regex is not 100% safe and may accept some strings which are not necessarily valid URLs but it does indeed validate some criterias. Its main goal was to extract the different parts of an URL not to validate it.
I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.
find
's optionsThere is actually no exec of /bin/ls
needed;
Find has an option that does just that:
find . -maxdepth 2 -type d -ls
To see only the one level of subdirectories you are interested in, add -mindepth
to the same level as -maxdepth
:
find . -mindepth 2 -maxdepth 2 -type d -ls
When the details that get shown should be different, -printf
can show any detail about a file in custom format;
To show the symbolic permissions and the owner name of the file, use -printf
with %M
and %u
in the format
.
I noticed later you want the full ownership information, which includes
the group. Use %g
in the format for the symbolic name, or %G
for the group id (like also %U
for numeric user id)
find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
This should give you just the details you need, for just the right files.
I will give an example that shows actually different values for user and group:
$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data www-data /tmp/user/33
drwx------ octopussy root /tmp/user/126
drwx------ root root /tmp/user/0
drwx------ siegel root /tmp/user/1000
drwxrwxrwt root root /tmp/systemd-[...].service-HRUQmm/tmp
(Edited for readability: indented, shortened last line)
Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:
Not only do we save creating a new process for each name - a huge task -
the information does not even need to be read, as find
already knows it.
I have utilize c# Uri class and it works, well with IP Address, localhost
public static bool CheckURLIsValid(string url)
{
Uri returnURL;
return (Uri.TryCreate(url, UriKind.Absolute, out returnURL)
&& (returnURL.Scheme == Uri.UriSchemeHttp || returnURL.Scheme == Uri.UriSchemeHttps));
}
The issue is probably due to /foo/bar not being owned by the writing process on a remote darwin (OS X) system. A solution to the issue is to set adequate owner on the remote site.
Since this answer has been voted, and therefore has been hopefully useful to someone, I'm extending it to make it clearer.
The reason why this happens is that rsync is probably trying to set an arbitrary modification time (mtime) when copying files.
In order to do this darwin's system utime()
function requires that the writing process effective uid is either the same as the file uid or super user's one, see opengroup utime's page.
Check this discussion on rsync mailing list as reference.
The tr
command could be replaced by //
bashism:
COMMAND=$'\nREBOOT\r \n'
echo "|${COMMAND}|"
|
OOT
|
echo "|${COMMAND//[$'\t\r\n']}|"
|REBOOT |
echo "|${COMMAND//[$'\t\r\n ']}|"
|REBOOT|
See Parameter Expansion and QUOTING in bash's man page:
man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash
man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash
As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND
do contain spaces...
COMMAND=$' \n RE BOOT \r \n'
echo "|$COMMAND|"
|
BOOT
|
CLEANED=${COMMAND//[$'\t\r\n']}
echo "|$CLEANED|"
| RE BOOT |
shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}
CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
| RE BOOT|
CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|
Shortly:
COMMAND=$' \n RE BOOT \r \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|
Note: bash have extglob
option to be enabled (shopt -s extglob
) in order to use *(...)
syntax.
I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.
So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.
pointers(ex:char *arr,int *arr) -------> heap
Nope, they can be on the stack or in the data segment. They can point anywhere.
Swift 5
The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.
To retain the old style you need to modify the view controller you will be presenting like this:
newViewController.modalPresentationStyle = .fullScreen
This is the same for both programmatically created and storyboard created controllers.
Swift 3
With a programmatically created Controller
If you want to navigate to Controller created Programmatically, then do this:
let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)
With a StoryBoard created Controller
If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
self.present(newViewController, animated: true, completion: nil)
open solition explorer
right click the webservice change URL Behavior to Dynamic
click the 'show all files' icon in solution explorer
in the web reference edit the Reference.cs file
change constructer
public Service1() {
this.Url = "URL"; // etc. string variable this.Url = ConfigClass.myURL
}
Is
is not the same as =
-- Is
compares the references, whilst =
will compare the values.
If you're using v2 of the .Net Framework (or later), there is the IsNot
operator which will do the right thing, and read more naturally.
1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.
android {
...
defaultConfig {
multiDexEnabled true
...
}
}
dependencies {
// add dependency
implementation 'com.android.support:multidex:1.0.1'
}
2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
.
.
.
.
.
</application>
3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.
public class MyApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]
Hopefully, It works for you.
Check if you have all NLTK libraries.
Add some CSS:
div#nav{
text-align: center;
}
div#nav ul{
display: inline-block;
}
I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:
#!/usr/bin/python3
""" Demonstrating Flask, using APScheduler. """
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask
def sensor():
""" Function for test purposes. """
print("Scheduler is alive!")
sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=60)
sched.start()
app = Flask(__name__)
@app.route("/home")
def home():
""" Function for test purposes. """
return "Welcome Home :) !"
if __name__ == "__main__":
app.run()
I'm also leaving this Gist here, if anyone have interest on updates for this example.
Here are some references, for future readings:
This suffices :
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);
since if the refnode
(second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore
Actually I doubt that the || null
is required, try it and see.
I've made a plugin vim-textobj-quotes
: https://github.com/beloglazov/vim-textobj-quotes
It provides text objects for the closest pairs of quotes of any type. Using only iq
or aq
it allows you to operate on the content of single ('), double ("), or back (`) quotes that currently surround the cursor, are in front of the cursor, or behind (in that order of preference). In other words, it jumps forward or backwards when needed to reach the quotes.
It's easier to understand by looking at examples (the cursor is shown with |
):
foo '1, |2, 3' bar
; after pressing diq
: foo '|' bar
foo| '1, 2, 3' bar
; after pressing diq
: foo '|' bar
foo '1, 2, 3' |bar
; after pressing diq
: foo '|' bar
foo '1, |2, 3' bar
; after pressing daq
: foo | bar
foo| '1, 2, 3' bar
; after pressing daq
: foo | bar
foo '1, 2, 3' |bar
; after pressing daq
: foo | bar
The examples above are given for single quotes, the plugin works exactly the same way for double (") and back (`) quotes.
You can also use any other operators: ciq
, diq
, yiq
, viq
, etc.
Please have a look at the github page linked above for more details.
use
=VLOOKUP(D4,F4:G9,2)
with the range F4:G9:
0 0.1
1 0.15
5 0.2
15 0.3
30 1
100 1.3
and D4
being the value in question, e.g. 18.75
-> result: 0.3
I have to pass two parameters like:
/Controller/Action/Param1Value/Param2Value
This way:
@Html.ActionLink(
linkText,
actionName,
controllerName,
routeValues: new {
Param1Name= Param1Value,
Param2Name = Param2Value
},
htmlAttributes: null
)
will generate this url
/Controller/Action/Param1Value?Param2Name=Param2Value
I used a workaround method by merging parameter two in parameter one and I get what I wanted:
@Html.ActionLink(
linkText,
actionName,
controllerName,
routeValues: new {
Param1Name= "Param1Value / Param2Value" ,
},
htmlAttributes: null
)
And I get :
/Controller/Action/Param1Value/Param2Value
You can just use "!important" to get your custom color
.navbar {
background-color: yourcolor !important;
}
You could try to extract columns as list, massage this as you want, and reindex your dataframe:
>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...
>>> df.reindex(columns=['n']+df.columns[:-1].tolist())
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
If that's what I understood, it's like this:
C:\Users\(username)\AppData\Local\Programs\Python\Python(version)
COPY (not delete) python.exe and rename to py.exe and execute:
py filename.py
GCC is ubiquitous. It is trusted and well understood by thousands of folks across dozens of communities.
Visual Studio is perhaps the best IDE ever developed. It has a great compiler underneath it. But it is strictly Windows-only.
If you're just playing, get GCC --it's free. If you're concerned about multiple platfroms, it's GCC. If you're talking serious Windows development, get Visual Studio.
Just to save time of people who come to the post (like me, who looking for Spring config type and want you schema name be set by an external source (property file)). The configuration will work for you is
<bean id="domainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JiraManager"/>
<property name="dataSource" ref="domainDataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false"/>
<property name="showSql" value="false"/>
<property name="databasePlatform" value="${hibernate.dialect}"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.default_schema">${yourSchema}</prop>
</props>
</property>
</bean>
Ps : For the hibernate.hdm2ddl.auto, you could look in the post Hibernate hbm2ddl.auto possible values and what they do? I have used to set create-update,because it is convenient. However, in production, I think it is better to take control of the ddl, so I take whatever ddl generate first time, save it, rather than let it automatically create and update.
Simple:
[DataType(DataType.Date)]
Public DateTime Ldate {get;set;}
I like @Omry Yadan's solution but I think it can be improved upon to use a loop in case you want to continue traversing up the directory tree until you find where wp-config.php
actually lives. Of course, if you don't find it and end up in the server's root then all is lost and we return a sane value (false
).
function wp_get_web_root() {
$base = dirname(__FILE__);
$path = false;
while(!$path && '/' != $base) {
if(@file_exists(dirname($base)).'/wp-config.php') {
$path = dirname($base);
} else {
$base = dirname($base);
}
}
return $path;
}
I know this post is from 4 years ago, but because of my C# background I was looking for a way to call the base class without having to specify the class name but rather obtain it by a property on the subclass. So my only change to Christoph's answer would be
From this:
MyClass.prototype.doStuff.call(this /*, args...*/);
To this:
this.constructor.prototype.doStuff.call(this /*, args...*/);
You have to go to the sheet of db to get the first blank row, you could try this method.
Sub DesdeColombia ()
Dim LastRowFull As Long
'Here we will define the first blank row in the column number 1 of sheet number 1:
LastRowFull = Sheet1.Cells(Rows.Count,1).End(xlUp).Offset(1,0).Row
'Now we are going to insert information
Sheet1.Cells(LastRowFull, 1).Value = "We got it"
End Sub
I was having the same problem except that I was importing the classes for which dependencies were not resolving somehow. I refreshed maven projects, Rebuild Project. It still did not resolve. Looks like IntelliJ was caching something incorrectly. I restarted IntelliJ and that resolved the dependencies. I guess it cleared the cache somehow.
Alternatively you can convert your object into a dataframe first:
df = pd.DataFrame(obj)
and then save this dataframe
in a json
file:
df.to_json(path_or_buf='df.json')
Hope this helps
Please check this:
* {margin: 0; padding: 0;}
html, body { width: 100%; height: 100%;}
Or try new method Viewport height :
html, body { width: 100vw; height: 100vh;}
Viewport: If your using viewport means whatever size screen content will come full height fo the screen.
for f, b in zip(foo, bar):
print(f, b)
zip
stops when the shorter of foo
or bar
stops.
In Python 3, zip
returns an iterator of tuples, like itertools.izip
in Python2. To get a list
of tuples, use list(zip(foo, bar))
. And to zip until both iterators are
exhausted, you would use
itertools.zip_longest.
In Python 2, zip
returns a list of tuples. This is fine when foo
and bar
are not massive. If they are both massive then forming zip(foo,bar)
is an unnecessarily massive
temporary variable, and should be replaced by itertools.izip
or
itertools.izip_longest
, which returns an iterator instead of a list.
import itertools
for f,b in itertools.izip(foo,bar):
print(f,b)
for f,b in itertools.izip_longest(foo,bar):
print(f,b)
izip
stops when either foo
or bar
is exhausted.
izip_longest
stops when both foo
and bar
are exhausted.
When the shorter iterator(s) are exhausted, izip_longest
yields a tuple with None
in the position corresponding to that iterator. You can also set a different fillvalue
besides None
if you wish. See here for the full story.
Note also that zip
and its zip
-like brethen can accept an arbitrary number of iterables as arguments. For example,
for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'],
['red', 'blue', 'green']):
print('{} {} {}'.format(num, color, cheese))
prints
1 red manchego
2 blue stilton
3 green brie
If your object could contain any key/value pairs, you could declare an interface called keyable
like :
interface keyable {
[key: string]: any
}
then use it as follows :
let countryProviders: keyable[];
or
let countryProviders: Array<keyable>;
here's what six is:
pip search six
six - Python 2 and 3 compatibility utilities
to install:
pip install six
though if you did install python-dateutil
from pip six should have been set as a dependency.
N.B.: to install pip run easy_install pip
from command line.
You might want Python's UUID functions:
21.15. uuid — UUID objects according to RFC 4122
eg:
import uuid
print uuid.uuid4()
7d529dd4-548b-4258-aa8e-23e34dc8d43d
This fixed my problem:
$http.defaults.headers.post["Content-Type"] = "text/plain";
I've used something like this with a Bash shell on Ubuntu 12.04 (LTS):
To append a new line with tab,second when first is matched:
sed -i '/first/a \\t second' filename
To replace first with tab,second:
sed -i 's/first/\\t second/g' filename
This may be platform specific, I somehow doubt it, but anyway, the best explanation I've seen is here on this msdn page where they explain about shutdown, linger options, socket closure and general connection termination sequences.
In summary, use shutdown to send a shutdown sequence at the TCP level and use close to free up the resources used by the socket data structures in your process. If you haven't issued an explicit shutdown sequence by the time you call close then one is initiated for you.
import java.math.*;
public class TestRound11 {
public static void main(String args[]){
double d = 3.1537;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
}
public static double round(double d, int decimalPlace){
// see the Javadoc about why we use a String in the constructor
// http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
}
Right-click on the function, select "Document this" and
private bool FindTheFoo(int numberOfFoos)
becomes
/// <summary>
/// Finds the foo.
/// </summary>
/// <param name="numberOfFoos">The number of foos.</param>
/// <returns></returns>
private bool FindTheFoo(int numberOfFoos)
(yes, it is all autogenerated).
It has support for C#, VB.NET and C/C++. It is per default mapped to Ctrl+Shift+D.
Remember: you should add information beyond the method signature to the documentation. Don't just stop with the autogenerated documentation. The value of a tool like this is that it automatically generates the documentation that can be extracted from the method signature, so any information you add should be new information.
That being said, I personally prefer when methods are totally selfdocumenting, but sometimes you will have coding-standards that mandate outside documentation, and then a tool like this will save you a lot of braindead typing.
Your first usage of Map
is inside a function in the combat
class. That happens before Map
is defined, hence the error.
A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map
is fully declared.
The solution is to follow the C++ pattern of the class declaration in a .h
file and the function bodies in a .cpp
. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.
The Unicode code blocks that the others answers gave certainly cover most of the Chinese Unicode characters, but check out some of these other code blocks, too.
CJK_UNIFIED_IDEOGRAPHS
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E
CJK_COMPATIBILITY
CJK_COMPATIBILITY_FORMS
CJK_COMPATIBILITY_IDEOGRAPHS
CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT
CJK_RADICALS_SUPPLEMENT
CJK_STROKES
CJK_SYMBOLS_AND_PUNCTUATION
ENCLOSED_CJK_LETTERS_AND_MONTHS
ENCLOSED_IDEOGRAPHIC_SUPPLEMENT
KANGXI_RADICALS
IDEOGRAPHIC_DESCRIPTION_CHARACTERS
See my fuller discussion here. And this site is convenient for browsing Unicode.
list comprehension
simple implementation with list comprehension ( my favorite)
df = pd.DataFrame([pd.Series(x) for x in df.teams])
df.columns = ['team_{}'.format(x+1) for x in df.columns]
timing on output:
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 2.71 ms
output:
team_1 team_2
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
Here you go. I have used this code with UIView, though. You should be able to make those adjustments for scrollview.
func addKeyboardNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow(notification:)),
name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide(notification:)),
name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
// if using constraints
// bottomViewBottomSpaceConstraint.constant = keyboardSize.height
self.view.frame.origin.y -= keyboardSize.height
UIView.animate(withDuration: duration) {
self.view.layoutIfNeeded()
}
}
}
func keyboardWillHide(notification: NSNotification) {
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
//if using constraint
// bottomViewBottomSpaceConstraint.constant = 0
self.view.frame.origin.y = 0
UIView.animate(withDuration: duration) {
self.view.layoutIfNeeded()
}
}
Don't forget to remove notifications at right place.
func removeKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
The problem is you can't template a typedef, also there is no need to typedef structs in C++.
The following will do what you need
template <typename T>
struct array {
size_t x;
T *ary;
};
sometimes whenever you copy cURL, it contains --compressed. Remove it while import->Paste Raw Text-->click on import. It will also solve the problem if you are getting the syntax error in postman while importing any cURL.
Generally, when people copy cURL from any proxy tools like Charles, it happens.
This solved it for me
AppRegistry.registerComponent('main', () => App);
So my index.js
file
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('main', () => App);
And my package.json
file:
"dependencies": {
"react": "^16.13.1",
"react-dom": "~16.9.0",
"react-native": "~0.61.5"
},
Big one I see that causes this is filename. If you have a SPACE then any number such as 'Site 2' the file path with look like something/Site%202/index.html This is because spaces or rendered as %20, and if another number is immediately following that it will try to read it as %202. Fix is you never use spaces in your filenames.
I found this page because I needed to migrate a site with many many bindings to a new server. I used some of the code here to generate the powershell script below to add the bindings to the new server. Sharing in case it is useful to someone else:
Import-Module WebAdministration
$Websites = Get-ChildItem IIS:\Sites
$site = $Websites | Where-object { $_.Name -eq 'site-name-in-iis-here' }
$Binding = $Site.bindings
[string]$BindingInfo = $Binding.Collection
[string[]]$Bindings = $BindingInfo.Split(" ")
$i = 0
$header = ""
Do{
[string[]]$Bindings2 = $Bindings[($i+1)].Split(":")
Write-Output ("New-WebBinding -Name `"site-name-in-iis-here`" -IPAddress " + $Bindings2[0] + " -Port " + $Bindings2[1] + " -HostHeader `"" + $Bindings2[2] + "`"")
$i=$i+2
} while ($i -lt ($bindings.count))
It generates records that look like this:
New-WebBinding -Name "site-name-in-iis-here" -IPAddress "*" -Port 80 -HostHeader www.aaa.com
You are declaring a local variable, not a class variable. To set an instance variable (attribute), use
class Example(object):
def the_example(self):
self.itsProblem = "problem" # <-- remember the 'self.'
theExample = Example()
theExample.the_example()
print(theExample.itsProblem)
To set a class variable (a.k.a. static member), use
class Example(object):
def the_example(self):
Example.itsProblem = "problem"
# or, type(self).itsProblem = "problem"
# depending what you want to do when the class is derived.
1) you are calling it wrong way try:
$(input[name="searchBar"]).val('hi')
2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event
$(document).ready(function() {
$(input[name="searchBar"]).val('hi');
});
In python, A dynamic array is an 'array' from the array module. E.g.
from array import array
x = array('d') #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop() # returns 2.2
This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.
However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.
See https://docs.python.org/2/library/array.html for details.
You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:
sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
open new terminal and validate environment is clean from old RVM settings (should be no output):
env | grep rvm
if there was output, try to open new terminal, if it does not help then restart your computer.
\curl -L https://get.rvm.io |
bash -s stable --ruby --autolibs=enable --auto-dotfiles
If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.
I would urge against using OleDB, especially if its going to be run on a server. Its likely to cost you more in the long run - eg we had a SSIS job calling a Stored Procedure with the OleDB reading an excel file in the sptroc and kept crashing the SQL box! I took the OleDB stuff out of the sproc and it stopped crashing the server.
A better method I've found is to do it with Office 2003 and the XML files - in respect of Considerations for server-side Automation of Office. Note: Office 2003 is a minimum requirement for this to fly:
Ref for reading from Excel: http://www.roelvanlisdonk.nl/?p=924 (please do more research to find other examples)
Ref for writing a Excel spreadsheet: http://weblogs.asp.net/jgaylord/archive/2008/08/11/use-linq-to-xml-to-generate-excel-documents.aspx
public void ReadExcelCellTest()
{
XDocument document = XDocument.Load(@"C:\BDATA\Cars.xml");
XNamespace workbookNameSpace = @"urn:schemas-microsoft-com:office:spreadsheet";
// Get worksheet
var query = from w in document.Elements(workbookNameSpace + "Workbook").Elements(workbookNameSpace + "Worksheet")
where w.Attribute(workbookNameSpace + "Name").Value.Equals("Settings")
select w;
List<XElement> foundWoksheets = query.ToList<XElement>();
if (foundWoksheets.Count() <= 0) { throw new ApplicationException("Worksheet Settings could not be found"); }
XElement worksheet = query.ToList<XElement>()[0];
// Get the row for "Seat"
query = from d in worksheet.Elements(workbookNameSpace + "Table").Elements(workbookNameSpace + "Row").Elements(workbookNameSpace + "Cell").Elements(workbookNameSpace + "Data")
where d.Value.Equals("Seat")
select d;
List<XElement> foundData = query.ToList<XElement>();
if (foundData.Count() <= 0) { throw new ApplicationException("Row 'Seat' could not be found"); }
XElement row = query.ToList<XElement>()[0].Parent.Parent;
// Get value cell of Etl_SPIImportLocation_ImportPath setting
XElement cell = row.Elements().ToList<XElement>()[1];
// Get the value "Leon"
string cellValue = cell.Elements(workbookNameSpace + "Data").ToList<XElement>()[0].Value;
Console.WriteLine(cellValue);
}
ianhanniballake is right. You can get all the functionality of Activity
from FragmentActivity
. In fact, FragmentActivity
has more functionality.
Using FragmentActivity
you can easily build tab and swap
format. For each tab you can use different Fragment
(Fragments
are reusable). So for any FragmentActivity
you can reuse the same Fragment
.
Still you can use Activity
for single pages like list down something and edit element of the list in next page.
Also remember to use Activity
if you are using android.app.Fragment
; use FragmentActivity
if you are using android.support.v4.app.Fragment
. Never attach a android.support.v4.app.Fragment
to an android.app.Activity
, as this will cause an exception to be thrown.
If you want the dot or other characters with a special meaning in regexes to be a normal character, you have to escape it with a backslash. Since regexes in Java are normal Java strings, you need to escape the backslash itself, so you need two backslashes e.g. \\.
I got the same issue, salutations are here
Avoid Jackson serialization on non fetched lazy objects
http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/
Try adding a header() call before sending headers, like:
header('X-Powered-By: Our company\'s development team');
regardless of the expose_php setting in php.ini
Internally, Javascript strings are all Unicode (actually UCS-2, a subset of UTF-16).
If you're retrieving the JSON files separately via AJAX, then you only need to make sure that the JSON files are served with the correct Content-Type and charset: Content-Type: application/json; charset="utf-8"
). If you do that, jQuery should already have interpreted them properly by the time you access the deserialized objects.
Could you post an example of the code you’re using to retrieve the JSON objects?