Here's another practical example from my CUDA Convolutional neural network library. I have the following class template:
template <class T> class Tensor
which is actually implements n-dimensional matrices manipulation. There's also a child class template:
template <class T> class TensorGPU : public Tensor<T>
which implements the same functionality but in GPU. Both templates can work with all basic types, like float, double, int, etc And I also have a class template (simplified):
template <template <class> class TT, class T> class CLayerT: public Layer<TT<T> >
{
TT<T> weights;
TT<T> inputs;
TT<int> connection_matrix;
}
The reason here to have template template syntax is because I can declare implementation of the class
class CLayerCuda: public CLayerT<TensorGPU, float>
which will have both weights and inputs of type float and on GPU, but connection_matrix will always be int, either on CPU (by specifying TT = Tensor) or on GPU (by specifying TT=TensorGPU).
Version I am using
Update 5th May 2012
Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:
Method 1
Add the comment /*csv*/
to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)
That's it.
Method 2
Run a query
Right click and select unload.
Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out
Revised screen shot for SQL Developer Version 3.0.04
From the format drop down select CSV
And follow the rest of the on screen instructions.
Basically, O(1) means its computation time is constant, while O(n) means it will depend lineally on the size of input - i.e. looping through an array has O(n) - just looping -, because it depends on the number of items, while calculating the maximum between to ordinary numbers has O(1).
Wikipedia might help as well: http://en.wikipedia.org/wiki/Computational_complexity_theory
select t2.*
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar) + '%/more'
where t1.id > 9000
Using concat like suggested is even better though
If you want to select the columns from First Table "which are also present in Second table, then in this case you can also use EXCEPT
. In this case, column names can be different as well but data type should be same.
Example:
select ID, FName
from FirstTable
EXCEPT
select ID, SName
from SecondTable
Again, using 3.5 you may do it like:
dt.Select().ToList()
BRGDS
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}
A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.
Reason : Old versions of Tomcat 6 JSP compiler don't seem to be aware of JDK 8 constant pool enhancements - eg. method handles. New code in JDK 8u is using a method handle instead of creating an anonymous class. This will cause the method handle to be listed in the constant pool and the eclipse compiler will choke on this - https://bz.apache.org/bugzilla/show_bug.cgi?id=56613
iReports Custom Fields for columns (sum, average, etc)
Right-Click on Variables and click Create Variable
Click on the new variable
a. Notice the properties on the right
Rename the variable accordingly
Change the Value Class Name to the correct Data Type
a. You can search by clicking the 3 dots
Select the correct type of calculation
Change the Expression
a. Click the little icon
b. Select the column you are looking to do the calculation for
c. Click finish
Set Initial Value Expression to 0
Set the increment type to none
Set the Reset Type (usually report)
Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)
Select the new variable
Click finish
Your problem is not actually specific to ejs.
2 things to note here
style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.
In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image
it can be done by
app.use(express.static(__dirname + '/public'));
assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like
<link href="/css/style.css" rel="stylesheet" type="text/css">
Here i assume you have put the css file in css folder inside your public folder.
So folder structure would be
.
./app.js
./public
/css
/style.css
Fedora/Cent Os same trouble when used yum install and interrupt it with Ctrl+Z.
Use this command:
sudo cat /var/cache/dnf/*pid
if there any pid, you can manually remove it:
sudo nano /var/cache/dnf/*pid
crtl+x followed by Y and Enter to exit nano editor (you can use any editor you want to open).
If after, delete some tmp files that may still be there:
sudo systemd-tmpfiles --remove dnf.conf
What solved it for me was using :
regasm.exe 'xx.dll' /tlb /codebase /register
It is however, important to understand the difference between regasm.exe and regsvr.exe:
What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?
I think a better way to do this is to change the base_size
argument. It will increase the text sizes consistently.
g + theme_grey(base_size = 22)
As seen here.
I needed to add USE_FRM to the repair statement to make it work.
REPAIR TABLE <table_name> USE_FRM;
thanks php-b-grader !
below the generic function for window.open pass values using POST:
function windowOpenInPost(actionUrl,windowName, windowFeatures, keyParams, valueParams)
{
var mapForm = document.createElement("form");
var milliseconds = new Date().getTime();
windowName = windowName+milliseconds;
mapForm.target = windowName;
mapForm.method = "POST";
mapForm.action = actionUrl;
if (keyParams && valueParams && (keyParams.length == valueParams.length)){
for (var i = 0; i < keyParams.length; i++){
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = keyParams[i];
mapInput.value = valueParams[i];
mapForm.appendChild(mapInput);
}
document.body.appendChild(mapForm);
}
map = window.open('', windowName, windowFeatures);
if (map) {
mapForm.submit();
} else {
alert('You must allow popups for this map to work.');
}}
For Python's boto3 after having used aws configure
:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('name')
for obj in bucket.objects.all():
print(obj.key)
A little variation on classes. Initialize it with hashtables.
class Point { $x; $y }
$a = [Point[]] (@{ x=1; y=2 },@{ x=3; y=4 })
$a
x y
- -
1 2
3 4
$a.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Point[] System.Array
$a[0].gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False Point System.Object
You can use addition to concatenate strings.
Strings are added by being joined into a larger string.
jq '.users[] | .first + " " + .last'
The above works when both first
and last
are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.
jq '.users[] | .first + " " + (.number|tostring)'
In Android L you will be able to just use View.setClipToOutline to get that effect. In previous versions there is no way to just clip the contents of a random ViewGroup in a certain shape.
You will have to think of something that would give you a similar effect:
If you only need rounded corners in the ImageView, you can use a shader to 'paint' the image over the shape you are using as background. Take a look at this library for an example.
If you really need every children to be clipped, maybe you can another view over your layout? One with a background of whatever color you are using, and a round 'hole' in the middle? You could actually create a custom ViewGroup that draws that shape over every children overriding the onDraw method.
$postbody='';
// Check for presence of a body in the request
if (count($request->json()->all())) {
$postbody = $request->json()->all();
}
This is how it's done in laravel 5.2 now.
i haved same problem when add new data in lazy image loader i just put
adapter.notifyDataSetChanged();
in
protected void onPostExecute(Void args) {
adapter.notifyDataSetChanged();
// Close the progressdialog
mProgressDialog.dismiss();
}
hope it helps you
Try this:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "127.0.0.1";
conn_string.Port = 3306;
conn_string.UserID = "root";
conn_string.Password = "myPassword";
conn_string.Database = "myDB";
MySqlConnection MyCon = new MySqlConnection(conn_string.ToString());
try
{
MyCon.Open();
MessageBox.Show("Open");
MyCon.Close();
MessageBox.Show("Close");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
You can use the @helper Razor directive:
@helper WelcomeMessage(string username)
{
<p>Welcome, @username.</p>
}
Then you invoke it like this:
@WelcomeMessage("John Smith")
Install Command Line Tools Works for me:
xcode-select --install
Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.
This is the way I am copying my arrays in Php:
function equal_array($arr){
$ArrayObject = new ArrayObject($arr);
return $ArrayObject->getArrayCopy();
}
$test = array("aa","bb",3);
$test2 = equal_array($test);
print_r($test2);
This outputs:
Array
(
[0] => aa
[1] => bb
[2] => 3
)
When you use --user
option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.
The location of user's packages folder can be found using:
python -m site --user-site
This will print something like:
C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages
When you don't use --user
option with pip, the package gets installed in global folder given by:
python -c "import site; print(site.getsitepackages())"
This will print something like:
['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'
Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());
I just finished my weekend project cached-webpgr.js which uses the localStorage / web storage to cache JavaScript files. This approach is very fast. My small test showed
The code to achieve that is tiny, you can check it out at my Github project https://github.com/webpgr/cached-webpgr.js
Here is a full example how to use it.
The complete library:
function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};
Calling the library
requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
requireScript('examplejs', '0.0.3', 'example.js');
});
As mentioned, ini4j can be used to achieve this. Let me show one other example.
If we have an INI file like this:
[header]
key = value
The following should display value
to STDOUT:
Ini ini = new Ini(new File("/path/to/file"));
System.out.println(ini.get("header", "key"));
Check the tutorials for more examples.
.net core
using System.Text.Json;
var jsonStr = JsonSerializer.Serialize(MyObject)
var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);
For more information about excluding properties and nulls check out This Microsoft side
objectframe.contentWindow.Reset()
you need reference to the top level element in the frame first.
I stumbled upon a similar problem as OP. Unfortunately the accepted answer did not work for me since the content of the collectionView
would not be centered properly. Therefore I came up with a different solution which only requires that all items in the collectionView
are of the same width, which seems to be the case in the question:
#define cellSize 90
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
float width = collectionView.frame.size.width;
float spacing = [self collectionView:collectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
int numberOfCells = (width + spacing) / (cellSize + spacing);
int inset = (width + spacing - numberOfCells * (cellSize + spacing) ) / 2;
return UIEdgeInsetsMake(0, inset, 0, inset);
}
That code will ensure that the value returned by ...minimumInteritemSpacing...
will be the exact spacing between every collectionViewCell
and furthermore guarantee that the cells all together will be centered in the collectionView
The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
. Let's replace it in its context:
i + 1 >= len(x)
<=> i >= 0
, the element x[i+1]
doesn't exist. Here, this element doesn't exist since the beginning of the for loop.To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
.
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined
if the array is empty.
Dumb question/answer perhaps, but have you tried dd/MM/yyyy
? Note the capitalization.
mm
is for minutes with a leading zero. So I doubt that's what you want.
This may be helpful: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
that scp command must be issued on the local command-line, for putty the command is pscp.
C:\something> pscp [email protected]:/dir/of/file.txt \local\dir\
$(".overdue").each( function() {
alert("Your book is overdue.");
});
Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.
Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).
Perhaps use the size function:
alert( "You have " + $(".overdue").size() + " books overdue." );
If you're having this problem with Spring Boot 1.4.x and up, you might be able to use @OverrideAutoConfiguration(enabled=true)
to solve the problem.
Similar to what was asked/answered here https://stackoverflow.com/a/39253304/1410035
You can reorder the operands:
$null -eq $foo
Note that -eq
in PowerShell is not an equivalence relation.
Darin Dimitrov's solution worked for me with one exception. When I submitted the partial view with (intentional) validation errors, I ended up with duplicate forms being returned in the dialog:
To fix this I had to wrap the Html.BeginForm in a div:
<div id="myForm">
@using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
{
//form contents
}
</div>
When the form was submitted, I cleared the div in the success function and output the validated form:
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myForm').html('');
$('#result').html(result);
}
});
}
return false;
});
});
You can use DISTINCT
like that
mysql_query("SELECT DISTINCT(ticket_id), column1, column2, column3
FROM temp_tickets
ORDER BY ticket_id");
1st Step: Add this content in pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2nd Step : Execute this command line by line.
cd /go/to/myApp
mvn clean
mvn compile
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute
Many people have already mentioned that document.cookie
gets you all the cookies (except http-only
ones).
I'll just add a snippet to keep up with the times.
document.cookie.split(';').reduce((cookies, cookie) => {
const [ name, value ] = cookie.split('=').map(c => c.trim());
cookies[name] = value;
return cookies;
}, {});
The snippet will return an object with cookie names as the keys with cookie values as the values.
Slightly different syntax:
document.cookie.split(';').reduce((cookies, cookie) => {
const [ name, value ] = cookie.split('=').map(c => c.trim());
return { ...cookies, [name]: value };
}, {});
With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.
You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/
The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):
SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
FROM dbo.tableZ AS t
ORDER BY t.A;
Not sure what the variables in your question are supposed to represent (they don't match).
You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.
You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).
You should convert the shortened array back to a string with .join(",")
and then use it for the new cookie instead of using old_cookie
which is not shortened.
You may also not be using .splice()
correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice()
here.
Why not check Number - a bit shorter and works in IE/Chrome/FF/node.js
function whatIsIt(object) {_x000D_
if (object === null) {_x000D_
return "null";_x000D_
}_x000D_
else if (object === undefined) {_x000D_
return "undefined";_x000D_
}_x000D_
if (object.constructor.name) {_x000D_
return object.constructor.name;_x000D_
}_x000D_
else { // last chance 4 IE: "\nfunction Number() {\n [native code]\n}\n" / node.js: "function String() { [native code] }"_x000D_
var name = object.constructor.toString().split(' ');_x000D_
if (name && name.length > 1) {_x000D_
name = name[1];_x000D_
return name.substr(0, name.indexOf('('));_x000D_
}_x000D_
else { // unreachable now(?)_x000D_
return "don't know";_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];_x000D_
// Test all options_x000D_
console.log(whatIsIt(null));_x000D_
console.log(whatIsIt());_x000D_
for (var i=0, len = testSubjects.length; i < len; i++) {_x000D_
console.log(whatIsIt(testSubjects[i]));_x000D_
}
_x000D_
From my understanding, size_t
is an unsigned
integer whose bit size is large enough to hold a pointer of the native architecture.
So:
sizeof(size_t) >= sizeof(void*)
Unix time conversion is new in .NET Framework 4.6.
You can now more easily convert date and time values to or from .NET Framework types and Unix time. This can be necessary, for example, when converting time values between a JavaScript client and .NET server. The following APIs have been added to the DateTimeOffset structure:
static DateTimeOffset FromUnixTimeSeconds(long seconds)
static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
long DateTimeOffset.ToUnixTimeSeconds()
long DateTimeOffset.ToUnixTimeMilliseconds()
Never ever use getApplicationContext() with views.
It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.
In RStudio you can write directly in a cell.
Suppose your data.frame is called myDataFrame
and the row and column are called columnName
and rowName
.
Then the code would look like:
myDataFrame["rowName", "columnName"] <- value
Hope that helps!
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
According to MSDN, e.AddedItems
:
Gets a list that contains the items that were selected.
So you could use:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}
You could also use SelectedItem
if you use string
values for the Items
from the sender
:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem as string;
}
or
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}
Since both Content
and SelectedItem
are objects, a safer approach would be to use .ToString()
instead of as string
Try:
SELECT into #T1 execute ('execute ' + @SQLString )
And this smells real bad like an sql injection vulnerability.
correction (per @CarpeDiem's comment):
INSERT into #T1 execute ('execute ' + @SQLString )
also, omit the 'execute'
if the sql string is something other than a procedure
Have you tried the Generate Scripts
(Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?
What is the difference between logger.debug and logger.info?
These are only some default level already defined. You can define your own levels if you like. The purpose of those levels is to enable/disable one or more of them, without making any change in your code.
When logger.debug will be printed ??
When you have enabled the debug or any higher level in your configuration.
You can either use JavaScript or CSS3.
JavaScript solution: Use an absolute positioned <img>
tag and resize it on the page load and whenever the page resizes. Be careful of possible bugs when trying to get the page/window size.
CSS3 solution: Use the CSS3 background-size property. You might use either 100% 100%
or contain
or cover
, depending on how you want the image to resize. Of course, this only works on modern browsers.
In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.
It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.
As a note for the future: if you need a sentence parsed out and tag it as linguistics
(and syntax
or whatnot, if that's available), someone can probably parse it out for you and guide you through it.
Note that using const user = {} as UserType
just provides intellisense but at runtime user
is empty object {}
and has no property inside. that means user.Email
will give undefined
instead of ""
type UserType = {
Username: string;
Email: string;
}
So, use class
with constructor
for actually creating objects with default properties.
type UserType = {
Username: string;
Email: string;
};
class User implements UserType {
constructor() {
this.Username = "";
this.Email = "";
}
Username: string;
Email: string;
}
const myUser = new User();
console.log(myUser); // output: {Username: "", Email: ""}
console.log("val: "+myUser.Email); // output: ""
You can also use interface
instead of type
interface UserType {
Username: string;
Email: string;
};
...and rest of code remains same.
Actually, you can even skip the constructor
part and use it like this:
class User implements UserType {
Username = ""; // will be added to new obj
Email: string; // will not be added
}
const myUser = new User();
console.log(myUser); // output: {Username: ""}
StringTokenizer separate = new StringTokenizer(s, " ");
String word = separate.nextToken();
System.out.println(word);
You may use closest()
in modern browsers:
var div = document.querySelector('div#myDiv');
div.closest('div[someAtrr]');
Use object detection to supply a polyfill or alternative method for backwards compatability with IE.
It really depends on what kind of type safety you need. The non-generic way of doing it is best done as:
Map x = new HashMap();
Note that x
is typed as a Map
. this makes it much easier to change implementations (to a TreeMap
or a LinkedHashMap
) in the future.
You can use generics to ensure a certain level of type safety:
Map<String, Object> x = new HashMap<String, Object>();
In Java 7 and later you can do
Map<String, Object> x = new HashMap<>();
The above, while more verbose, avoids compiler warnings. In this case the content of the HashMap
can be any Object
, so that can be Integer
, int[]
, etc. which is what you are doing.
If you are still using Java 6, Guava Libraries (although it is easy enough to do yourself) has a method called newHashMap()
which avoids the need to duplicate the generic typing information when you do a new
. It infers the type from the variable declaration (this is a Java feature not available on constructors prior to Java 7).
By the way, when you add an int or other primitive, Java is autoboxing it. That means that the code is equivalent to:
x.put("one", Integer.valueOf(1));
You can certainly put a HashMap
as a value in another HashMap
, but I think there are issues if you do it recursively (that is put the HashMap
as a value in itself).
.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.
You can also try this
// create a thread
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
// create and show the window
FaxImageLoad obj = new FaxImageLoad(destination);
obj.Show();
// start the Dispatcher processing
System.Windows.Threading.Dispatcher.Run();
}));
// set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// make the thread a background thread
newWindowThread.IsBackground = true;
// start the thread
newWindowThread.Start();
try:
ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'
for my case Footer method was having malformed html code (missing td) causing error on osx.
public function Footer() {
$this->SetY(-40);
$html = <<<EOD
<table>
<tr>
Test Data
</tr>
</table>
EOD;
$this->writeHTML($html);
}
As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:
mailto:[email protected]?subject=Subject&body=message%20goes%20here
User doesn't need to click a link if you force it to be opened with JavaScript
window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";
Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.
Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.
There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.
To get the result I believe you are looking for try this:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
</div>
</div>
Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.
Hope this helps.
There's a great example in the AngularJS docs.
It's very well commented and should get you pointed in the right direction.
A simple example, maybe more so what you're looking for is below:
HTML
<div ng-app="myDirective" ng-controller="x">
<input type="text" ng-model="test" my-directive>
</div>
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Edit: Same thing, doesn't require ngModel
jsfiddle:
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
// set the initial value of the textbox
element.val(scope.myDirective);
element.data('old-value', scope.myDirective);
// detect outside changes and update our input
scope.$watch('myDirective', function (val) {
element.val(scope.myDirective);
});
// on blur, update the value in scope
element.bind('propertychange keyup paste', function (blurEvent) {
if (element.data('old-value') != element.val()) {
console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
scope.myDirective = element.val();
element.data('old-value', element.val());
});
}
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
What is the right way to reverse a pandas DataFrame?
df[::-1]
This is objectively IMO the best method for reversing a DataFrame, because it is a ONE step operation, also very readable (assuming familiarity with slice notation).
I've found the ol' slicing trick df[::-1]
(or the equivalent df.loc[::-1]
1) to be the most concise and idiomatic way of reversing a DataFrame. This mirrors the python list reversal syntax lst[::-1]
and is clear in its intent. With the loc
syntax, you are also able to slice columns if required, so it is a bit more flexible.
Some points to consider while handling the index:
"what if I want to reverse the index as well?"
df[::-1]
reverses both the index and values."what if I want to drop the index from the result?"
.reset_index(drop=True)
at the end."what if I want to keep the index untouched (IOW, only reverse the data, not the index)?"
df[:] = df[::-1]
which creates an in-place update to df
, or df.loc[::-1].set_index(df.index)
, which returns a copy. 1: df.loc[::-1]
and df.iloc[::-1]
are equivalent since the slicing syntax remains the same, whether you're reversing by position (iloc
) or label (loc
).
X-axis represents the dataset size. Y-axis represents time taken to reverse. No method scales as well as the slicing trick, it's all the way at the bottom of the graph. Benchmarking code for reference, plots generated using perfplot.
df.reindex(index=df.index[::-1])
is clearly a popular solution, but on first glance, how obvious is it to an unfamiliar reader that this code is "reversing a DataFrame"? Additionally, this is reversing the index, then using that intermediate result to reindex
, so this is essentially a TWO step operation (when it could've been just one).
df.sort_index(ascending=False)
may work in most cases where you have a simple range index, but this assumes your index was sorted in ascending order and so doesn't generalize well.
PLEASE do not use iterrows
. I see some options suggesting iterating in reverse. Whatever your use case, there is likely a vectorized method available, but if there isn't then you can use something a little more reasonable such as list comprehensions. See How to iterate over rows in a DataFrame in Pandas for more detail on why iterrows
is an antipattern.
I also had this issue. I had both VS code
and Android studio
installed in my system.
The error was in VS code
.
When i opened the same project on Android studio
, the dependency was not actually added to pubsec.yaml
. I added it there and ran pub.get
.
When I returned to VS Code
and everything was working fine.
So, Try opening it in other editor if you have, or through NotePad
.
Edit:
Opening widget_test.dart
and running it should also solve your issue.
Not sure from what version, but I use 1.3.14 and you can just use:
window.location.href = '/employee/1';
No need to inject $location
or $window
in the controller and no need to get the current host address.
Try to use the WEEKDAY()
function.
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
How about using ASCII codes?
let n = str.charCodeAt(0);
let strStartsWithALetter = (n >= 65 && n < 91) || (n >= 97 && n < 123);
float : 23 bits of significand, 8 bits of exponent, and 1 sign bit.
double : 52 bits of significand, 11 bits of exponent, and 1 sign bit.
The closest you will ever get to doing such thing is a dissasembler, or debug info (Log2Vis.pdb).
You can also use:
img{
filter:grayscale(100%);
}
img:hover{
filter:none;
}
I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).
This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.
Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null
out the reference to class B to allow it to be collected.
A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.
If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?
You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.
Would that take more space than just plugging '5' into the println method?
The JIT is smart enough to turn fields which don't change into constants.
Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory
Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.
You can input variables via switch -e
$ gnuplot -e "filename='foo.data'" foo.plg
In foo.plg you can then use that variable
$ cat foo.plg
plot filename
pause -1
To make "foo.plg" a bit more generic, use a conditional:
if (!exists("filename")) filename='default.dat'
plot filename
pause -1
Note that -e
has to precede the filename otherwise the file runs before the -e
statements. In particular, running a shebang gnuplot #!/usr/bin/env gnuplot
with ./foo.plg -e ...
CLI arguments will ignore use the arguments provided.
Note: This solution works well on Ubuntu 16.04
, Ubuntu 17.04
and Ubuntu 18.04
.
Try to remove the existing cmdtest and yarn (which is the module of legacy black box command line tool of *nix systems) :
sudo apt remove cmdtest sudo apt remove yarn
Install it simple via npm
npm install -g yarn
OR
sudo npm install -g yarn
Now yarn is installed. Run your command.
yarn install sylius
I hope this will work. Cheers!
Edit:
Do remember to re-open the terminal
for changes to take effect.
Well one major thing is anything you submit over GET
is going to be exposed via the URL. Secondly as Ceejayoz says, there is a limit on characters for a URL.
I suggest Validator.nu's parser, based on the HTML5 parsing algorithm. It is the parser used in Mozilla from 2010-05-03
There is no such keyword "atomic"
@property(atomic, retain) UITextField *userName;
We can use the above like
@property(retain) UITextField *userName;
See Stack Overflow question I am getting issues if I use @property(atomic,retain)NSString *myString.
explode
has some very big problems in real life usage:
count(explode(',', null)); // 1 !!
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8
this is why i prefer preg_split
preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)
the entire boilerplate:
/** @brief wrapper for explode
* @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
* @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
* @param string $delimiter default ','
* @return array|mixed
*/
public static function explode($val, $as_is = false, $delimiter = ',')
{
// using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
return (is_string($val) || is_int($val)) ?
preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
:
($as_is ? $val : (is_array($val) ? $val : []));
}
C# 7 adds support for local functions
Here is the previous example using a local function
void Method()
{
string localFunction(string source)
{
// add your functionality here
return source ;
};
// call the inline function
localFunction("prefix");
}
As Parag's solution threw an error for me, here's my solution (combining David Hedlund's and Parag's):
if (!$("input[name='name']").is(':checked')) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
This worked fine for me!
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
Cast from string using float()
:
>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
If t
is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.
x = exp( -t.^2 )
or
x = exp( -t.*t )
When filtering a DataFrame with string values, I find that the pyspark.sql.functions
lower
and upper
come in handy, if your data could have column entries like "foo" and "Foo":
import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))
use test
go
alter proc restore_mdf_ldf_main (@database varchar(100), @mdf varchar(100),@ldf varchar(100),@filename varchar(200))
as
begin
begin try
RESTORE DATABASE @database FROM DISK = @FileName
with norecovery,
MOVE @mdf TO 'D:\sql samples\sample.mdf',
MOVE @ldf TO 'D:\sql samples\sample.ldf'
end try
begin catch
SELECT ERROR_MESSAGE() AS ErrorMessage;
print 'Restoring of the database ' + @database + ' failed';
end catch
end
exec restore_mdf_ldf_main product,product,product_log,'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\product.bak'
JPA is a specification to standardize ORM-APIs. Hibernate is a vendor of a JPA implementation. So if you use JPA with hibernate, you can use the standard JPA API, hibernate will be under the hood, offering some more non standard functions. See http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/ and http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/
If you are "getting data" from an application, the sensible thing would be to use the profiler and profile the database while running the application. Trace it, then search the results for that string.
As long as you specify a width on the element, it should wrap itself without needing anything else.
You must analyse the actual HTML output, for the hint.
By giving the path like this means "from current location", on the other hand if you start with a /
that would mean "from the context".
Another interesting solution is PhantomJS. It's a headless WebKit scriptable with JavaScript or CoffeeScript.
One of the use case is screen capture : you can programmatically capture web contents, including SVG and Canvas and/or Create web site screenshots with thumbnail preview.
The best entry point is the screen capture wiki page.
Here is a good example for polar clock (from RaphaelJS):
>phantomjs rasterize.js http://raphaeljs.com/polar-clock.html clock.png
Do you want to render a page to a PDF ?
> phantomjs rasterize.js 'http://en.wikipedia.org/w/index.php?title=Jakarta&printable=yes' jakarta.pdf
from re import search
from functools import wraps
def is_match(_lambda, pattern):
def wrapper(f):
@wraps(f)
def wrapped(self, *f_args, **f_kwargs):
if callable(_lambda) and search(pattern, (_lambda(self) or '')):
f(self, *f_args, **f_kwargs)
return wrapped
return wrapper
class MyTest(object):
def __init__(self):
self.name = 'foo'
self.surname = 'bar'
@is_match(lambda x: x.name, 'foo')
@is_match(lambda x: x.surname, 'foo')
def my_rule(self):
print 'my_rule : ok'
@is_match(lambda x: x.name, 'foo')
@is_match(lambda x: x.surname, 'bar')
def my_rule2(self):
print 'my_rule2 : ok'
test = MyTest()
test.my_rule()
test.my_rule2()
ouput: my_rule2 : ok
This should work perfect just copy this div code
<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&hl=en_US&autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>
For symfony 2.6 and above we can use
{{ app.user.getFirstname() }}
as app.security global variable for Twig template has been deprecated and will be removed from 3.0
more info:
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
and see the global variables in
http://symfony.com/doc/current/reference/twig_reference.html
The .bash_profile for macOS is found in the $HOME
directory. You can create the file if it does not exit. Sublime Text 3 can help.
If you follow the instruction from OS X Command Line - Sublime Text to launch ST3 with subl
then you can just do this
$ subl ~/.bash_profile
An easier method is to use open
$ open ~/.bash_profile -a "Sublime Text"
Use Command + Shift + . in Finder to view hidden files in your home directory.
The replace()
method is overloaded to accept both a primitive char
and a CharSequence
as arguments.
Now as far as the performance is concerned, the replace()
method is a bit faster than replaceAll()
because the latter first compiles the regex pattern and then matches before finally replacing whereas the former simply matches for the provided argument and replaces.
Since we know the regex pattern matching is a bit more complex and consequently slower, then preferring replace()
over replaceAll()
is suggested whenever possible.
For example, for simple substitutions like you mentioned, it is better to use:
replace('.', '\\');
instead of:
replaceAll("\\.", "\\\\");
Note: the above conversion method arguments are system-dependent.
Line from above answer:
HtmlDocument doc = new HtmlDocument();
This doesn't work in VS 2015 C#. You cannot construct an HtmlDocument
any more.
Another MS "feature" that makes things more difficult to use. Try HtmlAgilityPack.HtmlWeb
and check out this link for some sample code.
The __init__.py
file makes Python treat directories containing it as modules.
Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):
db.someCollection.find().snapshot().forEach(function(doc) {
if (doc._id.indexOf("2019:") != 0) {
print("Processing: " + doc._id);
var oldDocId = doc._id;
doc._id = "2019:" + doc._id;
db.someCollection.insert(doc);
db.someCollection.remove({_id: oldDocId});
}
});
if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.
Select * from table where date > 'Today's date(mm/dd/yyyy)'
You can also add time in the single quotes(00:00:00AM)
For example:
Select * from Receipts where Sales_date > '08/28/2014 11:59:59PM'
Alternatively you could add an endpoint to return your variable:
@app.route("/api/geocode")
def geo_code():
return jsonify(geocode)
Then do an XHR to retrieve it:
fetch('/api/geocode')
.then((res)=>{ console.log(res) })
here is your answer
String userName = "xxxx";
String password = "xxxx";
String url = "jdbc:sqlserver:xxx.xxx.xxx.xxx;databaseName=asdfzxcvqwer;integratedSecurity=true";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url, userName, password);
} catch (Exception e)
{
e.printStackTrace();
}
I've thought about this problem a lot, and there are a few different behaviors one could want. I've been implementing most of them for Unix and Windows, and will post them here once they are done.
input
or raw_input
, a blocking function which returns text typed by a user once they press a newline.The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).
The same as 1, except that poll only returns something once the user presses a newline.
These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user
A simple input
or raw_input
, a blocking function which returns text typed by a user once they press a newline.
typedString = raw_input()
A simple blocking function that waits for the user to press a single key, then returns that key
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
try:
self.impl = _GetchMacCarbon()
except(AttributeError, ImportError):
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
class _GetchMacCarbon:
"""
A function which returns the current ASCII key that is down;
if no ASCII key is down, the null string is returned. The
page http://www.mactech.com/macintosh-c/chap02-1.html was
very helpful in figuring out how to do this.
"""
def __init__(self):
import Carbon
Carbon.Evt #see if it has this (in Unix, it doesn't)
def __call__(self):
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
return ''
else:
#
# The event contains the following info:
# (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
#
# The message (msg) contains the ASCII char which is
# extracted with the 0x000000FF charCodeMask; this
# number is converted to an ASCII character with chr() and
# returned
#
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
return chr(msg & 0x000000FF)
def getKey():
inkey = _Getch()
import sys
for i in xrange(sys.maxint):
k=inkey()
if k<>'':break
return k
A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)
A callback that is called with the typed text after the user presses enter (a less realtime keylogger)
Windows:
This uses the windows Robot given below, naming the script keyPress.py
# Some if this is from http://nullege.com/codes/show/src@e@i@einstein-HEAD@Python25Einstein@[email protected]/380/win32api.GetStdHandle
# and
# http://nullege.com/codes/show/src@v@i@VistA-HEAD@Python@[email protected]/901/win32console.GetStdHandle.PeekConsoleInput
from ctypes import *
import time
import threading
from win32api import STD_INPUT_HANDLE, STD_OUTPUT_HANDLE
from win32console import GetStdHandle, KEY_EVENT, ENABLE_WINDOW_INPUT, ENABLE_MOUSE_INPUT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT
import keyPress
class CaptureLines():
def __init__(self):
self.stopLock = threading.Lock()
self.isCapturingInputLines = False
self.inputLinesHookCallback = CFUNCTYPE(c_int)(self.inputLinesHook)
self.pyosInputHookPointer = c_void_p.in_dll(pythonapi, "PyOS_InputHook")
self.originalPyOsInputHookPointerValue = self.pyosInputHookPointer.value
self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
def inputLinesHook(self):
self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
inputChars = self.readHandle.ReadConsole(10000000)
self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT)
if inputChars == "\r\n":
keyPress.KeyPress("\n")
return 0
inputChars = inputChars[:-2]
inputChars += "\n"
for c in inputChars:
keyPress.KeyPress(c)
self.inputCallback(inputChars)
return 0
def startCapture(self, inputCallback):
self.stopLock.acquire()
try:
if self.isCapturingInputLines:
raise Exception("Already capturing keystrokes")
self.isCapturingInputLines = True
self.inputCallback = inputCallback
self.pyosInputHookPointer.value = cast(self.inputLinesHookCallback, c_void_p).value
except Exception as e:
self.stopLock.release()
raise
self.stopLock.release()
def stopCapture(self):
self.stopLock.acquire()
try:
if not self.isCapturingInputLines:
raise Exception("Keystrokes already aren't being captured")
self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
self.isCapturingInputLines = False
self.pyosInputHookPointer.value = self.originalPyOsInputHookPointerValue
except Exception as e:
self.stopLock.release()
raise
self.stopLock.release()
A callback that is called with the keys pressed when a program is running (say, in a for loop or while loop)
Windows:
import threading
from win32api import STD_INPUT_HANDLE
from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT
class KeyAsyncReader():
def __init__(self):
self.stopLock = threading.Lock()
self.stopped = True
self.capturedChars = ""
self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
def startReading(self, readCallback):
self.stopLock.acquire()
try:
if not self.stopped:
raise Exception("Capture is already going")
self.stopped = False
self.readCallback = readCallback
backgroundCaptureThread = threading.Thread(target=self.backgroundThreadReading)
backgroundCaptureThread.daemon = True
backgroundCaptureThread.start()
except:
self.stopLock.release()
raise
self.stopLock.release()
def backgroundThreadReading(self):
curEventLength = 0
curKeysLength = 0
while True:
eventsPeek = self.readHandle.PeekConsoleInput(10000)
self.stopLock.acquire()
if self.stopped:
self.stopLock.release()
return
self.stopLock.release()
if len(eventsPeek) == 0:
continue
if not len(eventsPeek) == curEventLength:
if self.getCharsFromEvents(eventsPeek[curEventLength:]):
self.stopLock.acquire()
self.stopped = True
self.stopLock.release()
break
curEventLength = len(eventsPeek)
def getCharsFromEvents(self, eventsPeek):
callbackReturnedTrue = False
for curEvent in eventsPeek:
if curEvent.EventType == KEY_EVENT:
if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
pass
else:
curChar = str(curEvent.Char)
if self.readCallback(curChar) == True:
callbackReturnedTrue = True
return callbackReturnedTrue
def stopReading(self):
self.stopLock.acquire()
self.stopped = True
self.stopLock.release()
The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).
Windows and OS X (and maybe Linux):
global isWindows
isWindows = False
try:
from win32api import STD_INPUT_HANDLE
from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT
isWindows = True
except ImportError as e:
import sys
import select
import termios
class KeyPoller():
def __enter__(self):
global isWindows
if isWindows:
self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
self.curEventLength = 0
self.curKeysLength = 0
self.capturedChars = []
else:
# Save the terminal settings
self.fd = sys.stdin.fileno()
self.new_term = termios.tcgetattr(self.fd)
self.old_term = termios.tcgetattr(self.fd)
# New terminal setting unbuffered
self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)
return self
def __exit__(self, type, value, traceback):
if isWindows:
pass
else:
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)
def poll(self):
if isWindows:
if not len(self.capturedChars) == 0:
return self.capturedChars.pop(0)
eventsPeek = self.readHandle.PeekConsoleInput(10000)
if len(eventsPeek) == 0:
return None
if not len(eventsPeek) == self.curEventLength:
for curEvent in eventsPeek[self.curEventLength:]:
if curEvent.EventType == KEY_EVENT:
if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
pass
else:
curChar = str(curEvent.Char)
self.capturedChars.append(curChar)
self.curEventLength = len(eventsPeek)
if not len(self.capturedChars) == 0:
return self.capturedChars.pop(0)
else:
return None
else:
dr,dw,de = select.select([sys.stdin], [], [], 0)
if not dr == []:
return sys.stdin.read(1)
return None
Simple use case:
with KeyPoller() as keyPoller:
while True:
c = keyPoller.poll()
if not c is None:
if c == "c":
break
print c
The same as above, except that poll only returns something once the user presses a newline.
These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user
Windows:
# Modified from http://stackoverflow.com/a/13615802/2924421
import ctypes
from ctypes import wintypes
import time
user32 = ctypes.WinDLL('user32', use_last_error=True)
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_SCANCODE = 0x0008
MAPVK_VK_TO_VSC = 0
# C struct definitions
wintypes.ULONG_PTR = wintypes.WPARAM
SendInput = ctypes.windll.user32.SendInput
PUL = ctypes.POINTER(ctypes.c_ulong)
class KEYBDINPUT(ctypes.Structure):
_fields_ = (("wVk", wintypes.WORD),
("wScan", wintypes.WORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", wintypes.ULONG_PTR))
class MOUSEINPUT(ctypes.Structure):
_fields_ = (("dx", wintypes.LONG),
("dy", wintypes.LONG),
("mouseData", wintypes.DWORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", wintypes.ULONG_PTR))
class HARDWAREINPUT(ctypes.Structure):
_fields_ = (("uMsg", wintypes.DWORD),
("wParamL", wintypes.WORD),
("wParamH", wintypes.WORD))
class INPUT(ctypes.Structure):
class _INPUT(ctypes.Union):
_fields_ = (("ki", KEYBDINPUT),
("mi", MOUSEINPUT),
("hi", HARDWAREINPUT))
_anonymous_ = ("_input",)
_fields_ = (("type", wintypes.DWORD),
("_input", _INPUT))
LPINPUT = ctypes.POINTER(INPUT)
def _check_count(result, func, args):
if result == 0:
raise ctypes.WinError(ctypes.get_last_error())
return args
user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
LPINPUT, # pInputs
ctypes.c_int) # cbSize
def KeyDown(unicodeKey):
key, unikey, uniflag = GetKeyCode(unicodeKey)
x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag, 0))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
def KeyUp(unicodeKey):
key, unikey, uniflag = GetKeyCode(unicodeKey)
extra = ctypes.c_ulong(0)
x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag | KEYEVENTF_KEYUP, 0))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
def KeyPress(unicodeKey):
time.sleep(0.0001)
KeyDown(unicodeKey)
time.sleep(0.0001)
KeyUp(unicodeKey)
time.sleep(0.0001)
def GetKeyCode(unicodeKey):
k = unicodeKey
curKeyCode = 0
if k == "up": curKeyCode = 0x26
elif k == "down": curKeyCode = 0x28
elif k == "left": curKeyCode = 0x25
elif k == "right": curKeyCode = 0x27
elif k == "home": curKeyCode = 0x24
elif k == "end": curKeyCode = 0x23
elif k == "insert": curKeyCode = 0x2D
elif k == "pgup": curKeyCode = 0x21
elif k == "pgdn": curKeyCode = 0x22
elif k == "delete": curKeyCode = 0x2E
elif k == "\n": curKeyCode = 0x0D
if curKeyCode == 0:
return 0, int(unicodeKey.encode("hex"), 16), KEYEVENTF_UNICODE
else:
return curKeyCode, 0, 0
OS X:
#!/usr/bin/env python
import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost
# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease
from Quartz.CoreGraphics import kCGHIDEventTap
# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent
def KeyDown(k):
keyCode, shiftKey = toKeyCode(k)
time.sleep(0.0001)
if shiftKey:
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
time.sleep(0.0001)
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
time.sleep(0.0001)
if shiftKey:
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
time.sleep(0.0001)
def KeyUp(k):
keyCode, shiftKey = toKeyCode(k)
time.sleep(0.0001)
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
time.sleep(0.0001)
def KeyPress(k):
keyCode, shiftKey = toKeyCode(k)
time.sleep(0.0001)
if shiftKey:
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
time.sleep(0.0001)
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
time.sleep(0.0001)
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
time.sleep(0.0001)
if shiftKey:
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
time.sleep(0.0001)
# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes
def toKeyCode(c):
shiftKey = False
# Letter
if c.isalpha():
if not c.islower():
shiftKey = True
c = c.lower()
if c in shiftChars:
shiftKey = True
c = shiftChars[c]
if c in keyCodeMap:
keyCode = keyCodeMap[c]
else:
keyCode = ord(c)
return keyCode, shiftKey
shiftChars = {
'~': '`',
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
'(': '9',
')': '0',
'_': '-',
'+': '=',
'{': '[',
'}': ']',
'|': '\\',
':': ';',
'"': '\'',
'<': ',',
'>': '.',
'?': '/'
}
keyCodeMap = {
'a' : 0x00,
's' : 0x01,
'd' : 0x02,
'f' : 0x03,
'h' : 0x04,
'g' : 0x05,
'z' : 0x06,
'x' : 0x07,
'c' : 0x08,
'v' : 0x09,
'b' : 0x0B,
'q' : 0x0C,
'w' : 0x0D,
'e' : 0x0E,
'r' : 0x0F,
'y' : 0x10,
't' : 0x11,
'1' : 0x12,
'2' : 0x13,
'3' : 0x14,
'4' : 0x15,
'6' : 0x16,
'5' : 0x17,
'=' : 0x18,
'9' : 0x19,
'7' : 0x1A,
'-' : 0x1B,
'8' : 0x1C,
'0' : 0x1D,
']' : 0x1E,
'o' : 0x1F,
'u' : 0x20,
'[' : 0x21,
'i' : 0x22,
'p' : 0x23,
'l' : 0x25,
'j' : 0x26,
'\'' : 0x27,
'k' : 0x28,
';' : 0x29,
'\\' : 0x2A,
',' : 0x2B,
'/' : 0x2C,
'n' : 0x2D,
'm' : 0x2E,
'.' : 0x2F,
'`' : 0x32,
'k.' : 0x41,
'k*' : 0x43,
'k+' : 0x45,
'kclear' : 0x47,
'k/' : 0x4B,
'k\n' : 0x4C,
'k-' : 0x4E,
'k=' : 0x51,
'k0' : 0x52,
'k1' : 0x53,
'k2' : 0x54,
'k3' : 0x55,
'k4' : 0x56,
'k5' : 0x57,
'k6' : 0x58,
'k7' : 0x59,
'k8' : 0x5B,
'k9' : 0x5C,
# keycodes for keys that are independent of keyboard layout
'\n' : 0x24,
'\t' : 0x30,
' ' : 0x31,
'del' : 0x33,
'delete' : 0x33,
'esc' : 0x35,
'escape' : 0x35,
'cmd' : 0x37,
'command' : 0x37,
'shift' : 0x38,
'caps lock' : 0x39,
'option' : 0x3A,
'ctrl' : 0x3B,
'control' : 0x3B,
'right shift' : 0x3C,
'rshift' : 0x3C,
'right option' : 0x3D,
'roption' : 0x3D,
'right control' : 0x3E,
'rcontrol' : 0x3E,
'fun' : 0x3F,
'function' : 0x3F,
'f17' : 0x40,
'volume up' : 0x48,
'volume down' : 0x49,
'mute' : 0x4A,
'f18' : 0x4F,
'f19' : 0x50,
'f20' : 0x5A,
'f5' : 0x60,
'f6' : 0x61,
'f7' : 0x62,
'f3' : 0x63,
'f8' : 0x64,
'f9' : 0x65,
'f11' : 0x67,
'f13' : 0x69,
'f16' : 0x6A,
'f14' : 0x6B,
'f10' : 0x6D,
'f12' : 0x6F,
'f15' : 0x71,
'help' : 0x72,
'home' : 0x73,
'pgup' : 0x74,
'page up' : 0x74,
'forward delete' : 0x75,
'f4' : 0x76,
'end' : 0x77,
'f2' : 0x78,
'page down' : 0x79,
'pgdn' : 0x79,
'f1' : 0x7A,
'left' : 0x7B,
'right' : 0x7C,
'down' : 0x7D,
'up' : 0x7E
}
Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.
If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.
Sample code to set the rightbutton
on a NavigationBar
.
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Title"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[bar pushNavigationItem:item animated:NO];
But normally you would have a NavigationController
, enabling you to write:
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;
Careful - append()
will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>')
.
Use text()
to replace element content with text, or append(document.createTextNode(x))
to append a text node.
If you were to use the C library then this could be done:
time_t t;
struct tm * timeinfo;
time (&t);
timeinfo = localtime (&t);
NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);
And using Swift:
var t = time_t()
time(&t)
let x = localtime(&t)
println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")
For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/
Normal text editors are nano
, or vi
.
For example:
root@user:# nano galfit.feedme
or
root@user:# vi galfit.feedme
Oh I almost forgot. Here are a few more Ruby screencast resources:
SD Ruby - the have a bunch of videos online - I found their Rest talks SD9 and SD10 to be among the best of the intros. Other rest talks assume you know everything. These ones are very introductory and to the point.
Obie Fernandez on InfoQ - Restful Rails. I've also read his Rails Way book and found it informative but really long winded and meandering and the quality is a bit inconsistent. I learned a lot from this book but felt it was a bit punishing to have to read through the repetition and irrelevant stuff to get to the good bits.
Netbeans is a nice hand holding IDE that can teach you a lot of language tricks if you have the patience to wait for its tooltips (it is a painfully slow IDE even on a really fast machine) and you can use the IDE to graphically browse through the available generators and stuff like that. Get the latest builds and you even have Rspec test running built in.
Bort is a prebuilt base app with a lot of the standard plugins already plugged in. If you download it and play with it and figure out how it is setup you are about halfway to creating your own full featured apps.
in laravel, artisan is a file under root/protected page
for example,
c:\xampp\htdocs\my_project\protected\artisan
you can view the content of "artisan" file with any text editor, it's a php command syntax
so when we type
php artisan
we tell php to run php script in "artisan" file
for example:
php artisan change
will show the change of current laravel version
to see the other option, just type
php artisan
If calculating with dates summertime will cause often 1 uur more or one hour less than midnight (CEST). This causes 1 day difference when dates return. So the dates have to round to the nearest midnight. So the code will be (ths to jamisOn):
var d = new Date();
if(d.getHours() < 12) {
d.setHours(0,0,0,0); // previous midnight day
} else {
d.setHours(24,0,0,0); // next midnight day
}
You could do the following, without needing CSS...
<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>
Example: https://jsfiddle.net/jord8on/k1zsfqyk/
This solution was PERFECT for my needs! I found this solution here.
Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.
For Rails 5.2.4.1, I had to
app.extend app._routes.named_routes.path_helpers_module
app.whatever_path
Usually, IPython's %time
, %timeit
, %prun
and %lprun
(if one has line_profiler
installed) satisfy my profiling needs quite well. However, a use case for tic-toc
-like functionality arose when I tried to profile calculations that were interactively driven, i.e., by the user's mouse motion in a GUI. I felt like spamming tic
s and toc
s in the sources while testing interactively would be the fastest way to reveal the bottlenecks. I went with Eli Bendersky's Timer
class, but wasn't fully happy, since it required me to change the indentation of my code, which can be inconvenient in some editors and confuses the version control system. Moreover, there may be the need to measure the time between points in different functions, which wouldn't work with the with
statement. After trying lots of Python cleverness, here is the simple solution that I found worked best:
from time import time
_tstart_stack = []
def tic():
_tstart_stack.append(time())
def toc(fmt="Elapsed: %s s"):
print fmt % (time() - _tstart_stack.pop())
Since this works by pushing the starting times on a stack, it will work correctly for multiple levels of tic
s and toc
s. It also allows one to change the format string of the toc
statement to display additional information, which I liked about Eli's Timer
class.
For some reason I got concerned with the overhead of a pure Python implementation, so I tested a C extension module as well:
#include <Python.h>
#include <mach/mach_time.h>
#define MAXDEPTH 100
uint64_t start[MAXDEPTH];
int lvl=0;
static PyObject* tic(PyObject *self, PyObject *args) {
start[lvl++] = mach_absolute_time();
Py_RETURN_NONE;
}
static PyObject* toc(PyObject *self, PyObject *args) {
return PyFloat_FromDouble(
(double)(mach_absolute_time() - start[--lvl]) / 1000000000L);
}
static PyObject* res(PyObject *self, PyObject *args) {
return tic(NULL, NULL), toc(NULL, NULL);
}
static PyMethodDef methods[] = {
{"tic", tic, METH_NOARGS, "Start timer"},
{"toc", toc, METH_NOARGS, "Stop timer"},
{"res", res, METH_NOARGS, "Test timer resolution"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
inittictoc(void) {
Py_InitModule("tictoc", methods);
}
This is for MacOSX, and I have omitted code to check if lvl
is out of bounds for brevity. While tictoc.res()
yields a resolution of about 50 nanoseconds on my system, I found that the jitter of measuring any Python statement is easily in the microsecond range (and much more when used from IPython). At this point, the overhead of the Python implementation becomes negligible, so that it can be used with the same confidence as the C implementation.
I found that the usefulness of the tic-toc
-approach is practically limited to code blocks that take more than 10 microseconds to execute. Below that, averaging strategies like in timeit
are required to get a faithful measurement.
Try this:
CREATE TABLE SCHEMA.NEW_TB LIKE SCHEMA.OLD_TB;
INSERT INTO SCHEMA.NEW_TB (SELECT * FROM SCHEMA.OLD_TB);
Options that are not copied include:
You can try this also:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
Using LINQ your query should look something like this:
public User GetUser(int userID){
return
(
from p in "MyTable" //(Your Entity Model)
where p.UserID == userID
select p.Name
).SingleOrDefault();
}
Of course to do this you need to have an ADO.Net Entity Model in your solution.
The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx
$diff = strtotime('2019-11-25') - strtotime('2019-11-10');
echo abs(round($diff / 86400));
I had a similar problem. The fontsquirel demo page was working in FF but not my own page even though all files were coming from the same domain!
It turned out that I was linking my stylesheet with an absolute URL (http://example.com/style.css) so FF thought it was coming from a different domain. Changing my stylesheet link href to /style.css instead fixed things for me.
No, you cannot. But you can create a user defined table function.
Also you can only set mediaPlayer.reset()
and in onDestroy
set it to release.
Instead of hiding each element, you can hide the whole axis:
frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)
Or, you can set the ticks to an empty list:
frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])
In this second option, you can still use plt.xlabel()
and plt.ylabel()
to add labels to the axes.
In addition to already suggested p
and puts
— well, actually in most cases you do can write logger.info "blah"
just as you suggested yourself. It works in console too, not only in server mode.
But if all you want is console debugging, puts
and p
are much shorter to write, anyway.
You can use window.scrollTo()
, like this:
window.scrollTo(0, 0); // values are x,y-offset
I reckon your aspx page doesn't return a JSON object. Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus
should give you the type of error you're getting.
Use the @RequestParam to pass a parameter to the controller handler method.
In the jsp your form should have an input field with name = "id"
like the following:
<input type="text" name="id" />
<input type="submit" />
Then in your controller, your handler method should be like the following:
@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
return "note";
}
Please also refer to these answers and tutorial:
Building on @tmullaney 's answer, you can also left join in the sys.objects view to get insight when explicit permissions have been granted on objects. Make sure to use the LEFT join:
SELECT DISTINCT pr.principal_id, pr.name AS [UserName], pr.type_desc AS [User_or_Role], pr.authentication_type_desc AS [Auth_Type], pe.state_desc,
pe.permission_name, pe.class_desc, o.[name] AS 'Object'
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
LEFT JOIN sys.objects AS o on (o.object_id = pe.major_id)
There is Array.filter()
:
var numbers = [1, 2, 3, 4, 5];
var filtered = numbers.filter(function(x) { return x > 3; });
// As a JavaScript 1.8 expression closure
filtered = numbers.filter(function(x) x > 3);
Note that Array.filter()
is not standard ECMAScript, and it does not appear in ECMAScript specs older than ES5 (thanks Yi Jiang and jAndy). As such, it may not be supported by other ECMAScript dialects like JScript (on MSIE).
Nov 2020 Update: Array.filter is now supported across all major browsers.
I know the question is old and was answered correctly in few different ways but there is no answer as mine which I have used in similar situations. First approach (very basic):
IF (1=0)
BEGIN
PRINT 'it will not go there'
-- your script here
END
PRINT 'but it will here'
Second approach:
PRINT 'stop here'
RETURN
-- your script here
PRINT 'it will not go there'
You can test it easily by yourself to make sure it behave as expected.
Try using WGET
:
WGET 'http://localhost/index.php?a=1&b=2&c=3'
SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
//ul[@class="featureList" and li//text()[contains(., "Model")]]
Another alternative, Proxool, is mentioned in this article.
You might be able to find out why Hibernate bundles c3p0 for its default connection pool implementation?
kubectl -n <namespace-name> describe pod <pod name>
kubectl -n <namespace-name> logs -p <pod name>
I know it's an old thread, but I got into this once again with Oracle 12c and LD_LIBRARY_PATH has been set correctly.
I have used strace
to see what exactly it was looking for and why it failed:
strace sqlplus /nolog
sqlplus tries to load this lib from different dirs, some didn't exist in my install. Then it tried the one I already had on my LD_LIBRARY_PATH:
open("/oracle/product/12.1.0/db_1/lib/libsqlplus.so", O_RDONLY) = -1 EACCES (Permission denied)
So in my case the lib had 740 permissions, and since my user wasn't an owner or didn't have oracle group assigned I couldn't read it. So simple chmod +r
helped.
For *Unix based systems, you can check the ports used by a particular application by issueing the following command in the terminal
[~/.]$ netstat -tuplen
You will get the list of all the ports that are being currently held and used by their respective process ID's
I used: "\n\r" - it only works in double quotes though.
var fvalue = "foo";
var svalue = "bar";
alert("My first value is: " + fvalue + "\n\rMy second value is: " + svalue);
will alert as:
My first value is: foo
My second value is: bar
No, you don't it's enough to do something like this:
<ul class="clearfix">
<li>one</li>
<li>two></li>
</ul>
And the following CSS:
ul li {float: left;}
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
}
Before answering your question:
If you do not have a Person
class, first you must consider whether you want to create a Person
class. Do you plan to reuse the concept of a Person
very often? If so, you should create a Person
class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)
To answer your question:
You have access to their birthyear, so in that case you likely have a Person
class with a someperson.birthdate
field. In that case, you have to ask yourself, is someperson.age
a value that is reusable?
The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale
or someperson.positionToDisplayInGrid
or other irrelevant values, we would not extend the Person
class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData
or something).)
The best solution I've found was:
https://github.com/angular/angular-cli/issues/5139#issuecomment-283634059
Basically, you need to include a dummy variable on typings.d.ts, remove any "import * as $ from 'jquery" from your code, and then manually add a tag to jQuery script to your SPA html. This way, webpack won't be in your way, and you should be able to access the same global jQuery variable in all your scripts.
I had the same problem, but believe it or not is was a case of case sensitivity.
This on localhost: http://localhost/.../getdata.php?id=3
Did not behave the same as this on the server: http://server/.../getdata.php?id=3
Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3
A portable solution could use getc
.
#include <stdio.h>
char buffer[MAX_FILE_SIZE];
size_t i;
for (i = 0; i < MAX_FILE_SIZE; ++i)
{
int c = getc(fp);
if (c == EOF)
{
buffer[i] = 0x00;
break;
}
buffer[i] = c;
}
If you don't want to have a MAX_FILE_SIZE
macro or if it is a big number (such that buffer
would be to big to fit on the stack), use dynamic allocation.
TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".
So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.
In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".
It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.
Let's rephrase your question to this:
The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.
To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).
The following is an introduction/overview, but you might find this excellent article also informative.
WHAT GIT IS, AND WHAT IT'S FOR
A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.
A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.
The basic idea is to create a book so we can easily look backwards in time,
When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.
SNAPSHOTS AND TRACKING
tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)
In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.
Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.
Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.
One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.
For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.
This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.
COMMITS
A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:
A commit is the most important part of a well organized photo album.
THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES
Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.
The git family tree structure is modeled on our own, human family trees.
In what follows to help understand links in a simple way, I'll refer to:
You should understand this instinctively, as it is based on the tree of life:
Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.
With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.
With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.
Line diagram of a simple, single parent chain linking backwards in time:
(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)
BRANCHES
branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)
A git branch also refers to two things:
More than one child pointing --at a--> parent, is what git calls "branching".
NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.
The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".
In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.
Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)
ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.
The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)
(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)
So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".
So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.
The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".
The master branch always exists.
Line diagram of: Commit1 with 2 children (or what we call a git "branch"):
parent children
+-- Commit <-- Commit <-- Commit (Branch named 'Tom')
/
v
(older) ... <-- Commit1 <-- Commit (Branch named 'master')
Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.
So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.
MERGING
Children have one or more parents.
With just one parent this is just a simple parent <-- child commit.
With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.
Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):
parents child
... <-- Commit
v
\
(older) ... <-- Commit1 <-- Commit2
REMOTE
This word is also used to mean 2 different things:
remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)
(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.
A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)
You can setup multiple remotes if you want to pull or push to multiple remote repositories.
Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).
origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)
Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.
upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia
upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)
This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.
REMOTE TRACKING BRANCH
A remote-tracking-branch is first, just a branch name, like any other branch name.
It points at a local growing tip, i.e. a recent commit in your local git repository.
But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.
remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)
Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.
Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.
TRACKING IN ACTION
First we begin tracking a file with git.
Here are the basic commands involved with file tracking:
$ mkdir mydir && cd mydir && git init # create a new git repository
$ git branch # this initially reports no branches
# (IMHO this is a bug!)
$ git status -bs # -b = branch; -s = short # master branch is empty
## No commits yet on master
# ...
$ touch foo # create a new file
$ vim foo # modify it (OPTIONAL)
$ git add foo; commit -m 'your description' # start tracking foo
$ git rm --index foo; commit -m 'your description' # stop tracking foo
$ git rm foo; commit -m 'your description' # stop tracking foo & also delete foo
REMOTE TRACKING IN ACTION
$ git pull # Essentially does: get fetch; git merge # to update our clone
There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error:
callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json'
row.
There is a dirty trick, what I have used:
I am using bootstrap, so I just added .disabled
class to the element which I want to disable. Bootstrap handles the rest of the things.
Suggestion are heartily welcome towards this.
Adding class on run time:
$('#element').addClass('disabled');
This helper method should come in handy for someone. Example: int actionBarSize = getThemeAttributeDimensionSize(this, android.R.attr.actionBarSize);
public static int getThemeAttributeDimensionSize(Context context, int attr)
{
TypedArray a = null;
try{
a = context.getTheme().obtainStyledAttributes(new int[] { attr });
return a.getDimensionPixelSize(0, 0);
}finally{
if(a != null){
a.recycle();
}
}
}
Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)
select state, count(*) from pg_stat_activity where pid <> pg_backend_pid() group by 1 order by 1;
<button backButton>BACK</button>
You can put this into a directive, that can be attached to any clickable element:
import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common';
@Directive({
selector: '[backButton]'
})
export class BackButtonDirective {
constructor(private location: Location) { }
@HostListener('click')
onClick() {
this.location.back();
}
}
Usage:
<button backButton>BACK</button>
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.
Some possible alternatives:
Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.
Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.
Here is a minimal, contrived example.
console.log( window.location.href ); // whatever your current location href is
window.history.replaceState( {} , 'foo', '/foo' );
console.log( window.location.href ); // oh, hey, it replaced the path with /foo
There is more to replaceState()
but I don't know what exactly it is that you want to do with it.
I removed the text-transform: uppercase;
and then set it to bold
/bolder
, and this seemed to work.
This means you are using JPA or hibernate in your code and performing modifying operation on DB without making the business logic transaction. So simple solution for this is mark your piece of code @Transactional
If you are actually running into a performance problem I would suggest wrapping the calls that add/remove properties to/from the object with a function that also increments/decrements an appropriately named (size?) property.
You only need to calculate the initial number of properties once and move on from there. If there isn't an actual performance problem, don't bother. Just wrap that bit of code in a function getNumberOfProperties(object)
and be done with it.
Use:
columns = ['Col1', 'Col2', ...]
df.drop(columns, inplace=True, axis=1)
This will delete one or more columns in-place. Note that inplace=True
was added in pandas v0.13 and won't work on older versions. You'd have to assign the result back in that case:
df = df.drop(columns, axis=1)
To run the python file on mac.
Click on the install in the preferences to install packages.
Search for package "script" and click on install
Now open the python file(with .py extension ) you want to run and press 'control + r ' (^ + r)
The one that is mark as the solution is the better solution I been found until today, but has a serious problem with 0 (for example, 0.toFixedDown(2) gives -0.01). So I suggest to use this:
Number.prototype.toFixedDown = function(digits) {
if(this == 0) {
return 0;
}
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
in C, unsigned
is a shortcut for unsigned int
.
You have the same for long
that is a shortcut for long int
And it is also possible to declare a unsigned long
(it will be a unsigned long int
).
This is in the ANSI standard
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Microsoft announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.
After the release of the .NET Framework 4, Microsoft released a set of enhancements, named Windows Server AppFabric, for application server capabilities in the form of AppFabric Hosting and in-memory distributed caching support.
.NET Framework 4.5 was released on 15 August 2012., a set of new or improved features were added into this version. The .NET Framework 4.5 is only supported on Windows Vista or later. The .NET Framework 4.5 uses Common Language Runtime 4.0, with some additional runtime features.
Metro-style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows 8 using C# or Visual Basic. This subset is called .NET APIs for apps. The version of .NET Framework, runtime and libraries, used for Metro style apps is a part of the new Windows Runtime, which is the new platform and application model for Metro style apps. It is an ecosystem that houses many platforms and languages, including .NET Framework, C++ and HTML5/JavaScript.
In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.
In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:
For more information and access to reference links, please visit:
===========.Net 4.5 Poster=========
static
A member declared with the keyword 'static'.
factory methods
Methods that create and return new objects.
in Java
The programming language is relevant to the meaning of 'static' but not to the definition of 'factory'.
Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.
I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.
--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.
' **row** **Column1** **Column2**
' 1 Title1 Data 1 for title 1
' 2 Data 2 for title 1
' 3 Data 3 for title 1
' 4 Title2 Data 1 for title 2
' 5 Data 2 for title 2
' 6 Data 3 for title 2
' 7 Title 3 Data 1 for title 3
----- CopyDown code ----------
Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.
'
' Keyboard Shortcut: Ctrl+Shift+D
'
Set strtCell = ActiveCell
FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
' MsgBox Lastrow
Range(Lastrow).Formula = strtCell.Formula
Range(Lastrow).End(xlDown).Select
End Sub
Assuming the objects in your source array have an id property...
var $local_source = [
{ id: 1, value: "c++" },
{ id: 2, value: "java" },
{ id: 3, value: "php" },
{ id: 4, value: "coldfusion" },
{ id: 5, value: "javascript" },
{ id: 6, value: "asp" },
{ id: 7, value: "ruby" }];
Getting hold of the current instance and inspecting its selectedItem property will allow you to retrieve the properties of the currently selceted item. In this case alerting the id of the selected item.
$('#button').click(function() {
alert($("#txtAllowSearch").autocomplete("instance").selectedItem.id;
});
while (true)
{
Thread.Sleep(60 * 5 * 1000);
Console.WriteLine("*** calling MyMethod *** ");
MyMethod();
}
You can do it with something like this, so if no arguments are specified it will continue anyway:
public static void main(String[] args) {
try {
String one = args[0];
String two = args[1];
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException caught");
}
finally {
}
}
And then launch the application:
java -jar myapp.jar arg1 arg2
The following CSS changes in bold (plus a bunch of content in the columns to test scrolling) will work. See the result in this Pen.
.content { flex: 1; display: flex; height: 1px; }
.column { padding: 20px; border-right: 1px solid #999; overflow: auto; }
The trick seems to be that a scrollable panel needs to have a height
literally set somewhere (in this case, via its parent), not just determined by flexbox. So even height: 1px
works. The flex-grow:1
will still size the panel to fit properly.
SQLite is created in your python directory where you installed the python.
For there to be a Smart Cast of the properties, the data type of the property must be the class that contains the method or behavior that you want to access and NOT that the property is of the type of the super class.
Be:
class MyVM : ViewModel() {
fun onClick() {}
}
Solution:
From: private lateinit var viewModel: ViewModel
To: private lateinit var viewModel: MyVM
Usage:
viewModel = ViewModelProvider(this)[MyVM::class.java]
viewModel.onClick {}
GL
Here is what i did and it works.
I just used a stringified object.
$scope.thread = [
{
mostRecent:{text:'hello world',timeStamp:12345678 }
allMessages:[]
}
{MoreThreads...}
{etc....}
]
<div ng-repeat="message in thread | orderBy : '-mostRecent.timeStamp'" >
if i wanted to sort by text i would do
orderBy : 'mostRecent.text'
I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open
, then open
has to be wrapped in a try
. If the call to open
is in the header of a with
, then the with
has to be in a try
to catch the exception. There's no way around that.
So the answer is either: "Tim's way" or "No, you're doing it correctly.".
Previous unhelpful answer to which all the comments refer:
import os
if os.path.exists(fName):
with open(fName, 'rb') as f:
try:
# do stuff
except : # whatever reader errors you care about
# handle error
UPDATE just use the new way from @cminatti
old answer for historic purposes
IMO it's better to use select() and on() since that way you can have multiple resize event handlers... just don't get too crazy
d3.select(window).on('resize', resize);
function resize() {
// update width
width = parseInt(d3.select('#chart').style('width'), 10);
width = width - margin.left - margin.right;
// resize the chart
x.range([0, width]);
d3.select(chart.node().parentNode)
.style('height', (y.rangeExtent()[1] + margin.top + margin.bottom) + 'px')
.style('width', (width + margin.left + margin.right) + 'px');
chart.selectAll('rect.background')
.attr('width', width);
chart.selectAll('rect.percent')
.attr('width', function(d) { return x(d.percent); });
// update median ticks
var median = d3.median(chart.selectAll('.bar').data(),
function(d) { return d.percent; });
chart.selectAll('line.median')
.attr('x1', x(median))
.attr('x2', x(median));
// update axes
chart.select('.x.axis.top').call(xAxis.orient('top'));
chart.select('.x.axis.bottom').call(xAxis.orient('bottom'));
}
http://eyeseast.github.io/visible-data/2013/08/28/responsive-charts-with-d3/
Use \1
instead of $1
.
\number Matches the contents of the group of the same number.
http://docs.python.org/library/re.html#regular-expression-syntax
Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}
private static long ConvertStringToDate(String dateString, String format) {
try {
return new SimpleDateFormat(format).parse(dateString).getTime();
} catch (ParseException e) {}
return 0;
}
protected void btnUpload_Click(object sender, EventArgs e)
{
divStatusMsg.Style.Add("display", "none");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "";
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
{
GetExcelSheetForEmployeeCode(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";
}
}
}
}
private void GetExcelSheetForEmployeeCode(string filename)
{
int count = 0;
int selectedcheckbox = 0;
string empcodeexcel = "";
string empcodegrid = "";
string excelFile = "Employee/DateExcel" + filename;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet ds = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
// Create connection.
objConn = new OleDbConnection(connString);
// Opens connection with the database.
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
// Get the data table containing the schema guid, and also sheet names.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
if (ds.Tables[0].ToString() != null)
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
for (int k = 0; k < GrdEmplist.Rows.Count; k++)
{
empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
date.Value = ds.Tables[0].Rows[j][1].ToString();
Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
empcodegrid = lbl_Code.Text;
CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");
if ((empcodegrid == empcodeexcel) && (date.Value != ""))
{
chk.Checked = true;
txt_Sal.Text = date.Value;
selectedcheckbox = selectedcheckbox + 1;
lblSelectedRecord.InnerText = selectedcheckbox.ToString();
count++;
}
if (chk.Checked == true)
{
}
}
}
}
}
i++;
}
}
catch (Exception ex)
{
ShowMessage(ex.Message.ToString(), 0);
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
IB and Swift
Given the flowing layout where yellow is the superview and red, green, and blue are sibling subviews of yellow,
the goal is to move a subview (let's say green) to the top.
In the Interface Builder all you need to do is drag the view you want showing on the top to the bottom of the list in the Documents Outline.
Alternatively, you can select the view and then in the menu go to Editor > Arrange > Send to Front.
There are a couple of different ways to do this programmatically.
Method 1
yellowView.bringSubviewToFront(greenView)
This method is the programmatic equivalent of the IB answer above.
It only works if the subviews are siblings of each other.
An array of the subviews is contained in yellowView.subviews
. Here, bringSubviewToFront
moves the greenView
from index 0
to 2
. This can be observed with
print(yellowView.subviews.indexOf(greenView))
Method 2
greenView.layer.zPosition = 1
0
for all the other views, the result is that the greenView
looks like it is on top. However, it still remains at index 0
of the yellowView.subviews
array. This can cause some unexpected results, though, because things like tap events will still go first to the view with the highest index number. For that reason, it might be better to go with Method 1 above.zPosition
could be set to CGFloat.greatestFiniteMagnitude
(CGFloat(FLT_MAX)
in older versions of Swift) to ensure that it is on top.It's actually not too complicated...
Say you're on domain example.com
, and you want to make a request to domain example.net
. To do so, you need to cross domain boundaries, a no-no in most of browserland.
The one item that bypasses this limitation is <script>
tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.
Enter JSONP
. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.
For example, say the server expects a parameter called callback
to enable its JSONP capabilities. Then your request would look like:
http://www.example.net/sample.aspx?callback=mycallback
Without JSONP, this might return some basic JavaScript object, like so:
{ foo: 'bar' }
However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:
mycallback({ foo: 'bar' });
As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:
mycallback = function(data){
alert(data.foo);
};
And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!
It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.
These days (2015), CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.
On the last entry; this is another trick:
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_schema = ... and table_name = ...
PYTHONPATH
only affects import
statements, not the top-level Python interpreter's lookup of python files given as arguments.
Needing PYTHONPATH
to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.
Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.
In Angular2+ for anyone interested:
<input type="text" placeholder="My Date" [ngModel]="myDate | date: 'longDate'">
with type of filters in DatePipe Angular.
In Flask shell, all I needed to do was a session.rollback()
to get past this.