Use find
:
find . -maxdepth 1 -name "*string*" -print
It will find all files in the current directory (delete maxdepth 1
if you want it recursive) containing "string" and will print it on the screen.
If you want to avoid file containing ':', you can type:
find . -maxdepth 1 -name "*string*" ! -name "*:*" -print
If you want to use grep
(but I think it's not necessary as far as you don't want to check file content) you can use:
ls | grep touch
But, I repeat, find
is a better and cleaner solution for your task.
If need to find nested in some dirs:
find / -type f -wholename "*dirname/filename"
Or connected dirs:
find / -type d -wholename "*foo/bar"
The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing. So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.
Try using "/" instead of "\" for the path to your image. Some comments here seem to come from people that do not understand some of us are simply learning web development which in many cases is best done locally. So instead of using src=C:\Pics\H.gif use src="C:/Pics/H.gif" for an absolute path or just src="Pics/H.gif" for a relative path if your Pics are in a sub-directory of your html page's location). Note also, it is good practice to surround your path with quotes. otherwise you will have problems with paths that include spaces and other odd characters.
Add the servlet-api.jar
to your classpath. You can take it from tomcat's lib folder.
I suspect you would just want to grab a few columns from V$SESSION and the SQL statement from V$SQL. Assuming you want to exclude the background processes that Oracle itself is running
SELECT sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text
FROM v$session sess,
v$sql sql
WHERE sql.sql_id(+) = sess.sql_id
AND sess.type = 'USER'
The outer join is to handle those sessions that aren't currently active, assuming you want those. You could also get the sql_fulltext column from V$SQL which will have the full SQL statement rather than the first 1000 characters, but that is a CLOB and so likely a bit more complicated to deal with.
Realistically, you probably want to look at everything that is available in V$SESSION because it's likely that you can get a lot more information than SP_WHO provides.
This is not stated in the documentation, but to clear the opcode cache you must do:
apc_clear_cache('opcode');
EDIT: This seems to only apply to some older versions of APC..
No matter what version you are using you can't clear mod_php or fastcgi APC cache from a php cli script since the cli script will run from a different process as mod_php or fastcgi. You must call apc_clear_cache() from within the process (or child process) which you want to clear the cache for. Using curl to run a simple php script is one such approach.
I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.
@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL
This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.
A bit late to the party, but this is what worked for me:
>>> import sys
>>> sys.path.insert(0, '')
Apparently, if there is an empty string, Python knows that it should look in the current directory. I did not have the empty string in sys.path
, which caused this error.
Looking for a one line option:
<div class="jumbotron bg-dark"> got a team? </div>
Just try with:
var check = moment(n.entry.date_entered, 'YYYY/MM/DD');
var month = check.format('M');
var day = check.format('D');
var year = check.format('YYYY');
In C ++, if a const object is initialized with a constant expression, we can use our const object wherever a constant expression is required.
const int x = 10;
int a[x] = {0};
For example, we can make a case statement in switch.
constexpr can be used with arrays.
constexpr is not a type.
The constexpr keyword can be used in conjunction with the auto keyword.
constexpr auto x = 10;
struct Data { // We can make a bit field element of struct.
int a:x;
};
If we initialize a const object with a constant expression, the expression generated by that const object is now a constant expression as well.
Constant Expression : An expression whose value can be calculated at compile time.
x*5-4 // This is a constant expression. For the compiler, there is no difference between typing this expression and typing 46 directly.
Initialize is mandatory. It can be used for reading purposes only. It cannot be changed. Up to this point, there is no difference between the "const" and "constexpr" keywords.
NOTE: We can use constexpr and const in the same declaration.
constexpr const int* p;
Normally, the return value of a function is obtained at runtime. But calls to constexpr functions will be obtained as a constant in compile time when certain conditions are met.
NOTE : Arguments sent to the parameter variable of the function in function calls or to all parameter variables if there is more than one parameter, if C.E the return value of the function will be calculated in compile time. !!!
constexpr int square (int a){
return a*a;
}
constexpr int a = 3;
constexpr int b = 5;
int arr[square(a*b+20)] = {0}; //This expression is equal to int arr[35] = {0};
In order for a function to be a constexpr function, the return value type of the function and the type of the function's parameters must be in the type category called "literal type".
The constexpr functions are implicitly inline functions.
None of the constexpr functions need to be called with a constant expression.It is not mandatory. If this happens, the computation will not be done at compile time. It will be treated like a normal function call. Therefore, where the constant expression is required, we will no longer be able to use this expression.
1 ) The types used in the parameters of the function and the type of the return value of the function must be literal type.
2 ) A local variable with static life time should not be used inside the function.
3 ) If the function is legal, when we call this function with a constant expression in compile time, the compiler calculates the return value of the function in compile time.
4 ) The compiler needs to see the code of the function, so constexpr functions will almost always be in the header files.
5 ) In order for the function we created to be a constexpr function, the definition of the function must be in the header file.Thus, whichever source file includes that header file will see the function definition.
Normally with Default Member Initialization, static data members with const and integral types can be initialized within the class. However, in order to do this, there must be both "const" and "integral types".
If we use static constexpr then it doesn't have to be an integral type to initialize it inside the class. As long as I initialize it with a constant expression, there is no problem.
class Myclass {
const static int sx = 15; // OK
constexpr static int sy = 15; // OK
const static double sd = 1.5; // ERROR
constexpr static double sd = 1.5; // OK
};
I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.
Like this:
int Marylyn[256], Ann[1024];
The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:
#define TWO_FIFTY_SIX 256
#define TEN_TWENTY_FOUR 1024
int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];
On the following Monday afternoon I was called in and accused of having passive defiant tendencies.
Function pointers are a great way to do this, e.g.
result = switchFunction(someStringKey); //result is an optional return value
...this calls a function that you have set by string key (one function per case):
setSwitchFunction("foo", fooFunc);
setSwitchFunction("bar", barFunc);
Use a pre-existing hashmap/table/dictionary implementation such as khash, return that pointer to a function inside of switchFunction()
, and execute it (or just return it from switchFunction()
and execute it yourself). If the map implementation doesn't store that, just use a uint64_t
instead that you cast accordingly to a pointer.
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an =
as true
.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
This happened to me and while sourcetree kept telling me the lock file exists, there was no such a file there for me to remove. So I just checked out another branch and then returned to the original branch and noticed this change fixed the issue.
I tried my best to follow the answers given above. But I have below reason for the same.
Note: This is for maven+eclipse+tomcat deployment and issue faced especially with spring mvc.
1- If you are including servlet and jsp dependency please mark them provided in scope.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
Possibly you might be including jstl as dependency. So, jsp-api.jar
and servlet-api.jar
will be included along. So, require to exclude the servlet-api and jsp-api being deployed as required lib in target or in "WEB-INF/lib" as given below.
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
<exclusion>
<artifactId>jsp-api</artifactId>
<groupId>javax.servlet.jsp</groupId>
</exclusion>
</exclusions>
</dependency>
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
If you use the Angular CLI to create your components, let's say CarComponent
, it attaches app
to the selector name (i.e app-car
) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car>
or change the selector in the CarComponent
to selector: 'car'
what might get you where you want in plain SQL92:
select * from tbl where lower(answer) = upper(answer)
or, if you also want to be robust for leading/trailing spaces:
select * from tbl where lower(answer) = trim(upper(answer))
You might try a queuing system like Resque. You then can generate a job, that processes the information and quite fast return with the "processing" image. With this approach you won't know when it is finished though.
This solution is intended for larger scale applications, where you don't want your front machines to do the heavy lifting, so they can process user requests. Therefore it might or might not work with physical data like files and folders, but for processing more complicated logic or other asynchronous tasks (ie new registrations mails) it is nice to have and very scalable.
Show time in form 24 hours
Right("0" & hour(now),2) & ":" & Right("0" & minute(now),2) = 01:35
Right("0" & hour(now),2) = 01
Right("0" & minute(now),2) = 35
You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$status_codes = array (
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
There is no $contains
operator in mongodb.
You can use the answer from JohnnyHK as that works. The closest analogy to contains that mongo has is $in
, using this your query would look like:
PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);
Timer.Elapsed
expects method of specific signature (with arguments object
and EventArgs
). If you want to use your PlayMusicEvent
method with additional argument evaluated during event registration, you can use lambda expression as an adapter:
myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));
Edit: you can also use shorter version:
myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);
Move the Directory clause out of the virtualhost, and put it before declaring the virtualhost.
Drove me nuts for a long time too. Don't know why. It's a Debian thing.
One of the difference is that merge
is creating a new index, and join
is keeping the left side index. It can have a big consequence on your later transformations if you wrongly assume that your index isn't changed with merge
.
For example:
import pandas as pd
df1 = pd.DataFrame({'org_index': [101, 102, 103, 104],
'date': [201801, 201801, 201802, 201802],
'val': [1, 2, 3, 4]}, index=[101, 102, 103, 104])
df1
date org_index val
101 201801 101 1
102 201801 102 2
103 201802 103 3
104 201802 104 4
-
df2 = pd.DataFrame({'date': [201801, 201802], 'dateval': ['A', 'B']}).set_index('date')
df2
dateval
date
201801 A
201802 B
-
df1.merge(df2, on='date')
date org_index val dateval
0 201801 101 1 A
1 201801 102 2 A
2 201802 103 3 B
3 201802 104 4 B
-
df1.join(df2, on='date')
date org_index val dateval
101 201801 101 1 A
102 201801 102 2 A
103 201802 103 3 B
104 201802 104 4 B
Here is something that i have been trying.(Insertion sort- not the best way to sort but does the work)
def sort(list):
for index in range(1,len(list)):
value = list[index]
i = index-1
while i>=0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i -= 1
else:
break
Just a helpful hint, there is a company called Yodlee.com who provides this data. They do charge for the API. Companies like Mint.com use this API to gather bank and financial account data.
Also, checkout https://plaid.com/, they are a similar company Yodlee.com and provide both authentication API for several banks and REST-based transaction fetching endpoints.
I have tried directlabels
package for putting text labels. In the case of scatter plots it's not still perfect, but much better than manually adjusting the positions, specially in the cases that you are preparing the draft plots and not the final one - so you need to change and make plot again and again -.
You can also use rsync
rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out
The CSS :active
state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.
To fix your problem you have to create a class and add it manually to the current page's menu:
a.active { color: #f00 }
<ul>
<li><a href="index.php" class="active">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
To me, the problem looks like you're sending "datetime('now')"
as a string, rather than a value.
My thought is to find a way to grab the current date/time and send it to your database as a date/time value, or find a way to use SQLite's built-in (DATETIME('NOW'))
parameter
Check out the anwsers at this SO.com question - they might lead you in the right direction.
Hopefully this helps!
function uploadfile(ctrl) {
var validate = validateimg(ctrl);
if (validate) {
if (window.FormData !== undefined) {
ShowLoading();
var fileUpload = $(ctrl).get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
fileData.append('username', 'Wishes');
$.ajax({
url: 'UploadWishesFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function(result) {
var id = $(ctrl).attr('id');
$('#' + id.replace('txt', 'hdn')).val(result);
$('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();
HideLoading();
},
error: function(err) {
alert(err.statusText);
HideLoading();
}
});
} else {
alert("FormData is not supported.");
}
}
The download from java.com
which installs in /Library/Internet Plug-Ins
is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home
which you can then add to Eclipse via Preferences -> Java -> Installed JREs.
Use regular expression
var totalWords = "foo love bar very much.";_x000D_
_x000D_
var firstWord = totalWords.replace(/ .*/,'');_x000D_
_x000D_
$('body').append(firstWord);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
var pattern = new RegExp((0|1)[0-9]\/[0-3][0-9]\/(19|20)[0-9]{2});
if(!testdate.match(pattern))
return false;
else return true;
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
You could do something like this: order your table by e.g. CustomerID (using the AdventureWorks Sales.Customer
sample table), and iterate over those customers using a WHILE loop:
-- define the last customer ID handled
DECLARE @LastCustomerID INT
SET @LastCustomerID = 0
-- define the customer ID to be handled now
DECLARE @CustomerIDToHandle INT
-- select the next customer to handle
SELECT TOP 1 @CustomerIDToHandle = CustomerID
FROM Sales.Customer
WHERE CustomerID > @LastCustomerID
ORDER BY CustomerID
-- as long as we have customers......
WHILE @CustomerIDToHandle IS NOT NULL
BEGIN
-- call your sproc
-- set the last customer handled to the one we just handled
SET @LastCustomerID = @CustomerIDToHandle
SET @CustomerIDToHandle = NULL
-- select the next customer to handle
SELECT TOP 1 @CustomerIDToHandle = CustomerID
FROM Sales.Customer
WHERE CustomerID > @LastCustomerID
ORDER BY CustomerID
END
That should work with any table as long as you can define some kind of an ORDER BY
on some column.
Why reinvent the wheel. Just use the STL list container.
#include <list>
// in some function, you now do...
std::list<int> mylist; // integer list
public static void WriteLine(this List<int> theList)
{
foreach (int i in list)
{
Console.Write("{0}\t", t.ToString());
}
Console.WriteLine();
}
Then, later...
list.WriteLine();
If you use Bootstrap 3, it also has built-in CSS class named .text-center. That's what you want.
<div class="text-left">
left
</div>
<div class="text-center">
center
</div>
<div class="text-right">
right
</div>
Please see the example in jsfiddle. http://jsfiddle.net/ucheng/Q4Fue/
Try this:
colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
In a word - yes.
Actually, many classes in the JDK implement multiple interfaces. E.g., ArrayList
implements List
, RandomAccess
, Cloneable
, and Serializable
.
In iOS7 I found that if I had a View inside a UIScrollView on a FreeForm-sized ViewController it would not scroll in the app, no matter what I did. I played around and found the following seemed to work, which uses no FreeForms:
Insert a UIScrollView inside the main View of a ViewController
Set the Autolayout constraints on the ScrollView as appropriate. For me I used 0 to Top Layout guide and 0 to Bottom layout Guide
Inside the ScrollView, place a Container View. Set its height to whatever you want (e.g. 1000)
Add a Height constraint (1000) to the Container so it doesn't resize. The bottom will be past the end of the form.
Add the line [self.scrollView setContentSize:CGSizeMake(320, 1000)]; to the ViewController that contains the scrollView (which you've hooked up as a IBOutlet)
The ViewController (automatically added) that is associated with the Container will have the desired height (1000) in Interface Builder and will also scroll properly in the original view controller. You can now use the container's ViewController to layout your controls.
I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
If you need to run inside a shell:
shell.run(["sh", "-c", "echo -n hello"])
Basic difference between add()
and replace()
can be described as:
add()
is used for simply adding a fragment to some root element.replace()
behaves similarly but at first it removes previous fragments and then adds next fragment.We can see the exact difference when we use addToBackStack()
together with add()
or replace()
.
When we press back button after in case of add()
... onCreateView is never called, but in case of replace()
, when we press back button ... oncreateView is called every time.
This is a simple one line way to do it:
try {
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.
function isset(key){
ret = false;
array_example.forEach(function(entry) {
if( entry == key ){
ret = true;
}
});
return ret;
}
alert( isset("key_search") );
You can loop the array with a for loop and the object properties with for-in loops.
for (var i=0; i<result.length; i++)
for (var name in result[i]) {
console.log("Item name: "+name);
console.log("Source: "+result[i][name].sourceUuid);
console.log("Target: "+result[i][name].targetUuid);
}
To check if a folder exists or not, you can simply use the exists()
method:
// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )
// If it doesn't exist
if( !folder.exists() ) {
// Create all folders up-to and including B
folder.mkdirs()
}
// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
w << "Some text\n"
}
If you want first 2 letters and last 2 letters of a string then you can use the following code:
name = "India"
name[0:2]="In"
names[-2:]="ia"
span { display: table-cell; height: (your-height + px); vertical-align: middle; }
For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.
You need to do a while loop to get the result from the SQL query, like this:
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )
FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// If you want to display all results from the query at once:
print_r($row);
// If you want to display the results one by one
echo $row['column1'];
echo $row['column2']; // etc..
}
Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli
or PDO
extension. You can read more about that here.
For Angular 5+ Version we can use ngx-order-pipe package
Install package
$ npm install ngx-order-pipe --save
Import in apps module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { OrderModule } from 'ngx-order-pipe';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
OrderModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
use anywhere
<ul>
<li *ngFor="let item of (dummyData | orderBy:'name') ">
{{item.name}}
</li>
</ul>
An easy way to do this is using the pandas
library like this.
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name
The problem here was the skipinitialspace
which remove the spaces in the header. So ' star_name' becomes 'star_name'
<select name="forma" onchange="location = this.value;">
<option value="Home.php">Home</option>
<option value="Contact.php">Contact</option>
<option value="Sitemap.php">Sitemap</option>
</select>
UPDATE (Nov 2015): In this day and age if you want to have a drop menu there are plenty of arguably better ways to implement one. This answer is a direct answer to a direct question, but I don't advocate this method for public facing web sites.
UPDATE (May 2020): Someone asked in the comments why I wouldn't advocate this solution. I guess it's a question of semantics. I'd rather my users navigate using <a>
and kept <select>
for making form selections because HTML elements have semantic meeting and they have a purpose, anchors
take you places, <select>
are for picking things from lists.
Consider, if you are viewing a page with a non-traditional browser (a non graphical browser or screen reader or the page is accessed programmatically, or JavaScript is disabled) what then is the "meaning" or the "intent" of this <select>
you have used for navigation? It is saying "please pick a page name" and not a lot else, certainly nothing about navigating. The easy response to this is well i know that my users will be using IE or whatever so shrug
but this kinda misses the point of semantic importance.
Whereas a funky drop-down UI element made of suitable layout elements (and some js) containing some regular anchors still retains it intent even if the layout element is lost, "these are a bunch of links, select one and we will navigate there".
Here is an article on the misuse and abuse of <select>
.
You could just create an array of the correct size up-front and fill it:
frames = np.empty((480, 640, 3, 100))
for k in xrange(nframes):
frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))
if the frames were individual jpg file that were named in some particular way (in the example, frame_0.jpg, frame_1.jpg, etc).
Just a note, you might consider using a (nframes, 480,640,3)
shaped array, instead.
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.
FOR /d %%K in ("n:\test*") DO (
FOR /d %%J in ("%%K*") DO (
FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"
)
)
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged
This worked:
$("#theSelectId").prepend("<option value='' selected='selected'></option>");
Firebug Output:
<select id="theSelectId">
<option selected="selected" value=""/>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You could also use .prependTo
if you wanted to reverse the order:
?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????
To get the Color from Hex.
using System.Windows.Media;
Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
and then set the foreground
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color);
Probably, you need to insert schema identifier here:
in.addValue("po_system_users", null, OracleTypes.ARRAY, "your_schema.T_SYSTEM_USER_TAB");
This will only work for windows which are opened by using window.open(); method. Try this
var tmp=window.open(params);
tmp.close();
I was just searching for something similar:
I want to sum every odd row column.
SUMIF
has TWO possible ranges, the range to sum from, and a range to consider criteria in.
SUMIF(B1:B1000,1,A1:A1000)
This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.
To get "=1" to return in the B range I put this in B:
=MOD(ROWNUM(B1),2)
Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.
Easier than ARRAY stuff and hides the back-end of loops!
For 2019 ...
jQuery 3.4.0 is deprecating :first, :last, :eq, :even, :odd, :lt, :gt, and :nth. When we remove Sizzle, we’ll replace it with a small wrapper around querySelectorAll, and it would be almost impossible to reimplement these selectors without a larger selector engine.
We think this trade-off is worth it. Keep in mind we will still support the positional methods, such as .first, .last, and .eq. Anything you can do with positional selectors, you can do with positional methods instead. They perform better anyway.
https://blog.jquery.com/2019/04/10/jquery-3-4-0-released/
So you should be now be using .first()
, .last()
instead (or no jQuery).
You can use the NSThread
method:
[NSThread sleepForTimeInterval: delay];
However, if you do this on the main thread you'll block the app, so only do this on a background thread.
or in Swift
NSThread.sleepForTimeInterval(delay)
in Swift 3
Thread.sleep(forTimeInterval: delay)
Another alternative :
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> import json
Then with python2 :
>>> print json.dumps(mydict, indent=4, sort_keys=True) # python 2
{
"a": 1,
"b": 2,
"c": 3
}
or with python 3 :
>>> print(json.dumps(mydict, indent=4, sort_keys=True)) # python 3
{
"a": 1,
"b": 2,
"c": 3
}
If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).
test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
you never change the value of rng
so it always points to the initial cell
copy the Set rng = rng.Offset(1, 0)
to a new line before loop
also, your InStr
test will always fail
True
is -1, but the return from InStr
will be greater than 0 when the string is found. change the test to remove = True
new code:
Sub IfTest()
'This should split the information in a table up into cells
Dim Splitter() As String
Dim LenValue As Integer 'Gives the number of characters in date string
Dim LeftValue As Integer 'One less than the LenValue to drop the ")"
Dim rng As Range, cell As Range
Set rng = ActiveCell
Do While ActiveCell.Value <> Empty
If InStr(rng, "%") Then
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "% Change")
ActiveCell.Offset(0, 10).Select
ActiveCell.Value = Splitter(1)
ActiveCell.Offset(0, -1).Select
ActiveCell.Value = "% Change"
ActiveCell.Offset(1, -9).Select
Else
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "(")
ActiveCell.Offset(0, 9).Select
ActiveCell.Value = Splitter(0)
ActiveCell.Offset(0, 1).Select
LenValue = Len(Splitter(1))
LeftValue = LenValue - 1
ActiveCell.Value = Left(Splitter(1), LeftValue)
ActiveCell.Offset(1, -10).Select
End If
Set rng = rng.Offset(1, 0)
Loop
End Sub
I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477
Or you can read it there ==>
When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
This rings a bell. I came across a similar problem in the past,
You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.
Cheers, Tarun
Update 2016-07-08:
For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:
After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.
You can't because Nullable<DateTime>
is a different type to DateTime
.
You need to write your own function to do it,
public bool TryParse(string text, out Nullable<DateTime> nDate)
{
DateTime date;
bool isParsed = DateTime.TryParse(text, out date);
if (isParsed)
nDate = new Nullable<DateTime>(date);
else
nDate = new Nullable<DateTime>();
return isParsed;
}
Hope this helps :)
EDIT: Removed the (obviously) improperly tested extension method, because (as Pointed out by some bad hoor) extension methods that attempt to change the "this" parameter will not work with Value Types.
P.S. The Bad Hoor in question is an old friend :)
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
Either
or
Which one you use is up to you, depending how much performance and how much stability you need.
The developer of H2 has put up a nice performance evaluation:
http://www.h2database.com/html/performance.html
Try using the Intel X86 Atom Storage Image for a relatively faster boot up than using ARM based images when emulating the device.
Another thing to be taken into the notice is that according to your system configuration, running an Android emulator with 1.21 GB RAM can be a sluggish experience, because the emulator requires up to some certain percentage of RAM which is used for emulating the device, not forgetting about the RAM used by the ADT.
Try a system image of 2.1 - 2.3.3 for at least a runnable experience. Plus not forgetting about Save to Snapshot for quicker loading. Though the first load may take time. But saving to a snapshot definitely saves up some time.
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
VanillaJS is a term for library/framework free javascript.
Its sometimes ironically referred to as a library, as a joke for people who could be seen as mindlessly using different frameworks, especially jQuery.
Some people have gone so far to release this library, usually with an empty or comment-only js file.
Sometimes using row.getLastCellNum()
gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.
private int getLastFilledCellPosition(Row row) {
int columnIndex = -1;
for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
Cell cell = row.getCell(i);
if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
continue;
} else {
columnIndex = cell.getColumnIndex();
break;
}
}
return columnIndex;
}
you can also highlight the spaces (replacing the spaces with a block):
:%s/ /¦/g
(before writing undo it)
The code below removes remove grid lines from chart area only not the ones in x&y axis labels
Chart.defaults.scale.gridLines.drawOnChartArea = false;
Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .
the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .
using as a statement automatically calls the dispose on the specified object. The object must implement the IDisposable interface. It is possible to use several objects in one statement as long as they are of the same type.
The CLR converts your code into MSIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in IL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
In Python 3, the default encoding is "utf-8"
, so you can directly use:
b'hello'.decode()
which is equivalent to
b'hello'.decode(encoding="utf-8")
On the other hand, in Python 2, encoding defaults to the default string encoding. Thus, you should use:
b'hello'.decode(encoding)
where encoding
is the encoding you want.
Note: support for keyword arguments was added in Python 2.7.
You can find keyboard shortcuts from
File > Preferences > Keyboard Shortcuts
Default Keyboard Shortcuts are,
Copy Lines Down Action : shift+alt+down
Copy Lines Up Action : shift+alt+up
Move Lines Up Action : alt+up
Move Lines Down Action : alt+down
Or you can override the keyboard shortcuts from
File > Preferences > Keyboard Shortcuts
And editing the keybindings.json
Example:
[
{
"key": "ctrl+d",
"command": "editor.action.copyLinesDownAction",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+up",
"command": "editor.action.moveLinesUpAction",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+down",
"command": "editor.action.moveLinesDownAction",
"when": "editorTextFocus"
}
]
The most voted answer has got already defined [String] function body. I was looking for the solution to rename already declared function's name and finally after an hour of struggling I've dealt with it. It:
.toString()
methodfunction
and (
new Function()
constructorfunction nameAppender(name,fun){_x000D_
const reg = /^(function)(?:\s*|\s+([A-Za-z0-9_$]+)\s*)(\()/;_x000D_
return (new Function(`return ${fun.toString().replace(reg,`$1 ${name}$3`)}`))();_x000D_
}_x000D_
_x000D_
//WORK FOR ALREADY NAMED FUNCTIONS:_x000D_
function hello(name){_x000D_
console.log('hello ' + name);_x000D_
}_x000D_
_x000D_
//rename the 'hello' function_x000D_
var greeting = nameAppender('Greeting', hello); _x000D_
_x000D_
console.log(greeting); //function Greeting(name){...}_x000D_
_x000D_
_x000D_
//WORK FOR ANONYMOUS FUNCTIONS:_x000D_
//give the name for the anonymous function_x000D_
var count = nameAppender('Count',function(x,y){ _x000D_
this.x = x;_x000D_
this.y = y;_x000D_
this.area = x*y;_x000D_
}); _x000D_
_x000D_
console.log(count); //function Count(x,y){...}
_x000D_
If your constraint is on a user type, then don't forget to see if there is a Default Constraint
, usually something like DF__TableName__ColumnName__6BAEFA67
, if so then you will need to drop the Default Constraint
, like this:
ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]
For more info see the comments by the brilliant Aaron Bertrand on this answer.
import re
result=[x for x in re.split(',| ',your_string) if x!='']
this works fine for me.
You could use ResolverUtil (raw source) from the Stripes Framework
if you need something simple and quick without refactoring any existing code.
Here's a simple example not having loaded any of the classes:
package test;
import java.util.Set;
import net.sourceforge.stripes.util.ResolverUtil;
public class BaseClassTest {
public static void main(String[] args) throws Exception {
ResolverUtil<Animal> resolver = new ResolverUtil<Animal>();
resolver.findImplementations(Animal.class, "test");
Set<Class<? extends Animal>> classes = resolver.getClasses();
for (Class<? extends Animal> clazz : classes) {
System.out.println(clazz);
}
}
}
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
class Donkey extends Animal {}
This also works in an application server as well since that's where it was designed to work ;)
The code basically does the following:
ClassLoader#loadClass(String fullyQualifiedName)
Animal.class.isAssignableFrom(loadedClass);
In the case of no repeats and no order, the following EqualityComparer can be used to allow collections as dictionary keys:
public class SetComparer<T> : IEqualityComparer<IEnumerable<T>>
where T:IComparable<T>
{
public bool Equals(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == second)
return true;
if ((first == null) || (second == null))
return false;
return first.ToHashSet().SetEquals(second);
}
public int GetHashCode(IEnumerable<T> enumerable)
{
int hash = 17;
foreach (T val in enumerable.OrderBy(x => x))
hash = hash * 23 + val.GetHashCode();
return hash;
}
}
Here is the ToHashSet() implementation I used. The hash code algorithm comes from Effective Java (by way of Jon Skeet).
The easiest way is to turn the int into a string and take each character of the string as an element of your list:
>>> n = 43365644
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits) # use the extends method if you want to add the list to another
It involves a casting operation, but it's readable and acceptable if you don't need extreme performance.
In nutshell: CANDIDATE KEY is a minimal SUPER KEY.
Where Super key is the combination of columns(or attributes) that uniquely identify any record(or tuple) in a relation(table) in RDBMS.
For instance, consider the following dependencies in a table having columns A, B, C, and D (Giving this table just for a quick example so not covering all dependencies that R could have).
Attribute set (Determinant)---Can Identify--->(Dependent)
A-----> AD
B-----> ABCD
C-----> CD
AC----->ACD
AB----->ABCD
ABC----->ABCD
BCD----->ABCD
Now, B, AB, ABC, BCD identifies all columns so those four qualify for the super key.
But, B?AB; B?ABC; B?BCD hence AB, ABC, and BCD disqualified for CANDIDATE KEY as their subsets could identify the relation, so they aren't minimal and hence only B is the candidate key, not the others.
One more thing Primary key is any one among the candidate keys.
Thanks for asking
The only way to reliably detect if a socket is still connected is to periodically try to send data. Its usually more convenient to define an application level 'ping' packet that the clients ignore, but if the protocol is already specced out without such a capability you should be able to configure tcp sockets to do this by setting the SO_KEEPALIVE socket option. I've linked to the winsock documentation, but the same functionality should be available on all BSD-like socket stacks.
I most cases, creating a temporary file named after your variable name might be acceptable. (as you are probably using meaningful variables name...)
Here, my variable name is SSH_PAGEANT_AUTH_SOCK
dir /w "\\.\pipe\\"|find "pageant" > %temp%\SSH_PAGEANT_AUTH_SOCK && set /P SSH_PAGEANT_AUTH_SOCK=<%temp%\SSH_PAGEANT_AUTH_SOCK
Old question I know. You don't need to convert it. See this function:
function getType( oObj )
{
if( typeof oObj === "object" )
{
return ( oObj === null )?'Null':
// Check if it is an alien object, for example created as {world:'hello'}
( typeof oObj.constructor !== "function" )?'Object':
// else return object name (string)
oObj.constructor.name;
}
// Test simple types (not constructed types)
return ( typeof oObj === "boolean")?'Boolean':
( typeof oObj === "number")?'Number':
( typeof oObj === "string")?'String':
( typeof oObj === "function")?'Function':false;
};
Examples:
function MyObject() {}; // Just for example
console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() ); // Function
console.log( getType( {} )); // Object
console.log( getType( [] )); // Array
console.log( getType( new MyObject() )); // MyObject
var bTest = false,
uAny, // Is undefined
fTest function() {};
// Non constructed standard types
console.log( getType( bTest )); // Boolean
console.log( getType( 1.00 )); // Number
console.log( getType( 2000 )); // Number
console.log( getType( 'hello' )); // String
console.log( getType( "hello" )); // String
console.log( getType( fTest )); // Function
console.log( getType( uAny )); // false, cannot produce
// a string
Low cost and simple.
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
Assuming I am understanding your question and setup correctly,
If you're trying to use the build number in your script, you have two options:
1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}
2) Change your script so that:
<property environment="env" />
<property name="build_parameter" value="${env.BUILD_NUMBER}"/>
You must set the settings in the file 'Startup.cs'
You also have to define it in the default values of JsonConvert, this is if you later want to directly use the library to serialize an object.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
let count=0;_x000D_
let text = document.getElementById('heading');_x000D_
let btn = document.getElementById('btn');_x000D_
btn.addEventListener('click', function(){_x000D_
if(count%2==0){_x000D_
text.style.opacity="0.1";_x000D_
unfade(text);_x000D_
text.innerText="Welcome to Javascript </>"; _x000D_
text.style.color="forestgreen";_x000D_
}//end of if_x000D_
else{ text.style.opacity="0.1";_x000D_
unfade(text);_x000D_
text.innerText="Hello javascript"; _x000D_
text.style.color="blueviolet";_x000D_
}//end of else_x000D_
count++;//for toggling the text_x000D_
});_x000D_
//function for fade effect--------_x000D_
function unfade(element) {_x000D_
var op = 0.1; // initial opacity_x000D_
element.style.display = 'block';_x000D_
var timer = setInterval(function () {_x000D_
if (op >= 1){_x000D_
clearInterval(timer);_x000D_
}_x000D_
element.style.opacity = op;_x000D_
element.style.filter = 'alpha(opacity=' + op * 100 + ")";_x000D_
op += op * 0.1;_x000D_
}, 30);_x000D_
}
_x000D_
<h1 style="color:blueviolet" id="heading">Hello javascript</h1>_x000D_
<button id="btn">Click me</button>
_x000D_
It's simple if you already have Homebrew: Assuming you have homebrew installed, type the following:
brew install git
This should automatically install git and set it in your path, replacing the Apple one. Quit and restart terminal. Check git version to confirm.
git --version
If the output of the above command shows the latest version and does not mention Apple with the version details, then you are all set.
If however you still see apple version, then type the following two lines, which will manually set our path to the local git distro instead of the Apple one.
export PATH=/usr/local/bin:$PATH
git --version
IF YOU DON'T HAVE HOMEBREW, FOLLOW THESE STEPS
Check version
$ git --version
Backup (or remove) Apple git (Optional)
$ sudo mv /usr/bin/git /usr/bin/git-apple
Install Homebrew if you didn’t have
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Or update if you already have
$ brew update && brew upgrade
Install Git with Homebrew
$ brew install git
Symbolic link
$ brew link --force git
Quit terminal and open a new terminal, then check version.
$ git --version
You should see…
git version <latest version>
Nice! We’re safe now! And next time you can just…
$ brew update && brew upgrade
I had the same problem. The problem sit in the Excel Source task. When you setup this task the first time, the task will connect to the specified Excel file (via the Excel connection) and decide what type each column is based on the current spreadsheet.
Thus, if you set up the Excel Source task, just make sure that the columns that should be text only has text in the column. This means that the Excel Source task will always assume that any subsequent spreadsheets will have the same format and will read 12345 as text because the column was text when the task was set up.
Hope it makes sense!
I'm not sure if this is bad practice or no, but my team and I have been using a mixed html, JS, and php solution. We start with the PHP string we want to pull into a JS variable, lets call it:
$someString
Next we use in-page hidden form elements, and have their value set as the string:
<form id="pagePhpVars" method="post">
<input type="hidden" name="phpString1" id="phpString1" value="'.$someString.'" />
</form>
Then its a simple matter of defining a JS var through document.getElementById:
<script type="text/javascript" charset="UTF-8">
var moonUnitAlpha = document.getElementById('phpString1').value;
</script>
Now you can use the JS variable "moonUnitAlpha" anywhere you want to grab that PHP string value. This seems to work really well for us. We'll see if it holds up to heavy use.
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Instead of using position:relative
in #icons
, you could just take that away and maybe add a z-index or something so the picture won't get covered up. Hope this helps.
Well my client side (a cshtml file) was using DataTables to display a grid (now using Infragistics control which are great). And once the user clicked on the row, I captured the row event and the date associated with that record in order to go back to the server and make additional server-side requests for trades, etc. And no - I DID NOT stringify it...
The DataTables def started as this (leaving lots of stuff out), and the click event is seen below where I PUSH onto my Json object :
oTablePf = $('#pftable').dataTable({ // INIT CODE
"aaData": PfJsonData,
'aoColumnDefs': [
{ "sTitle": "Pf Id", "aTargets": [0] },
{ "sClass": "**td_nodedate**", "aTargets": [3] }
]
});
$("#pftable").delegate("tbody tr", "click", function (event) { // ROW CLICK EVT!!
var rownum = $(this).index();
var thisPfId = $(this).find('.td_pfid').text(); // Find Port Id and Node Date
var thisDate = $(this).find('.td_nodedate').text();
//INIT JSON DATA
var nodeDatesJson = {
"nodedatelist":[]
};
// omitting some code here...
var dateArry = thisDate.split("/");
var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1];
nodeDatesJson.nodedatelist.push({ nodedate: nodeDate });
getTradeContribs(thisPfId, nodeDatesJson); // GET TRADE CONTRIBUTIONS
});
You can insert using a Sub-query as follows:
INSERT INTO new_table (columns....)
SELECT columns....
FROM initial_table where column=value
For some weird reason "Java SE Development Kit 8u151" gives this trouble. Just install, "Java SE Development Kit 8u152" from the following link-
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
It should work then.
Have no fear, because a brave group of Ops Programmers have solved the situation with a brand spanking new nginx_tcp_proxy_module
Written in August 2012, so if you are from the future you should do your homework.
Assumes you are using CentOS:
init.d/nginx
script)yum install pcre pcre-devel openssl openssl-devel
and any other necessary libs for building NGINXAgain, assumes CentOS:
cd /usr/local/
wget 'http://nginx.org/download/nginx-1.2.1.tar.gz'
tar -xzvf nginx-1.2.1.tar.gz
cd nginx-1.2.1/
patch -p1 < /path/to/nginx_tcp_proxy_module/tcp.patch
./configure --add-module=/path/to/nginx_tcp_proxy_module --with-http_ssl_module
(you can add more modules if you need them)make
make install
Optional:
sudo /sbin/chkconfig nginx on
Remember to copy over your old configuration files first if you want to re-use them.
Important: you will need to create a tcp {}
directive at the highest level in your conf. Make sure it is not inside your http {}
directive.
The example config below shows a single upstream websocket server, and two proxies for both SSL and Non-SSL.
tcp {
upstream websockets {
## webbit websocket server in background
server 127.0.0.1:5501;
## server 127.0.0.1:5502; ## add another server if you like!
check interval=3000 rise=2 fall=5 timeout=1000;
}
server {
server_name _;
listen 7070;
timeout 43200000;
websocket_connect_timeout 43200000;
proxy_connect_timeout 43200000;
so_keepalive on;
tcp_nodelay on;
websocket_pass websockets;
websocket_buffer 1k;
}
server {
server_name _;
listen 7080;
ssl on;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.key;
timeout 43200000;
websocket_connect_timeout 43200000;
proxy_connect_timeout 43200000;
so_keepalive on;
tcp_nodelay on;
websocket_pass websockets;
websocket_buffer 1k;
}
}
I had this error when I had specified fromGroupName instead of formArrayName.
Make sure you correctly specify if it is a form array or form group.
<div formGroupName="formInfo"/>
<div formArrayName="formInfo"/>
-L is the test for file exists and is also a symbolic link
If you do not want to test for the file being a symbolic link, but just test to see if it exists regardless of type (file, directory, socket etc) then use -e
So if file is really file and not just a symbolic link you can do all these tests and get an exit status whose value indicates the error condition.
if [ ! \( -e "${file}" \) ]
then
echo "%ERROR: file ${file} does not exist!" >&2
exit 1
elif [ ! \( -f "${file}" \) ]
then
echo "%ERROR: ${file} is not a file!" >&2
exit 2
elif [ ! \( -r "${file}" \) ]
then
echo "%ERROR: file ${file} is not readable!" >&2
exit 3
elif [ ! \( -s "${file}" \) ]
then
echo "%ERROR: file ${file} is empty!" >&2
exit 4
fi
Download last version (not 2.5.1 or other old ones) from jmeter.apache.org
Unzip file
Ensure you install a version of JAVA which is compatible, Java 6 or 7 for JMeter 2.11
In bin folder click on jmeter.sh not on jar or execute sh ./apache-jmeter-x.x.x/bin/jmeter
in the terminal.
x.x.x is the version you use.
Finally, when started you may want to select System Look and feel for Mac OSX better integration. Menu > Options > Look and Feel > System
You can also post runnable using the view from any other thread. But be sure that the view is not null:
tView.post(new Runnable() {
@Override
public void run() {
tView.setText("Success");
}
});
According to the Documentation:
"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."
Ruby provides a built-in function for checking the length of a string. Say it's called s
:
if s.length <= 25
# We're OK
else
# Too long
end
also check this out, for example we wanna count t
echo "test" | awk -v RS='t' 'END{print NR-1}'
or in python
python -c 'print "this is for test".count("t")'
or even better, we can make our script dynamic with awk
echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""
in this case output is like this :
e 1
s 1
t 2
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:
comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;
or:
comm.Parameters.AddWithValue("@person", Myname);
That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.
Hope this helps.
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
You MUST override the "stop()" method in your Application instance to make it works. If you have overridden even empty "stop()" then the application shuts down gracefully after the last stage is closed (actually the last stage must be the primary stage to make it works completely as in supposed to be). No any additional Platform.exit or setOnCloseRequest calls are need in such case.
About the .dex File :
One of the most remarkable features of the Dalvik Virtual Machine
(the workhorse under the Android system) is that it does not use Java bytecode. Instead, a homegrown format called DEX was introduced and not even the bytecode instructions are the same as Java bytecode instructions.
Compiled Android application code file.
Android programs are compiled into .dex
(Dalvik Executable) files, which are in turn zipped into a single .apk
file on the device. .dex
files can be created by automatically translating compiled applications written in the Java programming language.
Dex file format:
1. File Header
2. String Table
3. Class List
4. Field Table
5. Method Table
6. Class Definition Table
7. Field List
8. Method List
9. Code Header
10. Local Variable List
Android has documentation on the Dalvik Executable Format
(.dex files). You can find out more over at the official docs: Dex File Format
.dex
files are similar to java class files, but they were run under the Dalkvik Virtual Machine (DVM) on older Android versions, and compiled at install time on the device to native code with ART on newer Android versions.
You can decompile
.dex using the dexdump
tool which is provided in android-sdk.
There are also some Reverse Engineering Techniques to make a jar file
or java class file
from a .dex
file.
.section {
display: flex;
}
.element-left {
width: 94%;
}
.element-right {
flex-grow: 1;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
or
.section {
display: flex;
flex-wrap: wrap;
}
.element-left {
flex: 2;
}
.element-right {
width: 100px;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
This kind of error can be caused by LF vs CRLF line ending mismatches, e.g. when you're looking at the patch file and you're absolutely sure it should be able to apply, but it just won't.
To test this out, if you have a patch that applies to just one file, you can try running 'unix2dos' or 'dos2unix' on just that file (try both, to see which one causes the file to change; you can get these utilities for Windows as well as Unix), then commit that change as a test commit, then try applying the patch again. If that works, that was the problem.
NB git am
applies patches as LF by default (even if the patch file contains CRLF), so if you want to apply CRLF patches to CRLF files you must use git am --keep-cr
, as per this answer.
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
create or replace procedure mili(num in number)
as
yr number;
yrsms number;
mon number;
monsms number;
wk number;
wksms number;
dy number;
dysms number;
hr number;
hrsms number;
mn number;
mnsms number;
sec number;
begin
yr := FLOOR(num/31556952000);
yrsms := mod(num, 31556952000);
mon := FLOOR(yrsms/2629746000);
monsms := mod(num,2629746000);
wk := FLOOR(monsms/(604800000));
wksms := mod(num,604800000);
dy := floor(wksms/ (24*60*60*1000));
dysms :=mod(num,24*60*60*1000);
hr := floor((dysms)/(60*60*1000));
hrsms := mod(num,60*60*1000);
mn := floor((hrsms)/(60*1000));
mnsms := mod(num,60*1000);
sec := floor((mnsms)/(1000));
dbms_output.put_line(' Year:'||yr||' Month:'||mon||' Week:'||wk||' Day:'||dy||' Hour:'||hr||' Min:'||mn||' Sec: '||sec);
end;
/
begin
mili(12345678904234);
end;
public static ArrayList<String> getTablesList(Connection conn)
throws SQLException {
ArrayList<String> listofTable = new ArrayList<String>();
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
if (rs.getString(4).equalsIgnoreCase("TABLE")) {
listofTable.add(rs.getString(3));
}
}
return listofTable;
}
For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,
once with for each Dkey in dDict,
and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)
=>You will notice a huge difference, even though you are going through the same construct.
OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.
Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.
But the real cause of your problem is that you are using when
on two different objects, before you complete the stubbing. When you call when
, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn
part. Each call to when
must be followed by one and only one call to thenReturn
, before you do any more calls to when
. You made two calls to when
without calling thenReturn
- that's your error.
SequenceEqual can be faster. Namely in the case where almost all of the time, both arrays have indeed the same length and are not the same object.
It's still not the same functionality as the OP's function, as it won't silently compare null values.
If you are using jQuery UI you have translations for common key codes. In ui/ui/ui.core.js:
$.ui.keyCode = {
...
ENTER: 13,
...
};
There's also some translations in tests/simulate/jquery.simulate.js but I could not find any in the core JS library. Mind you, I merely grep'ed the sources. Maybe there is some other way to get rid of these magic numbers.
You can also make use of String.charCodeAt and .fromCharCode:
>>> String.charCodeAt('\r') == 13
true
>>> String.fromCharCode(13) == '\r'
true
This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe(){
console.log(abc); // it is available here too!
}
...
};
This technique relies on using a closure. But it doesn't work with this
because this
is a pseudo variable that may change from scope to scope dynamically:
// we want to use "this" variable in embedded functions
function xyz(){
// "this" is different here!
console.log(this); // not what we wanted!
function qwe(){
// "this" is different here too!
console.log(this); // not what we wanted!
}
...
};
What can we do? Assign it to some variable and use it through the alias:
var abc = this; // we want to use this variable in embedded functions
function xyz(){
// "this" is different here! --- but we don't care!
console.log(abc); // now it is the right object!
function qwe(){
// "this" is different here too! --- but we don't care!
console.log(abc); // it is the right object here too!
}
...
};
this
is not unique in this respect: arguments
is the other pseudo variable that should be treated the same way — by aliasing.
Why are you combining GET and POST? Use one or the other.
$.ajax({
type: 'post',
data: {
timestamp: timestamp,
uid: uid
...
}
});
php:
$uid =$_POST['uid'];
Or, just format your request properly (you're missing the ampersands for the get parameters).
url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,
You cannot display a lot of websites inside an iFrame. Reason being that they send an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page. This is a security feature to prevent click-jacking. Some details at How to show google.com in an iframe?
This could be of some help : https://www.maketecheasier.com/create-survey-form-with-google-docs/
I concur with Seba, I tried to set my alternating row color in the rowForIndexPath delegate method but was getting inconsistent results between 3.2 and 4.2. The following worked great for me.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ((indexPath.row % 2) == 1) {
cell.backgroundColor = UIColorFromRGB(0xEDEDED);
cell.textLabel.backgroundColor = UIColorFromRGB(0xEDEDED);
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
else
{
cell.backgroundColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
}
Format(Fields!CUL1.Value, "0.00")
would work better since @abe
suggests they want to show 0.00
, and if the value was 0, "#0.##"
would show "0"
.
It sounds like your workbook got set to Manual Calculation. You can change this to Automatic by going to Formulas > Calculation > Calculation Options > Automatic.
Manual calculation can be useful to reduce computational load and improve responsiveness in workbooks with large amounts of formulas. The idea is that you can look at data and make changes, then choose when you want to make your computer go through the effort of calculation.
Qt works very well with graphics. In my opinion it is more versatile than PIL.
You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, QPainter
.
To use Qt you need a Python binding for it: PySide or PyQt4.
They both support Python 3.
Here is a simple example that loads a JPG image, draws an antialiased circle of radius 10 at coordinates (20, 20) with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:
from PySide.QtCore import *
from PySide.QtGui import *
app = QCoreApplication([])
img = QImage('input.jpg')
g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()
img.save('output.png')
But please note that this solution is quite 'heavyweight', because Qt is a large framework for making GUI applications.
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
I wanted a one-time solution:
ssh -o ServerAliveInterval=60 [email protected]
Stored it in an alias:
alias sshprod='ssh -v -o ServerAliveInterval=60 [email protected]'
Now can connect like this:
me@MyMachine:~$ sshprod
There are more api-friendly libraries than Net::HTTP
, for example httparty:
require "httparty"
File.open("/tmp/my_file.flv", "wb") do |f|
f.write HTTParty.get("http://somedomain.net/flv/sample/sample.flv").parsed_response
end
I was able to convert using below method for my WebAPI:
[HttpPost]
public HttpResponseMessage Post(dynamic item) // Passing parameter as dynamic
{
JArray itemArray = item["Region"]; // You need to add JSON.NET library
JObject obj = itemArray[0] as JObject; // Converting from JArray to JObject
Region objRegion = obj.ToObject<Region>(); // Converting to Region object
}
Use the S_ISDIR
macro:
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
Late answer, I know, but for me the following script is quite useful - and it answers the question too, hitting two flys with one flag ;-)
The following script expands SendTo in the file explorer's context menu:
@echo off
cls
if "%~dp1"=="" goto Install
REM change drive, then cd to path given and run shell there
%~d1
cd "%~dp1"
cmd /k
goto End
:Install
rem No arguments: Copies itself into SendTo folder
copy "%0" "%appdata%\Microsoft\Windows\SendTo\A - Open in CMD shell.cmd"
:End
If you run this script without any parameters by double-clicking on it, it will copy itself to the SendTo folder and renaming it to "A - Open in CMD shell.cmd". Afterwards it is available in the "SentTo" context menu.
Then, right-click on any file or folder in Windows explorer and select "SendTo > A - Open in CMD shell.cmd"
The script will change drive and path to the path containing the file or folder you have selected and open a command shell with that path - useful for Visual Studio Code, because then you can just type "code ." to run it in the context of your project.
How does it work?
%0
- full path of the batch script
%~d1
- the drive contained in the first argument (e.g. "C:")
%~dp1
- the path contained in the first argument
cmd /k
- opens a command shell which stays open
Not used here, but %~n1
is the file name of the first argument.
I hope this is helpful for someone.
On RHEL systems, the /etc/rc.d/init.d/functions
script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.
The specific function provided to help with this is daemon
. If you are intending to use it to start a daemon-like program, a simple usage would be:
daemon --user=username command
If that is too heavy-handed for what you need, there is runuser
(see man runuser
for full info; some versions may need -u
prior to the username):
/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"
import sys
expanded version
sys.version_info
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)
specific
maj_ver = sys.version_info.major
repr(maj_ver)
'3'
or
print(sys.version_info.major)
'3'
or
version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'
In your trigger, you have two pseudo-tables available, Inserted
and Deleted
, which contain those values.
In the case of an UPDATE, the Deleted
table will contain the old values, while the Inserted
table contains the new values.
So if you want to log the ID, OldValue, NewValue
in your trigger, you'd need to write something like:
CREATE TRIGGER trgEmployeeUpdate
ON dbo.Employees AFTER UPDATE
AS
INSERT INTO dbo.LogTable(ID, OldValue, NewValue)
SELECT i.ID, d.Name, i.Name
FROM Inserted i
INNER JOIN Deleted d ON i.ID = d.ID
Basically, you join the Inserted
and Deleted
pseudo-tables, grab the ID (which is the same, I presume, in both cases), the old value from the Deleted
table, the new value from the Inserted
table, and you store everything in the LogTable
As addition to other answers, one can write something else if variable is None like this:
{{ variable or '' }}
Can't get much simpler than this :)
ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
# your file exists
fi
As suggested by dimo414, this can be collapsed to:
if ssh host "test -e /path/to/file"; then
# your file exists
fi
So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.
The basic idea is to signal the reader to split on the carriage character "\n"
(or "\r\n"
for Windows). Python can do this with the file.readline()
function.
import json
def json_reader(filename):
with open(filename) as f:
for line in f:
yield json.loads(line)
However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.
def json_writer(file, json_objects):
with open(file, "w") as f:
for jsonobj in json_objects:
jsonstr = json.dumps(jsonobj)
f.write(jsonstr + "\n")
You could also do the same operation with file.writelines()
and a list comprehension:
...
json_strs = [json.dumps(j) + "\n" for j in json_objects]
f.writelines(json_strs)
...
And if you wanted to append the data instead of writing a new file just change open(file, "w")
to open(file, "a")
.
In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.
On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write
lst = list(json_reader(file))
I can't reproduce your issue running El Cap + Homebrew 1.0.x
Upgrade to Homebrew 1.0.x, which was released late in September. Specific changes were made in the way openssl is linked. The project is on a more robust release schedule now that it's hit 1.0.
brew uninstall openssl
brew update && brew upgrade && brew cleanup && brew doctor
You should fix any issues raised by brew doctor
before proceeding.
brew install openssl
Note: Upgrading homebrew will update all your installed packages to their latest versions.
On windows, you can print with this command in your CLI
C:\Users\dir\env | more
You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.
Just use matrix
:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
This happens when you pull and all files were executable in the remote repository. Making them executable again will set everything back to normal again.
chmod +x <yourfile> //For one file
chmod +x folder/* // For files in a folder
You might need to do:
chmod -x <file> // Removes execute bit
instead, for files that was not set as executable and that was changed because of the above operation. There is a better way to do this but this is just a very quick and dirty fix.
Using Nick's sample above, you can create a constructor for objects without parameters using a return statement as the last statement in your object definition. Return your constructor function as below and it will run the code in __construct each time you create the object:
function Box()
{
var __construct = function() {
alert("Object Created.");
this.color = 'green';
}
this.color = '';
this.getColor = function() {
return this.color;
}
__construct();
}
var b = new Box();
In one word: no. The only way to stretch an image is with the <img>
tag. You'll have to be creative.
This used to be true in 2008, when the answer was written. Today modern browsers support background-size
which solves this problem. Beware that IE8 doesn't support it.
[function.fopen]: failed to open stream
If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :
allow_url_fopen = off
should bee this
allow_url_fopen = On
And add this line below it:
allow_url_include = off
should bee this
allow_url_include = on
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
>>> def delete_key(dict, key):
... del dict[key]
... return dict
...
>>> test_dict = {'one': 1, 'two' : 2}
>>> print delete_key(test_dict, 'two')
{'one': 1}
>>>
this doesn't do any error handling, it assumes the key is in the dict, you might want to check that first and raise
if its not
application/vnd.ms-excel
vnd class
/ vendor specificSimple and effective alternative:
public class ClassName
{
public List<dynamic> MyProperty { get; set; }
}
or
public class ClassName
{
public List<object> MyProperty { get; set; }
}
For differences see this post: List<Object> vs List<dynamic>
The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.
function start(){
document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
}
function addActivityItem(){
//option is selected
alert("yeah");
}
window.addEventListener("load", start, false);
1) Put https://api-server.com/API/index.php/member/signin
in the url input box and choose POST
from the dropdown
2) In Headers tab, enter:
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
3) In Body tab, select the raw
radio button and write:
{"description":"","phone":"","lastname":"","app_version":"2.6.2","firstname":"","password":"my_pass","city":"","apikey":"213","lang":"fr","platform":"1","email":"[email protected]","pseudo":"example"}
select form-data
radio button and write:
key = name Value = userfile Select Text
key = filename Select File
and upload your profil.jpg
Alternative to explicit if
statement
Minimally:
test $? -eq 0 || echo "something bad happened"
Complete:
EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened";
exit $EXITCODE
The following is a very easy way to see the maximum elements and its positions. Here axis
is the domain; axis
= 0 means column wise maximum number and axis
= 1 means row wise max number for the 2D case. And for higher dimensions it depends upon you.
M = np.random.random((3, 4))
print(M)
print(M.max(axis=1), M.argmax(axis=1))
The NULLIF function will convert any column value with only whitespace into a NULL value. Works for T-SQL and SQL Server 2008 & up.
SELECT [column_name]
FROM [table_name]
WHERE NULLIF([column_name], '') IS NULL
A little late to the party, but hopefully this will help someone.
In C arrays always allocate memory on the stack, thus a function can't return a (non-static) array due to the fact that memory allocated on the stack gets freed automatically when the execution reaches the end of the current block. That's really annoying when you want to deal with two-dimensional arrays (i.e. matrices) and implement a few functions that can alter and return matrices. To achieve this, you could use a pointer-to-pointer to implement a matrix with dynamically allocated memory:
/* Initializes a matrix */
double** init_matrix(int num_rows, int num_cols){
// Allocate memory for num_rows float-pointers
double** A = calloc(num_rows, sizeof(double*));
// return NULL if the memory couldn't allocated
if(A == NULL) return NULL;
// For each double-pointer (row) allocate memory for num_cols floats
for(int i = 0; i < num_rows; i++){
A[i] = calloc(num_cols, sizeof(double));
// return NULL if the memory couldn't allocated
// and free the already allocated memory
if(A[i] == NULL){
for(int j = 0; j < i; j++){
free(A[j]);
}
free(A);
return NULL;
}
}
return A;
}
Here's an illustration:
double** double* double
------------- ---------------------------------------------------------
A ------> | A[0] | ----> | A[0][0] | A[0][1] | A[0][2] | ........ | A[0][cols-1] |
| --------- | ---------------------------------------------------------
| A[1] | ----> | A[1][0] | A[1][1] | A[1][2] | ........ | A[1][cols-1] |
| --------- | ---------------------------------------------------------
| . | .
| . | .
| . | .
| --------- | ---------------------------------------------------------
| A[i] | ----> | A[i][0] | A[i][1] | A[i][2] | ........ | A[i][cols-1] |
| --------- | ---------------------------------------------------------
| . | .
| . | .
| . | .
| --------- | ---------------------------------------------------------
| A[rows-1] | ----> | A[rows-1][0] | A[rows-1][1] | ... | A[rows-1][cols-1] |
------------- ---------------------------------------------------------
The double-pointer-to-double-pointer A
points to the first element A[0]
of a
memory block whose elements are double-pointers itself. You can imagine these
double-pointers as the rows of the matrix. That's the reason why every
double-pointer allocates memory for num_cols elements of type double.
Furthermore A[i]
points to the i-th row, i.e. A[i]
points to A[i][0]
and
that's just the first double-element of the memory block for the i-th row.
Finally, you can access the element in the i-th row
and j-th column easily with A[i][j]
.
Here's a complete example that demonstrates the usage:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Initializes a matrix */
double** init_matrix(int num_rows, int num_cols){
// Allocate memory for num_rows double-pointers
double** matrix = calloc(num_rows, sizeof(double*));
// return NULL if the memory couldn't allocated
if(matrix == NULL) return NULL;
// For each double-pointer (row) allocate memory for num_cols
// doubles
for(int i = 0; i < num_rows; i++){
matrix[i] = calloc(num_cols, sizeof(double));
// return NULL if the memory couldn't allocated
// and free the already allocated memory
if(matrix[i] == NULL){
for(int j = 0; j < i; j++){
free(matrix[j]);
}
free(matrix);
return NULL;
}
}
return matrix;
}
/* Fills the matrix with random double-numbers between -1 and 1 */
void randn_fill_matrix(double** matrix, int rows, int cols){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
matrix[i][j] = (double) rand()/RAND_MAX*2.0-1.0;
}
}
}
/* Frees the memory allocated by the matrix */
void free_matrix(double** matrix, int rows, int cols){
for(int i = 0; i < rows; i++){
free(matrix[i]);
}
free(matrix);
}
/* Outputs the matrix to the console */
void print_matrix(double** matrix, int rows, int cols){
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
printf(" %- f ", matrix[i][j]);
}
printf("\n");
}
}
int main(){
srand(time(NULL));
int m = 3, n = 3;
double** A = init_matrix(m, n);
randn_fill_matrix(A, m, n);
print_matrix(A, m, n);
free_matrix(A, m, n);
return 0;
}
Try the following:
DateTime dtStart;
DateTime dtEnd;
if (DateTime.TryParse( tb1.Text, out dtStart ) && DateTime.TryParse(tb2.Text, out dtEnd ))
{
TimeSpan ts = dtStart - dtEnd;
double difference = ts.TotalMilliseconds;
}
Change the plugin to no longer apply the style. That would be much better than removing the style there-after.
I always using tutorial from this article to center things. It's great
div.container3 {
height: 10em;
position: relative } /* 1 */
div.container3 p {
margin: 0;
position: absolute; /* 2 */
top: 50%; /* 3 */
transform: translate(0, -50%) } /* 4 */
The essential rules are:
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
Maybe you can try the followings $indent -kr -i8 *.c
Hope it's useful for you!
Try this:
<meta http-equiv="refresh" content="5;URL= your url">
or
<meta http-equiv="refresh" content="5">
<div>
<input type="checkbox">
<img src="/image.png" />
</div>
input[type="checkbox"]
{
margin-top: -50%;
vertical-align: middle;
}
That's a great example. When ¤t
is parsed into a text node it is converted to ¤t
. When parsed into an attribute value, it is parsed as ¤t
.
If you want ¤t
in a text node, you should write &current
in your markup.
The gory details are in the HTML5 parsing spec - Named Character Reference State
I've taken Anas Nakawa's idea and improved it. First of all, there is no reason to actually run the function being declared. We want to know whether it parses correctly, not whether the code works. Second, a literal object is a better context for our purpose than var XXX
as it's harder to break out of.
function isValidVarName( name ) {
try {
return name.indexOf('}') === -1 && eval('(function() { a = {' + name + ':1}; a.' + name + '; var ' + name + '; }); true');
} catch( e ) {
return false;
}
return true;
}
// so we can see the test code
var _eval = eval;
window.eval = function(s) {
console.log(s);
return _eval(s);
}
console.log(isValidVarName('name'));
console.log(isValidVarName('$name'));
console.log(isValidVarName('not a name'));
console.log(isValidVarName('a:2,b'));
console.log(isValidVarName('"a string"'));
console.log(isValidVarName('xss = alert("I\'m in your vars executin mah scrip\'s");;;;;'));
console.log(isValidVarName('_;;;'));
console.log(isValidVarName('_=location="#!?"'));
console.log(isValidVarName('?'));
console.log(isValidVarName('HELLO'));
console.log(isValidVarName('????'));
console.log(isValidVarName('?????????????'));
console.log(isValidVarName('KingGeorge?'));
console.log(isValidVarName('}; }); alert("I\'m in your vars executin\' mah scripts"); true; // yeah, super valid'));
console.log(isValidVarName('if'));
If I understand you correctly, this should do the trick. You'll need add using System.IO
at the top of your file if you don't already have it.
public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
try
{
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(byteArray, 0, byteArray.Length);
return true;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in process: {0}", ex);
return false;
}
}
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data
but the new (RC.1
) router doesn't yet.
Update
data
was re-introduced in RC.4
How do I pass data in Angular 2 components while using Routing?
There is none. Don't forget that the value may be found on any number of keys, including 0 or more than 1.
I got this error because I stupidly wrote
public interface FooBarRepository extends CrudRepository<FooBarRepository, Long> { ...
A brief explanation: One typically creates a FooBarRepository class to manage FooBar objects (often representing data in a table called something like foo_bar.) When extending the CrudRepository to create the specialized repository class, one needs to specify the type that's being managed -- in this case, FooBar. What I mistakenly typed, though, was FooBarRepository rather than FooBar. FooBarRepository is not the type (the class) I'm trying to manage with the FooBarRepository. Therefore, the compiler issues this error.
I highlighted the mistaken bit of typing in bold. Delete the highlighted word Repository in my example and the code compiles.
There are plenty of built in python modules that whould help with this. For example urllib and htmllib.
The problem will be simpler if you change the way you're approaching it. You say you want to "fill some forms, click submit button, send the data back to server, recieve the response", which sounds like a four stage process.
In fact, what you need to do is post some data to a webserver and get a response.
This is as simple as:
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
(example taken from the urllib docs).
What you do with the response depends on how complex the HTML is and what you want to do with it. You might get away with parsing it using a regular expression or two, or you can use the htmllib.HTMLParser class, or maybe a higher level more flexible parser like Beautiful Soup.
The problem is going to be that you probably have no good means of keeping up with the changing postal code requirements of countries on the other side of the globe and which you share no common languages. Unless you have a large enough budget to track this, you are almost certainly better off giving the responsibility of validating addresses to google or yahoo.
Both companies provide address lookup facuilities through a programmable API.
Watch this video or try this:
Outer joins can offer superior performance when used in views.
Say you have a query that involves a view, and that view is comprised of 10 tables joined together. Say your query only happens to use columns from 3 out of those 10 tables.
If those 10 tables had been inner-joined together, then the query optimizer would have to join them all even though your query itself doesn't need 7 out of 10 of the tables. That's because the inner joins themselves might filter down the data, making them essential to compute.
If those 10 tables had been outer-joined together instead, then the query optimizer would only actually join the ones that were necessary: 3 out of 10 of them in this case. That's because the joins themselves are no longer filtering the data, and thus unused joins can be skipped.
Source: http://www.sqlservercentral.com/blogs/sql_coach/2010/07/29/poor-little-misunderstood-views/
per the mysql documentation, the DATE() function will pull the date part of a datetime feild, and TIME() for the time portion. so I would try:
select DATE(dateTimeField) as Date, TIME(dateTimeField) as Time, col2, col3, FROM Table1 ...
This worked for me. Add it in your web.config
<system.web>
<trust level="Full" />
angular.module('myApp').controller('myCtrl', function($scope, $rootScope) {
var a = //something in the scope
//put it in the root scope
$rootScope.test = "TEST";
});
angular.module('myApp').controller('myCtrl2', function($scope, $rootScope) {
var b = //get var a from root scope somehow
//use var b
$scope.value = $rootScope.test;
alert($scope.value);
// var b = $rootScope.test;
// alert(b);
});
This will give you sequence of anonymous objects, containing date string and two properties with average price:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new {
LogDate = g.Key,
AvgGoldPrice = (int)g.Average(x => x.GoldPrice),
AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
};
If you need to get list of PriceLog objects:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new PriceLog {
LogDateTime = DateTime.Parse(g.Key),
GoldPrice = (int)g.Average(x => x.GoldPrice),
SilverPrice = (int)g.Average(x => x.SilverPrice)
};
Do this:
FILE 1
There's also this quick (and somewhat dirty) one-liner:
$linecount=0; $i=0;
Get-Content .\BIG_LOG_FILE.txt | %
{
Add-Content OUT$i.log "$_";
$linecount++;
if ($linecount -eq 3000) {$I++; $linecount=0 }
}
You can tweak the number of first lines per batch by changing the hard-coded 3000 value.
Get-Content C:\TEMP\DATA\split\splitme.txt | Select -First 5000 | out-File C:\temp\file1.txt -Encoding ASCII
FILE 2
Get-Content C:\TEMP\DATA\split\splitme.txt | Select -Skip 5000 | Select -First 5000 | out-File C:\temp\file2.txt -Encoding ASCII
FILE 3
Get-Content C:\TEMP\DATA\split\splitme.txt | Select -Skip 10000 | Select -First 5000 | out-File C:\temp\file3.txt -Encoding ASCII
etc…
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
I don't see the benefit in aliasing out users tied to Schemas. Here is why....
Most people connect their user accounts to databases via roles initially, As soon as you assign a user to either the sysadmin, or the database role db_owner, in any form, that account is either aliased to the "dbo" user account, or has full permissions on a database. Once that occurs, no matter how you assign yourself to a scheme beyond your default schema (which has the same name as your user account), those dbo rights are assigned to those object you create under your user and schema. Its kinda pointless.....and just a namespace and confuses true ownership on those objects. Its poor design if you ask me....whomever designed it.
What they should have done is created "Groups", and thrown out schemas and role and just allow you to tier groups of groups in any combination you like, then at each tier tell the system if permissions are inherited, denied, or overwritten with custom ones. This would have been so much more intuitive and allowed DBA's to better control who the real owners are on those objects. Right now its implied in most cases the dbo default SQL Server user has those rights....not the user.
Page content can be displayed easily and perfectly this way:
<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; ?>
<?php else : ?>
<h3><?php _e('404 Error: Not Found'); ?></h3>
<?php endif; ?>
Note:
In terms of displaying content - i) comments_template() function is an optional use if you need to enable commenting with different functionality.
ii) _e() function is also optional but more meaningful & effective than just showing text through <p>
. while preferred stylized 404.php can be created to be redirected.
'openURL:' is deprecated: first deprecated in iOS 10.0 - Please use openURL:options:completionHandler: instead
in Objective-c iOS 10+ use :
NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber] options:@{} completionHandler:nil];
JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write
to display things on browser.
Also if your document.write
exceeds one line, make sure to put concatenation +
at the end of each line.
Example
<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>
Also if you use NHibernate you can turn on and setup second level cache for queries and add to queries scope and timeout. And there is kick ass profiler for EF, L2S and NHibernate - http://hibernatingrhinos.com/products/UberProf. It will help to tune your queries.
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
Interesting question on the differences between prevent default and return false.
In this case, return false will work just fine because the event doesn't need to be propagated.
Using pip with git+ to clone a repository can be extremely slow (test with https://github.com/django/django@stable/1.6.x for example, it will take a few minutes). The fastest thing I've found, which works with GitHub and BitBucket, is:
pip install https://github.com/user/repository/archive/branch.zip
which becomes for Django master:
pip install https://github.com/django/django/archive/master.zip
for Django stable/1.7.x:
pip install https://github.com/django/django/archive/stable/1.7.x.zip
With BitBucket it's about the same predictable pattern:
pip install https://bitbucket.org/izi/django-admin-tools/get/default.zip
Here, the master branch is generally named default.
This will make your requirements.txt
installing much faster.
Some other answers mention variations required when placing the package to be installed into your requirements.txt
. Note that with this archive syntax, the leading -e
and trailing #egg=blah-blah
are not required, and you can just simply paste the URL, so your requirements.txt looks like:
https://github.com/user/repository/archive/branch.zip
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
You can turn the color picker into an application by following the guide here:
http://hints.macworld.com/article.php?story=20060408050920158
From the guide:
Simply fire up AppleScript (Applications -> AppleScript Editor) and enter this text:
choose color
Now, save it as an application (File -> Save As, and set the File Format pop-up to Application), and you're done
For a massive speed increase, use NumPy's where function.
Create a two-column DataFrame with 100,000 rows with some zeros.
df = pd.DataFrame(np.random.randint(0,3, (100000,2)), columns=list('ab'))
numpy.where
df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
%timeit df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
685 µs ± 6.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit df.loc[df['a'] == 0, 'b'] = np.nan
3.11 ms ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Numpy's where
is about 4x faster
Assuming you already have a JFrame to call this from:
JOptionPane.showMessageDialog(frame, "thank you for using java");
Why not map the network drive but deselect "Reconnect at logon"? The drive will only connect when you try to access it. Note that some applications will fail if they point to it, but if you're accessing files directly through Windows Explorer this works great.