I want to thank the most upvoted answer for giving me the idea of my own problem basically the variation of it with arrow function and passing param from child component:
class Parent extends React.Component {
constructor(props) {
super(props)
// without bind, replaced by arrow func below
}
handler = (val) => {
this.setState({
someVar: val
})
}
render() {
return <Child handler = {this.handler} />
}
}
class Child extends React.Component {
render() {
return <Button onClick = {() => this.props.handler('the passing value')}/ >
}
}
Hope it helps someone.
Here a CSS animation fork of jezzipin's Solution, to seperate code from styling.
JS:
$(window).on("scroll touchmove", function () {
$('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0);
});
CSS:
.header {
width:100%;
height:100px;
background: #26b;
color: #fff;
position:fixed;
top:0;
left:0;
transition: height 500ms, background 500ms;
}
.header.tiny {
height:40px;
background: #aaa;
}
http://jsfiddle.net/sinky/S8Fnq/
On scroll/touchmove the css class "tiny" is set to "#header_nav" if "$(document).scrollTop()" is greater than 0.
CSS transition attribute animates the "height" and "background" attribute nicely.
I had this error because "Rebuild" was not really rebuilding.
Solution: Close Visual Studio, really go and delete the bin folder, then rebuild, it might work better.
Also, sometimes Visual Studio lies about references, so check the HintPath
in your .csproj
files.
Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer
The easiest way to see benefits from this is to look at this example.
Every MVC framework has a Router/Dispatcher
that maps URL-s to actionControllers.
So URL like this: /blog/article/1
would invoke blogController::articleAction($id);
Now this Router is only aware of the URL or /blog/article/1/
But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.
That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.
For example:
if you want to retrive article 1 you can do this:
GET /blog/article/1 HTTP/1.1
but if you want to delete article 1 you will do this:
DELETE /blog/article/1 HTTP/1.1
Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.
Read this two articles, they might help you:
These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.
Hope this helps!
Using MacOS Mojave 10.14.6 for MySQL 8.0.19 installed via Homebrew
sudo find / -name my.cnf
/usr/local/etc/my.cnf
Worked for a time then eventually the error returned. Uninstalled the Homebrew version of MySQL and installed the .dmg file directly from here
Happily connecting since then.
try this to get the box-shadow under your full control.
<html>
<head>
<style>
div {
width:300px;
height:100px;
background-color:yellow;
box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
}
</style>
</head>
<body>
<div>
</div>
</body>
</html>
this would apply to outer box-shadow as well.
First convert it to a string:
var mynumber = 123;
alert((""+mynumber).length);
Adding an empty string to it will implicitly cause mynumber
to turn into a string.
The following fixed my issue, please consider adding radio input inside the form
tag and use the [value]
tag to display the value.
<form name="form" (ngSubmit)="">
<div *ngFor="let item of options">
<input [(ngModel)]="model.option_id" type="radio" name="options" [value]="item.id"> {{ item.name }}
</div>
</form>
arr = np.array([1,2,3,4])
arr[-1] # last element
The most widely compatible way of doing this is likely going to be creating a second div under your auto-suggest box the same size as the box itself, nudged a few pixels down and to the right. You can use JS to create and position it, which shouldn't be terribly difficult if you're using a fairly modern framework.
tmux
instead of screen
as suggested in the original answer below, if you choose to use that solution.:term
command. This provides much more complete integration with the rest of the Vim features.I would definitely recommend screen
for something like this. Vim is a text editor, not a shell.
I would use Ctrl+AS to split the current window horizontally, or in Ubuntu's screen and other patched versions, you can use Ctrl+A|(pipe) to split vertically. Then use Ctrl+ATab (or equivalently on some systems, Ctrl+ACtrl+I which may be easier to type) to switch between the windows. There are other commands to change the size and arrangement of the windows.
Or a less advanced use of screen
is just to open multiple full-screen windows and toggle between them. This is what I normally do, I only use the split screen feature occasionally.
The GNU Screen Survival Guide question has a number of good tips if you're unfamiliar with its use.
Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Even if WHERE textcolumn LIKE "%SUBSTRING%"
is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).
If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")
There isn't any need to write this much. Just put your desired field separator with the -F
option in the AWK command and the column number you want to print segregated as per your mentioned field separator.
echo "1: " | awk -F: '{print $1}'
1
echo "1#2" | awk -F# '{print $1}'
1
Loop like
foreach (GridViewRow row in grid.Rows)
{
if (((CheckBox)row.FindControl("chkboxid")).Checked)
{
//read the label
}
}
In my application I was checking if device is rooted or not by executing "su" command. But today I've removed this part of my code. Why?
Because my application became a memory killer. How? Let me tell you my story.
There were some complaints that my application was slowing down devices(Of course I thought that can not be true). I tried to figure out why. So I used MAT to get heap dumps and analyze, and everything seemed perfect. But after relaunching my app many times I realized that device is really getting slower and stopping my application didn't make it faster (unless I restart device). I analyzed dump files again while device is very slow. But everything was still perfect for dump file. Then I did what must be done at first. I listed processes.
$ adb shell ps
Surprize; there were many processes for my application (with my application's process tag at manifest). Some of them was zombie some of them not.
With a sample application which has a single Activity and executes just "su" command, I realized that a zombie process is being created on every launch of application. At first these zombies allocate 0KB but than something happens and zombie processes are holding nearly same KBs as my application's main process and they became standart processes.
There is a bug report for same issue on bugs.sun.com: http://bugs.sun.com/view_bug.do?bug_id=6474073 this explains if command is not found zombies are going to be created with exec() method. But I still don't understand why and how can they become standart processes and hold significant KBs. (This is not happening all the time)
You can try if you want with code sample below;
String commandToExecute = "su";
executeShellCommand(commandToExecute);
Simple command execution method;
private boolean executeShellCommand(String command){
Process process = null;
try{
process = Runtime.getRuntime().exec(command);
return true;
} catch (Exception e) {
return false;
} finally{
if(process != null){
try{
process.destroy();
}catch (Exception e) {
}
}
}
}
To sum up; I have no advice for you to determine if device is rooted or not. But if I were you I would not use Runtime.getRuntime().exec().
By the way; RootTools.isRootAvailable() causes same problem.
It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..
in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library
follow this tutorial in the docs
http://developer.android.com/tools/support-library/setup.html
if you're using reactive forms then you can use the following way. consider the following example.
`<p class="mr-3"> Require Shipping:
<input type="radio" class="ml-2" value="true" name="requiresShipping"
id="requiresShipping" formControlName="requiresShipping">
Yes
<input type="radio" class="ml-2" value="false" name="requiresShipping"
id="requiresShipping" formControlName="requiresShipping">
No
</p>`
`
export class ClassName implements OnInit {
public yourForm: FormGroup
constructor(
private fromBuilder: FormBuilder
) {
this.yourForm= this.fromBuilder.group({
requiresShipping: this.fromBuilder.control('true'),
})
}
}
`
now you will get the default selected radio button.
I have found a solution that works fine for nested model and array using native JavaScript functions.
var results = [{},{},...]; //your result data returned from sequelize query
var jsonString = JSON.stringify(results); //convert to string to remove the sequelize specific meta data
var obj = JSON.parse(jsonString); //to make plain json
// do whatever you want to do with obj as plain json
Who is Jon Skeet?
DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.
An informational message is displayed if there are no active transactions in the log.
This is an old question, but the current answers are incorrect :)
Use yum whatprovides, with the absolute path to the file you want (which may be wildcarded). For example:
yum whatprovides '*bin/grep'
Returns
grep-2.5.1-55.el5.x86_64 : The GNU versions of grep pattern matching utilities.
Repo : base
Matched from:
Filename : /bin/grep
You may prefer the output and speed of the repoquery
tool, available in the yum-utils
package.
sudo yum install yum-utils
repoquery --whatprovides '*bin/grep'
grep-0:2.5.1-55.el5.x86_64
grep-0:2.5.1-55.el5.x86_64
repoquery
can do other queries such as listing package contents, dependencies, reverse-dependencies, etc.
To iterate through the keys of an object, use a for .. in
loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
Removing a property of an object can be done by using the delete
keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
The following is works best in my opinion:
Get-Item Env:PATH
Get-ChildItem
. There's no hierarchy with environment variables.Set-Item -Path env:SomeVariable -Value "Some Value"
)Get-Item Env:
)I found the syntax odd at first, but things started making more sense after I understood the notion of Providers. Essentially PowerShell let's you navigate disparate components of the system in a way that's analogous to a file system.
What's the point of the trailing colon in Env:
? Try listing all of the "drives" available through Providers like this:
PS> Get-PSDrive
I only see a few results... (Alias, C, Cert, D, Env, Function, HKCU, HKLM, Variable, WSMan). It becomes obvious that Env
is simply another "drive" and the colon is a familiar syntax to anyone who's worked in Windows.
You can navigate the drives and pick out specific values:
Get-ChildItem C:\Windows
Get-Item C:
Get-Item Env:
Get-Item HKLM:
Get-ChildItem HKLM:SYSTEM
Here's an extension to Tony's extension... :-)
For Entity Framework 4.x, if you want to get the name and value of the key field so that you know which entity instance (DB record) has the problem, you can add the following. This provides access to the more powerful ObjectContext class members from your DbContext object.
// Get the key field name & value.
// This assumes your DbContext object is "_context", and that it is a single part key.
var e = ((IObjectContextAdapter)_context).ObjectContext.ObjectStateManager.GetObjectStateEntry(validationErrors.Entry.Entity);
string key = e.EntityKey.EntityKeyValues[0].Key;
string val = e.EntityKey.EntityKeyValues[0].Value;
It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)
This should work:
%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)
%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)
Above solutions will work only if its a string. Input type date, gives you output in javascript date object in some cases like if you use angular or so. That's why some people are getting error like "TypeError: str.split is not a function". It's a date object, so you should use functions of Date object in javascript to manipulate it. Example here:
var date = $scope.dateObj ;
//dateObj is data bind to the ng-modal of input type dat.
console.log(date.getFullYear()); //this will give you full year eg : 1990
console.log(date.getDate()); //gives you the date from 1 to 31
console.log(date.getMonth() + 1); //getMonth will give month from 0 to 11
Check the following link for reference:
Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:
SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc,
pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
ON pe.grantee_principal_id = pr.principal_id;
Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.
After playing with the timeit
module, I don't like its interface, which is not so elegant compared to the following two method.
The following code is in Python 3.
This is almost the same with @Mike's method. Here I add kwargs
and functools
wrap to make it better.
def timeit(func):
@functools.wraps(func)
def newfunc(*args, **kwargs):
startTime = time.time()
func(*args, **kwargs)
elapsedTime = time.time() - startTime
print('function [{}] finished in {} ms'.format(
func.__name__, int(elapsedTime * 1000)))
return newfunc
@timeit
def foobar():
mike = Person()
mike.think(30)
from contextlib import contextmanager
@contextmanager
def timeit_context(name):
startTime = time.time()
yield
elapsedTime = time.time() - startTime
print('[{}] finished in {} ms'.format(name, int(elapsedTime * 1000)))
For example, you can use it like:
with timeit_context('My profiling code'):
mike = Person()
mike.think()
And the code within the with
block will be timed.
Using the first method, you can eaily comment out the decorator to get the normal code. However, it can only time a function. If you have some part of code that you don't what to make it a function, then you can choose the second method.
For example, now you have
images = get_images()
bigImage = ImagePacker.pack(images, width=4096)
drawer.draw(bigImage)
Now you want to time the bigImage = ...
line. If you change it to a function, it will be:
images = get_images()
bitImage = None
@timeit
def foobar():
nonlocal bigImage
bigImage = ImagePacker.pack(images, width=4096)
drawer.draw(bigImage)
Looks not so great...What if you are in Python 2, which has no nonlocal
keyword.
Instead, using the second method fits here very well:
images = get_images()
with timeit_context('foobar'):
bigImage = ImagePacker.pack(images, width=4096)
drawer.draw(bigImage)
I ran into this error when attempting to install 12c 32x client on Windows 10. "net use \\localhost\c$"
worked, but when I substituted "localhost" the computer's "name" (e.g., \\my-computer\c$
), I got the "System error 53 ...
". Oracle seems to prefer the computer's name.
What fixed it: we temporarily disabled the IPv6 protocol for the computer (our network uses IPv4). How to do this: Control Panel --> Network and Sharing Center --> Change adapter settings --> right click on Ethernet Connection --> Properties --> uncheck "Internet Protocol Version 6 (TCP/IPv6) --> OK. That should disable it. After that, \\my-computer\c$
ran successfully in the command prompt. Then the Oracle installer finally completed and we were able to tnsping the database server.
Just to test it out, we re-enabled IPv6 and restarted the computer. \\my-computer\c$
failed in the cmd prompt, but tnsping still functioned correctly.
I hope this helps somebody in the future.
May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..
JSON.parse("\"'\"")
It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga
faulthandler.enable()
// bad code goes here
or
$ python3 -q -X faulthandler
>>> /// bad cod goes here
I think that's better to use flex boxes (compatibility) than the absolute position. Here's example from me in pure css.
.container{_x000D_
background-color:green;_x000D_
height:500px;_x000D_
_x000D_
/*FLEX BOX */_x000D_
display: -ms-flexbox;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-direction: column;_x000D_
-ms-flex-direction: column;_x000D_
flex-direction: column;_x000D_
-webkit-flex-wrap: nowrap;_x000D_
-ms-flex-wrap: nowrap;_x000D_
flex-wrap: nowrap;_x000D_
-webkit-justify-content: flex-start;_x000D_
-ms-flex-pack: start;_x000D_
justify-content: flex-start;_x000D_
-webkit-align-content: stretch;_x000D_
-ms-flex-line-pack: stretch;_x000D_
align-content: stretch;_x000D_
-webkit-align-items: flex-start;_x000D_
-ms-flex-align: start;_x000D_
align-items: flex-start;_x000D_
}_x000D_
_x000D_
.elem1{_x000D_
background-color:red;_x000D_
padding:20px;_x000D_
_x000D_
/*FLEX BOX CHILD */_x000D_
-webkit-order: 0;_x000D_
-ms-flex-order: 0;_x000D_
order: 0;_x000D_
-webkit-flex: 0 1 auto;_x000D_
-ms-flex: 0 1 auto;_x000D_
flex: 0 1 auto;_x000D_
-webkit-align-self: flex-end;_x000D_
-ms-flex-item-align: end;_x000D_
align-self: flex-end;_x000D_
_x000D_
}
_x000D_
<div class="container">_x000D_
TOP OF CONTAINER _x000D_
<div class="elem1">_x000D_
Nam pretium turpis et arcu. Sed a libero. Sed mollis, eros et ultrices tempus, mauris ipsum aliquam libero, non adipiscing dolor urna a orci._x000D_
_x000D_
Mauris sollicitudin fermentum libero. Pellentesque libero tortor, tincidunt et, tincidunt eget, semper nec, quam. Quisque id mi._x000D_
_x000D_
Donec venenatis vulputate lorem. Maecenas ullamcorper, dui et placerat feugiat, eros pede varius nisi, condimentum viverra felis nunc et lorem. Curabitur vestibulum aliquam leo._x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Some Theory
$
is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $
as shown below:
$ = function() {
alert('I am in the $ function');
}
JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery
. To make it easier for people to use the framework and reduce typing the whole word jQuery
every single time they want to call the function, they have also created an alias for it. That alias is $
. Therefore $
is the name of a function. Within the jQuery source code, you can see this yourself:
window.jQuery = window.$ = jQuery;
Answer To Your Question
So what is $(function() { });?
Now that you know that $
is the name of the function, if you are using the jQuery library, then you are calling the function named $
and passing the argument function() {}
into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.
The other way to accomplish this is like this:
$(document).ready(function() { });
As you can see this is more verbose so people prefer $(function() { })
So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $
as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.
Another way to interpret $(function() { })
is like this:
Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?
You could use the Chr(int) function
So easy we can get the String from files by method: getText();
public class Main {
static int countOfWords(String str) {
if (str.equals("") || str == null) {
return 0;
}else{
int numberWords = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
numberWords++;
}
}
return ++numberWordss;
}
}
}
Simplest answer is to put another condition '.xml' == strtolower(substr($file, -3))
.
But I'd recommend using glob
instead too.
Much of the time when you ask for a dynamic object, you get an ExpandoObject (not in the question's anonymous-but-statically-typed example above, but you mention JavaScript and my chosen JSON parser JsonFx, for one, generates ExpandoObjects).
If your dynamic is in fact an ExpandoObject, you can avoid reflection by casting it to IDictionary, as described at http://msdn.microsoft.com/en-gb/library/system.dynamic.expandoobject.aspx.
Once you've cast to IDictionary, you have access to useful methods like .Item and .ContainsKey
Return false from the anonymous function:
$(xml).find("strengths").each(function() {
// Code
// To escape from this block based on a condition:
if (something) return false;
});
From the documentation of the each method:
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).
Done it, by a bit of creative programming,
Enum the Keys in HKEY_USERS for those funny number keys...
Enum the keys in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\
and you will find the same numbers.... Now in those keys look at the String value: ProfileImagePath = "SomeValue" where the values are either:
"%systemroot%\system32\config\systemprofile"... not interested in this one... as its not a directory path...
%SystemDrive%\Documents and Settings\LocalService - "Local Services" %SystemDrive%\Documents and Settings\NetworkService "NETWORK SERVICE"
or
%SystemDrive%\Documents and Settings\USER_NAME, which translates directly to the "USERNAME" values in most un-tampered systems, ie. where the user has not changed the their user name after a few weeks or altered the paths explicitly...
You are correct that the GPL is more restrictive than the MIT license.
You cannot include GPL code in a MIT licensed product. If you distribute a combined work that combines GPL and MIT code (except in some particular situations, e.g. 'mere aggregation'), that distribution must be compliant with the GPL.
You can include MIT licensed code in a GPL product. The whole combined work must be distributed in a way compliant with the GPL. If you have made changes to the MIT parts of the code, you would be required to publish the source for those changes if you distribute an application that contains GPL and MIT code.
If you are the copyright owner of the GPL code, you can of course choose to release that code under the MIT license instead - in that case it's your code and you can publish it under as many licenses as you want.
The standard library arrays are useful for binary I/O, such as translating a list of ints to a string to write to, say, a wave file. That said, as many have already noted, if you're going to do any real work then you should consider using NumPy.
Guidelines from MSDN: Using decimal, float, and real Data
The default maximum precision of numeric and decimal data types is 38. In Transact-SQL, numeric is functionally equivalent to the decimal data type. Use the decimal data type to store numbers with decimals when the data values must be stored exactly as specified.
The behavior of float and real follows the IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types. Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.
Rather than silencing the warnings, gcc style is usually to use either standard C constructs or the __attribute__
extension to tell the compiler more about your intention. For instance, the warning about assignment used as a condition is suppressed by putting the assignment in parentheses, i.e. if ((p=malloc(cnt)))
instead of if (p=malloc(cnt))
. Warnings about unused function arguments can be suppressed by some odd __attribute__
I can never remember, or by self-assignment, etc. But generally I prefer just globally disabling any warning option that generates warnings for things that will occur in correct code.
If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.
In my case, the issue was simply that I was trying to access the site at
myserver.myintranet.com/mysite
But the web site binding for http in IIS didn't have the host name specified in the binding. It had worked before and I have no idea how that got blown away.
Once I put myserver.myintranet.com
into the host name the 404 was gone.
In IIS Manager you go into Bindings... in the actions pane, then edit the http binding to specify the host name.
axios.get
accepts a request config as the second parameter (not query string params).
You can use the params
config option to set query string params as follows:
axios.get('/api', {
params: {
foo: 'bar'
}
});
copying Superfly Jon's comment into an answer:
To create a new branch without committing on master
, you can use:
git checkout -b <branchname>
Keeping the element's size relative to its content can also be done with display: inline-flex
and display: table
The centering can be done with..
text-align: center;
on the parent (or above, it's inherited)
display: flex;
and justify-content: center;
on the parent
position: absolute;
left: 50%;
transform: translateX(-50%);
on
the element with position: relative; (at least) on the parent.
Here's a flexbox guide from CSS Tricks
Here's an article on centering from CSS Tricks.
Keeping an element only as wide as its content..
Can use display: table;
Or inline-anything including inline-flex
as used in my snippet
example below.
Keep in mind that when centering with flexbox's justify-content: center;
when the text wraps the text will align left. So you will still need text-align: center;
if your site is responsive and you expect lines to wrap.
body {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
padding: 20px;_x000D_
}_x000D_
.container {_x000D_
display: flex;_x000D_
justify-content: center; /* center horizontally */_x000D_
align-items: center; /* center vertically */_x000D_
height: 50%;_x000D_
}_x000D_
.container.c1 {_x000D_
text-align: center; /* needed if the text wraps */_x000D_
/* text-align is inherited, it can be put on the parent or the target element */_x000D_
}_x000D_
.container.c2 {_x000D_
/* without text-align: center; */_x000D_
}_x000D_
.button {_x000D_
padding: 5px 10px;_x000D_
font-size: 30px;_x000D_
text-decoration: none;_x000D_
color: hsla(0, 0%, 90%, 1);_x000D_
background: linear-gradient(hsla(21, 85%, 51%, 1), hsla(21, 85%, 61%, 1));_x000D_
border-radius: 10px;_x000D_
box-shadow: 2px 2px 15px -5px hsla(0, 0%, 0%, 1);_x000D_
}_x000D_
.button:hover {_x000D_
background: linear-gradient(hsl(207.5, 84.8%, 51%), hsla(207, 84%, 62%, 1));_x000D_
transition: all 0.2s linear;_x000D_
}_x000D_
.button.b1 {_x000D_
display: inline-flex; /* element only as wide as content */_x000D_
}_x000D_
.button.b2 {_x000D_
display: table; /* element only as wide as content */_x000D_
}
_x000D_
<div class="container c1">_x000D_
<a class="button b1" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Before And After Wrap</a>_x000D_
</div>_x000D_
<div class="container c2">_x000D_
<a class="button b2" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Only Before Wrap</a>_x000D_
</div>
_x000D_
Fiddle
Just for completeness, you can use the standard library and do QString qstr = QString::fromStdString(std::to_string(42));
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
I'd do it like this jsFiddle example.
JavaScript:
function check(elem) {
document.getElementById('mySelect1').disabled = !elem.selectedIndex;
}
HTML:
<form>
<select id="mySelect" onChange="check(this);">
<option>No</option>
<option>Yes</option>
</select>
<select id="mySelect1" disabled="disabled" >
<option>Dep1</option>
<option>Dep2</option>
<option>Dep3</option>
<option>Dep4</option>
</select>
</form>
This affects:
This is because Netbeans does not 'see' that tomcat is started, although it started just fine.
I have filed Bug #262749 with NetBeans.
In the server.xml
file, in the Connector
element for HTTP/1.1, add the following attribute: server="Apache-Coyote/1.1"
.
Example:
<Connector
connectionTimeout="20000"
port="8080"
protocol="HTTP/1.1"
redirectPort="8443"
server="Apache-Coyote/1.1"
/>
The reason for that is that prior to 8.5.3, the default was to set the server header as Apache-Coyote/1.1
, while since 8.5.3 this default has now been changed to blank. Apparently Netbeans checks on this header.
Maybe in the future we can expect a fix in netbeans addressing this issue.
I was able to trace it back to a change in documentation.
"Overrides the Server header for the http response. If set, the value for this attribute overrides any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then no Server header is set."
"Overrides the Server header for the http response. If set, the value for this attribute overrides the Tomcat default and any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then Apache-Coyote/1.1 is used. Unless you are paranoid, you won't need this feature."
That explains the need for explicitly adding the server attribute since version 8.5.3.
Regex should be a fast approach:
re.search('[a-zA-Z]', the_string)
Another question elligeable for a 'code-challenge': here are some source code executables to answer the problem, but they are not complete.
Will you find a vb script that anyone can execute on his/her computer, with the expected result ?
systeminfo|find /i "original"
would give you the actual date... not the number of seconds ;)
As Sammy comments, find /i "install"
gives more than you need.
And this only works if the locale is English: It needs to match the language.
For Swedish this would be "ursprungligt
" and "ursprüngliches
" for German.
In Windows PowerShell script, you could just type:
PS > $os = get-wmiobject win32_operatingsystem
PS > $os.ConvertToDateTime($os.InstallDate) -f "MM/dd/yyyy"
By using WMI (Windows Management Instrumentation)
If you do not use WMI, you must read then convert the registry value:
PS > $path = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
PS > $id = get-itemproperty -path $path -name InstallDate
PS > $d = get-date -year 1970 -month 1 -day 1 -hour 0 -minute 0 -second 0
## add to hours (GMT offset)
## to get the timezone offset programatically:
## get-date -f zz
PS > ($d.AddSeconds($id.InstallDate)).ToLocalTime().AddHours((get-date -f zz)) -f "MM/dd/yyyy"
The rest of this post gives you other ways to access that same information. Pick your poison ;)
In VB.Net that would give something like:
Dim dtmInstallDate As DateTime
Dim oSearcher As New ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")
For Each oMgmtObj As ManagementObject In oSearcher.Get
dtmInstallDate =
ManagementDateTimeConverter.ToDateTime(CStr(oMgmtO bj("InstallDate")))
Next
In Autoit (a Windows scripting language), that would be:
;Windows Install Date
;
$readreg = RegRead("HKLM\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\", "InstallDate")
$sNewDate = _DateAdd( 's',$readreg, "1970/01/01 00:00:00")
MsgBox( 4096, "", "Date: " & $sNewDate )
Exit
In Delphy 7, that would go as:
Function GetInstallDate: String;
Var
di: longint;
buf: Array [ 0..3 ] Of byte;
Begin
Result := 'Unknown';
With TRegistry.Create Do
Begin
RootKey := HKEY_LOCAL_MACHINE;
LazyWrite := True;
OpenKey ( '\SOFTWARE\Microsoft\Windows NT\CurrentVersion', False );
di := readbinarydata ( 'InstallDate', buf, sizeof ( buf ) );
// Result := DateTimeToStr ( FileDateToDateTime ( buf [ 0 ] + buf [ 1 ] * 256 + buf [ 2 ] * 65535 + buf [ 3 ] * 16777216 ) );
showMessage(inttostr(di));
Free;
End;
End;
As an alternative, CoastN proposes in the comments:
As the
system.ini-file
stays untouched in a typical windows deployment, you can actually get the install-date by using the following oneliner:(PowerShell): (Get-Item "C:\Windows\system.ini").CreationTime
perhaps this is what you're looking for: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/colors.xml
Adding this in conf.d fixed this issue for me.
Options +Indexes +FollowSymLinks
There is a pseudocolumn called %%physloc%% that shows the physical address of the row.
So I just had this same issue, but a little different. I already had the icon as an object as Philippe Boissonneault suggests, but I was using an SVG image.
What solved it for me was:
Switch from an SVG image to a PNG and following Catherine Nyo on having an image that is double the size of what you will use.
type this command
select CURRENT_USER();
You will get the username and server
Does GitHub have this social feature?
If the commit email is kept private, GitHub now (July 2020) proposes:
Users and organizations can now add Twitter usernames to their GitHub profiles
You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.
We've also added the latest changes:
- Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
- All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
- When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.
That could be a workaround to leave a message to a GitHub user.
An optional way if you want to use pure Python:
ElementTree is good for most cases, but it can't CData and pretty print.
So, if you need CData and pretty print you should use minidom:
minidom_example.py:
from xml.dom import minidom
doc = minidom.Document()
root = doc.createElement('root')
doc.appendChild(root)
leaf = doc.createElement('leaf')
text = doc.createTextNode('Text element with attributes')
leaf.appendChild(text)
leaf.setAttribute('color', 'white')
root.appendChild(leaf)
leaf_cdata = doc.createElement('leaf_cdata')
cdata = doc.createCDATASection('<em>CData</em> can contain <strong>HTML tags</strong> without encoding')
leaf_cdata.appendChild(cdata)
root.appendChild(leaf_cdata)
branch = doc.createElement('branch')
branch.appendChild(leaf.cloneNode(True))
root.appendChild(branch)
mixed = doc.createElement('mixed')
mixed_leaf = leaf.cloneNode(True)
mixed_leaf.setAttribute('color', 'black')
mixed_leaf.setAttribute('state', 'modified')
mixed.appendChild(mixed_leaf)
mixed_text = doc.createTextNode('Do not use mixed elements if it possible.')
mixed.appendChild(mixed_text)
root.appendChild(mixed)
xml_str = doc.toprettyxml(indent=" ")
with open("minidom_example.xml", "w") as f:
f.write(xml_str)
minidom_example.xml:
<?xml version="1.0" ?>
<root>
<leaf color="white">Text element with attributes</leaf>
<leaf_cdata>
<![CDATA[<em>CData</em> can contain <strong>HTML tags</strong> without encoding]]> </leaf_cdata>
<branch>
<leaf color="white">Text element with attributes</leaf>
</branch>
<mixed>
<leaf color="black" state="modified">Text element with attributes</leaf>
Do not use mixed elements if it possible.
</mixed>
</root>
Please try something like:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
You seem to have three main possible scenarios:
ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.
I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.
This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.
This with =FIND which looks for a space (" "
) in C1
, starting with the eighth character within C1
counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.
Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.
So
=VALUE(LEFT(C1,FIND(" ",C1,8)))
returns 40671
in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.
If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:
=RIGHT(C2,4)
Takes the last four characters of C2, hence 2011
in this example.
=MID(C2,4,2)
Starting at the fourth character, takes the next two characters of C2, hence 05
in this example (representing May).
=LEFT(C2,2))
Takes the first two characters of C2, hence 08
in this example (representing the 8th day of the month).
Date is not a text function so does not need to be wrapped in =VALUE.
Taken together
=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2))
also returns 40671
in this example, but from different input from Case #1.
Is simple because already a date serial number, so just
=C2
is sufficient.
Put the above together to cover all three cases in a single formula:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:
The easiest way to do this is :
ALTER TABLE db.TABLENAME ADD COLUMN [datatype] NOT NULL DEFAULT 'value'
Ex : Adding a column x (bit datatype) to a table ABC with default value 0
ALTER TABLE db.ABC ADD COLUMN x bit NOT NULL DEFAULT 0
PS : I am not a big fan of using the table designer for this. Its so much easier being conventional / old fashioned sometimes. :). Hope this helps answer
I think you just need to create your volume outside docker first with a docker create -v /location --name
and then reuse it.
And by the time I used to use docker a lot, it wasn't possible to use a static docker volume with dockerfile definition so my suggestion is to try the command line (eventually with a script ) .
I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.
public static void main(String... args) throws IOException {
final int runs = 5 * 1000 * 1000;
final ServerSocket ss = new ServerSocket(0);
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket serverConn = ss.accept();
String line = "Hello World!\n";
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
for (int count = 0; count < runs; count++)
br.write(line);
serverConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Socket conn = new Socket("localhost", ss.getLocalPort());
long start = System.nanoTime();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
List<String> responseData = new ArrayList<String>();
while ((line = in.readLine()) != null) {
responseData.add(line);
}
long time = System.nanoTime() - start;
System.out.println("Average time to read a line was " + time / runs + " ns.");
conn.close();
ss.close();
}
prints
Average time to read a line was 158 ns.
If you want to build a StringBuilder, keeping newlines I would suggets the following approach.
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
Still prints
Average time to read a line was 159 ns.
In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.
I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.
Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).
In MySQL you can use:
SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")
The SOUNDEX
function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.
View
is the SuperClass of All component like TextView, EditText, ListView,
etc..
while ViewGroup
is Collection of Views(TextView, EditText, ListView, etc..)
, somewhat like container.
Use restart: always in your docker compose file.
Docker-compose up -d
will launch container from images again. Use docker-compose start
to start the stopped containers, it never launches new containers from images.
nginx:
restart: always
image: nginx
ports:
- "80:80"
- "443:443" links:
- other_container:other_container
Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.
Converting the date without specifying the current format can bring this error to you easily.
sdate <- "2015.10.10"
date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".
date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.
You could create helper methods that would convert a list (array) of type T
to a list (array) of type U
using the map
operation on stream
.
//for lists
public static <T, U> List<U> convertList(List<T> from, Function<T, U> func) {
return from.stream().map(func).collect(Collectors.toList());
}
//for arrays
public static <T, U> U[] convertArray(T[] from,
Function<T, U> func,
IntFunction<U[]> generator) {
return Arrays.stream(from).map(func).toArray(generator);
}
And use it like this:
//for lists
List<String> stringList = Arrays.asList("1","2","3");
List<Integer> integerList = convertList(stringList, s -> Integer.parseInt(s));
//for arrays
String[] stringArr = {"1","2","3"};
Double[] doubleArr = convertArray(stringArr, Double::parseDouble, Double[]::new);
s -> Integer.parseInt(s)
could be replaced with Integer::parseInt
(see Method references)
Well, this is another solution that some of you guys might be looking for (as I was..)
My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.
The solutions presented here were not working 100%.
My solution was this:
showLocationModal = function(loc){
var is_loading = true;
if(is_loading === true) {
is_loading = false;
var $modal = $('#locationModal');
$modal.modal({show:true});
// prevent Modal to close before the iframe is loaded
$modal.on("hide", function (e) {
if(is_loading !== true) {
e.preventDefault();
return false
}
});
// populate Modal
$modal.find('.modal-body iframe').hide().attr('src', location.link).load(function(){
is_loading = true;
});
}};
So I temporarily prevent the Modal from closing with:
$modal.on("hide", function (e) {
if(is_loading !== true) {
e.preventDefault();
return false
}
});
But ith the var is_loading that will re enable closing after the Iframe has loaded.
The below made sense for 2013. However, now, I would use the :not()
selector as described below.
CSS can be overwritten.
DEMO: http://jsfiddle.net/persianturtle/J4SUb/
Use this:
.parent {
padding: 50px;
border: 1px solid black;
}
.parent span {
position: absolute;
top: 200px;
padding: 30px;
border: 10px solid green;
}
.parent:hover span {
border: 10px solid red;
}
.parent span:hover {
border: 10px solid green;
}
_x000D_
<a class="parent">
Parent text
<span>Child text</span>
</a>
_x000D_
Also look up ArrayAdapter interface:
ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
use return
for this
if(i==1) {
return; //stop the execution of function
}
//keep on going
I was looking for same answer & found this info from wiki useful: Loop Instructions
The loop instruction decrements ECX and jumps to the address specified by arg unless decrementing ECX caused its value to become zero. For example:
mov ecx, 5
start_loop:
; the code here would be executed 5 times
loop start_loop
loop does not set any flags.
loopx arg
These loop instructions decrement ECX and jump to the address specified by arg if their condition is satisfied (that is, a specific flag is set), unless decrementing ECX caused its value to become zero.
loope loop if equal
loopne loop if not equal
loopnz loop if not zero
loopz loop if zero
Source: X86 Assembly, Control Flow
To answer your question, these should work as long as:
But, if I remember correctly, these values can be faked to an extent, so it's best not to rely on them.
My personal preference is to set the domain name as an environment variable in the apache2 virtual host:
# Virtual host
setEnv DOMAIN_NAME example.com
And read it in PHP:
// PHP
echo getenv(DOMAIN_NAME);
This, however, isn't applicable in all circumstances.
It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.
A string is a series of characters followed by a string terminator ('\0'
). An empty string (""
) consists of no characters followed by a single string terminator character - i.e. one character in total.
So I would try the following:
string[1] = ""
Note that this behaviour is not the emulated by strlen
, which does not count the terminator as part of the string length.
If you only need to execute only one command all by itself and no wait needed, you should try "cmd /c", this works for me!
cmd /c start iexplore "http://your/url.html"
cmd /c means executing a command and then exit.
You can learn the functions of your switches by typing in your command prompt
anycmd /?
In addition to accepted answer:
`this is a
single string`
which evaluates to: 'this is a\nsingle string'.
If you want to use string interpolation but without a new line, just add backslash as in normal string:
`this is a \
single string`
=> 'this is a single string'.
Bear in mind manual whitespace is necessary though:
`this is a\
single string`
=> 'this is asingle string'
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
If performance is not a major concern, you can also use any of these methods:
(In case you wanted the hash string to be in upper case, replace "x2"
with "X2"
.)
public static string SHA256ToString(string s)
{
using (var alg = SHA256.Create())
return string.Join(null, alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Select(x => x.ToString("x2")));
}
or:
public static string SHA256ToString(string s)
{
using (var alg = SHA256.Create())
return alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.ToString("x2"))).ToString();
}
Judging from the examples you provide, I'm assuming that by ANNs, you mean multilayer feed-forward networks (FF nets for short), such as multilayer perceptrons, because those are in direct competition with SVMs.
One specific benefit that these models have over SVMs is that their size is fixed: they are parametric models, while SVMs are non-parametric. That is, in an ANN you have a bunch of hidden layers with sizes h1 through hn depending on the number of features, plus bias parameters, and those make up your model. By contrast, an SVM (at least a kernelized one) consists of a set of support vectors, selected from the training set, with a weight for each. In the worst case, the number of support vectors is exactly the number of training samples (though that mainly occurs with small training sets or in degenerate cases) and in general its model size scales linearly. In natural language processing, SVM classifiers with tens of thousands of support vectors, each having hundreds of thousands of features, is not unheard of.
Also, online training of FF nets is very simple compared to online SVM fitting, and predicting can be quite a bit faster.
EDIT: all of the above pertains to the general case of kernelized SVMs. Linear SVM are a special case in that they are parametric and allow online learning with simple algorithms such as stochastic gradient descent.
// Totally generic sorting for use with a gridview
public List<T> Sort_List<T>(string sortDirection, string sortExpression, List<T> data)
{
List<T> data_sorted = new List<T>();
if (sortDirection == "Ascending")
{
data_sorted = (from n in data
orderby GetDynamicSortProperty(n, sortExpression) ascending
select n).ToList();
}
else if (sortDirection == "Descending")
{
data_sorted = (from n in data
orderby GetDynamicSortProperty(n, sortExpression) descending
select n).ToList();
}
return data_sorted;
}
public object GetDynamicSortProperty(object item, string propName)
{
//Use reflection to get order type
return item.GetType().GetProperty(propName).GetValue(item, null);
}
Scenario: You did a big clean up of your code by using your IDE. Problem: The IDE cleaned up more than it should and now you code does not compile (missing resources, etc.)
Solution:
git grep --cached "text_to_find"
It will find the file where "text_to_find" was changed.
You can now undo this change and compile your code.
You need to add the referer field in the headers of the HTTP request. With wget, you just need the --header arg :
wget http://www.icerts.com/images/logo.jpg --header "Referer: www.icerts.com"
And the result :
--2011-10-02 02:00:18-- http://www.icerts.com/images/logo.jpg
Résolution de www.icerts.com (www.icerts.com)... 97.74.86.3
Connexion vers www.icerts.com (www.icerts.com)|97.74.86.3|:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 6102 (6,0K) [image/jpeg]
Sauvegarde en : «logo.jpg»
If you've got the Java EE JDK with Glassfish, it's in glassfish3/glassfish/modules/javax.servlet-api.jar.
As you can see in the generated SQL statements the difference is not the "OR" as some may suspect. It is how the WHERE and JOIN is placed.
(example from https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships)
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
This will give you all the Blogs that have one entry with both (entry_headline_contains='Lennon') AND (entry__pub_date__year=2008), which is what you would expect from this query. Result: Book with {entry.headline: 'Life of Lennon', entry.pub_date: '2008'}
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
This will cover all the results from Example 1, but it will generate slightly more result. Because it first filters all the blogs with (entry_headline_contains='Lennon') and then from the result filters (entry__pub_date__year=2008).
The difference is that it will also give you results like: Book with {entry.headline: 'Lennon', entry.pub_date: 2000}, {entry.headline: 'Bill', entry.pub_date: 2008}
I think it is this one you need:
Book.objects.filter(inventory__user__profile__vacation=False, inventory__user__profile__country='BR')
And if you want to use OR please read: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.
A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).
It's a nit, but enough to cause unit tests to fail.
You would certainly benefit from using a responsive framework for your project. It would save you a good amount of headaches. However, seeing the structure of your HTML I would do the following:
Please check the example: http://jsfiddle.net/xLA4q/
HTML:
<div class="nav-content-wrapper">
<div class="left-nav">asdasdasd ads asd ads asd ad asdasd ad ad a ad</div>
<div class="content">asd as dad ads ads ads ad ads das ad sad</div>
</div>
CSS:
.nav-content-wrapper{position:relative; overflow:auto; display:block;height:300px;}
.left-nav{float:left;width:30%;height:inherit;}
.content{float:left;width:70%;height:inherit;}
For Each row As DataGridViewRow In yourDGV.SelectedRows
yourDGV.Rows.Remove(row)
Next
This will delete all rows that had been selected.
For the sake of completeness, there is another way to remove the Server
header, using regedit.
Create a DWORD entry called DisableServerHeader in the following Registry key and set the value to 1.
HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters
I'd rather find a proper solution using the Web.config, but using <rewrite>
is not good because it requires the rewrite module to be installed, and even then it won't really remove the header, just empty it.
You can use netstat command
netstat --listen
To display open ports and established TCP connections,
netstat -vatn
To display only open UDP ports try the following command:
netstat -vaun
Alternative flexibility solution is Apscheduler.
pip install apscheduler
from apscheduler.schedulers.background import BlockingScheduler
def print_t():
pass
sched = BlockingScheduler()
sched.add_job(print_t, 'interval', seconds =60) #will do the print_t work for every 60 seconds
sched.start()
Also, apscheduler provides so many schedulers as follow.
BlockingScheduler: use when the scheduler is the only thing running in your process
BackgroundScheduler: use when you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application
AsyncIOScheduler: use if your application uses the asyncio module
GeventScheduler: use if your application uses gevent
TornadoScheduler: use if you’re building a Tornado application
TwistedScheduler: use if you’re building a Twisted application
QtScheduler: use if you’re building a Qt application
For an 8-bit (CV_8U) OpenCV image, the syntax is:
Mat img(Mat(nHeight, nWidth, CV_8U);
img = cv::Scalar(50); // or the desired uint8_t value from 0-255
Sure, you can do nested ternary operators but they are hard to read.
var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))
Where on earth did you find this syntax? Java Enums are very simple, you just specify the values.
public enum Gender {
MALE,
FEMALE
}
If you want them to be more complex, you can add values to them like this.
public enum Gender {
MALE("Male", 0),
FEMALE("Female", 1);
private String stringValue;
private int intValue;
private Gender(String toString, int value) {
stringValue = toString;
intValue = value;
}
@Override
public String toString() {
return stringValue;
}
}
Then to use the enum, you would do something like this:
Gender me = Gender.MALE
This answer is just useful to understand how you can make delay using JQuery delay
function.
Imagine you have an alert and you want to set the alert text then show the alert and after a few seconds hide it.
Here is the simple solution:
$(".alert-element").html("I'm the alert text").fadeIn(500).delay(5000).fadeOut(1000);
It is completely simple:
.html()
will change the text of .alert-element
.fadeIn(500)
will fade in after 500 millisecondsdelay(5000)
function will make 5000 milliseconds of delay before calling next function.fadeOut(1000)
at the end of the statement will fade out the .alert-element
Neither databases, nor tablespaces nor data files belong to any user. Are you coming to this from an MS SQL background?
select tablespace_name,
file_name
from dba_tablespaces
order by tablespace_name,
file_name;
I have changed from 3.2.1 to 4.0.1 and the folder was font and now is called fonts.
src: url('../font/fontawesome-webfont.eot?v=3.2.1');
src: url('../fonts/fontawesome-webfont.eot?v=4.0.1');
I hope it help someone.
In Java8 you can use streams:
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsIn) {
return listCarnet.stream().filter(carnet -> codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null);
}
Additionally, in case you have many different objects (not only Carnet
) or you want to find it by different properties (not only by cideIsin
), you could build an utility class, to ecapsulate this logic in it:
public final class FindUtils {
public static <T> T findByProperty(Collection<T> col, Predicate<T> filter) {
return col.stream().filter(filter).findFirst().orElse(null);
}
}
public final class CarnetUtils {
public static Carnet findByCodeTitre(Collection<Carnet> listCarnet, String codeTitre) {
return FindUtils.findByProperty(listCarnet, carnet -> codeTitre.equals(carnet.getCodeTitre()));
}
public static Carnet findByNomTitre(Collection<Carnet> listCarnet, String nomTitre) {
return FindUtils.findByProperty(listCarnet, carnet -> nomTitre.equals(carnet.getNomTitre()));
}
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsin) {
return FindUtils.findByProperty(listCarnet, carnet -> codeIsin.equals(carnet.getCodeIsin()));
}
}
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
A couple of things to enhance the other answers. First, you should never return a HashMap
, which is a specific implementation. Return instead a plain old java.util.Map
. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>
. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).
You can't use string.replace...as one string is assigned you cannot manipulate. For that, we use string builder. Here is my example. In the HTML page I add [Name] which is replaced by Name. Make sure [Name] is unique or you can give any unique name:
string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));
StringBuilder builder = new StringBuilder(contents);
builder.Replace("[Name]", Name);
StringReader sr = new StringReader(builder.ToString());
I had a lot of issues with curl for Windows. I finally used Cygwin, which includes curl by default.
Try this instead:
print_r($sth->errorInfo());
Add this before your prepare:
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.
If you are using pandas you can access the index by calling .index of whatever array you wish to mimic. The train_test_split carries over the pandas indices to the new dataframes.
In your code you simply use
x1.index
and the returned array is the indexes relating to the original positions in x.
Just for other's reference, I just received this and found it was due to AngularJS. It's for backwards compatibility:
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
I'm using this https://github.com/biggora/bootstrap-ajax-typeahead
The result of code using Codeigniter/PHP
<pre>
$("#produto").typeahead({
onSelect: function(item) {
console.log(item);
getProductInfs(item);
},
ajax: {
url: path + 'produto/getProdName/',
timeout: 500,
displayField: "concat",
valueField: "idproduto",
triggerLength: 1,
method: "post",
dataType: "JSON",
preDispatch: function (query) {
showLoadingMask(true);
return {
search: query
}
},
preProcess: function (data) {
if (data.success === false) {
return false;
}else{
return data;
}
}
}
});
</pre>
You can also try this:
Python 2.x:
python -c "import sys; print '\n'.join(sys.path)"
Python 3.x:
python3 -c "import sys; print('\n'.join(sys.path))"
The output will be more readable and clean, like so:
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload /Library/Python/2.7/site-packages /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
In the app server we use where I work (Oracle Application Server 10g, as I recall), pooling is handled by the app server. We retrieve a javax.sql.DataSource
using a JNDI lookup with a javax.sql.InitialContext
.
it's done something like this
try {
context = new InitialContext();
jdbcURL = (DataSource) context.lookup("jdbc/CachedDS");
System.out.println("Obtained Cached Data Source ");
}
catch(NamingException e)
{
System.err.println("Error looking up Data Source from Factory: "+e.getMessage());
}
(We didn't write this code, it's copied from this documentation.)
The single-step answer to the first question is to use something like:
update TBL set CLM = CLM + 1 where key = 'KEY'
That's very much a single-instruction way of doing it.
As for the second question, you shouldn't need to resort to DBMS-specific SQL gymnastics (like UPSERT
) to get the result you want. There's a standard method to do update-or-insert that doesn't require a specific DBMS.
try:
insert into TBL (key,val) values ('xyz',0)
catch:
do nothing
update TBL set val = val + 1 where key = 'xyz'
That is, you try to do the creation first. If it's already there, ignore the error. Otherwise you create it with a 0 value.
Then do the update which will work correctly whether or not:
It's not a single instruction and yet, surprisingly enough, it's how we've been doing it successfully for a long long time.
You can also use redirect()
method like this:-
return redirect('https://stackoverflow.com/');
This was the tutorial I was looking for in this thread. It shows the way to open files in Visual Studio Code by writing code .
1.- Open the file
Bash
open ~/.bash_profile
Terminal OS
open ~/.zshrc
2.- Add in your file the :
code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}
3.- Reinicialize terminal and try in the folder you want to open
code .
4.- Then you can use it as shown in this comment: https://stackoverflow.com/a/41821250/10033560
Please find the answer for the selecting single image from gallery
import android.app.Activity;
import android.net.Uri;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class PickImage extends Activity {
Button btnOpen, btnGet, btnPick;
TextView textInfo1, textInfo2;
ImageView imageView;
private static final int RQS_OPEN_IMAGE = 1;
private static final int RQS_GET_IMAGE = 2;
private static final int RQS_PICK_IMAGE = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_pick);
btnOpen = (Button)findViewById(R.id.open);
btnGet = (Button)findViewById(R.id.get);
btnPick = (Button)findViewById(R.id.pick);
textInfo1 = (TextView)findViewById(R.id.info1);
textInfo2 = (TextView)findViewById(R.id.info2);
imageView = (ImageView) findViewById(R.id.image);
btnOpen.setOnClickListener(btnOpenOnClickListener);
btnGet.setOnClickListener(btnGetOnClickListener);
btnPick.setOnClickListener(btnPickOnClickListener);
}
View.OnClickListener btnOpenOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, RQS_OPEN_IMAGE);
}
};
View.OnClickListener btnGetOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, RQS_OPEN_IMAGE);
}
};
View.OnClickListener btnPickOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_PICK_IMAGE);
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RQS_OPEN_IMAGE ||
requestCode == RQS_GET_IMAGE ||
requestCode == RQS_PICK_IMAGE) {
imageView.setImageBitmap(null);
textInfo1.setText("");
textInfo2.setText("");
Uri mediaUri = data.getData();
textInfo1.setText(mediaUri.toString());
String mediaPath = mediaUri.getPath();
textInfo2.setText(mediaPath);
//display the image
try {
InputStream inputStream = getBaseContext().getContentResolver().openInputStream(mediaUri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byteArray = stream.toByteArray();
imageView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
ResultSet result = stmt.executeQuery(sqlQuery);
if (!result.next())
status = "ERROR";
else
status = "SUCCESS";
Firefox can reject a stylesheet if it is not served with a content type of "text/css". (This is separate from the 'type="text/css"'
declaration in the HTML.)
I used below function to compare two strings and It is working good.
function CompareUserId (first, second)
{
var regex = new RegExp('^' + first+ '$', 'i');
if (regex.test(second))
{
return true;
}
else
{
return false;
}
return false;
}
There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.
version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}" # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}" # 7 1
Just use replace
instead of replaceAll
(which expects regex):
str = str.replace(",", ".");
or
str = str.replace(',', '.');
(replace
takes as input either char
or CharSequence
, which is an interface implemented by String
)
Also note that you should reassign the result
Your class:
class name {
public:
string first;
string last;
name() { } //Default constructor.
name(string a, string b){
first = a;
last = b;
}
};
Has an explicit constructor that requires two string parameters. Classes with no constructor written explicitly get default constructors taking no parameters. Adding the explicit one stopped the compiler from generating that default constructor for you.
So, if you wish to make an array of uninitialized objects, add a default constructor to your class so the compiler knows how to create them without providing those two string parameters - see the commented line above.
Solution Working in the Year 2020 and 2021:
I tried the other solutions and nothing worked. This is because of input logic in React.js has been changed. For detail, you can see this link: https://hustle.bizongo.in/simulate-react-on-change-on-controlled-components-baa336920e04.
In short, when we change the value of input by changing state and then dispatch a change event then React will register both the setState and the event and consider it a duplicate event and swallow it.
The solution is to call native value setter on input (See setNativeValue function in following code)
Example Code
import React, { Component } from 'react'
export class CustomInput extends Component {
inputElement = null;
// THIS FUNCTION CALLS NATIVE VALUE SETTER
setNativeValue(element, value) {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
}
constructor(props) {
super(props);
this.state = {
inputValue: this.props.value,
};
}
addToInput = (valueToAdd) => {
this.setNativeValue(this.inputElement, +this.state.inputValue + +valueToAdd);
this.inputElement.dispatchEvent(new Event('input', { bubbles: true }));
};
handleChange = e => {
console.log(e);
this.setState({ inputValue: e.target.value });
this.props.onChange(e);
};
render() {
return (
<div>
<button type="button" onClick={() => this.addToInput(-1)}>-</button>
<input
readOnly
ref={input => { this.inputElement = input }}
name={this.props.name}
value={this.state.inputValue}
onChange={this.handleChange}></input>
<button type="button" onClick={() => this.addToInput(+1)}>+</button>
</div>
)
}
}
export default CustomInput
Result
>>> import numpy
>>> print numpy.power.__doc__
power(x1, x2[, out])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
Examples
--------
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
>>>
As per the discussed observation on numerical precision as per @GarethRees objection in comments:
>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677
>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241
>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )
>>> import zmq
>>> aClk = zmq.Stopwatch()
>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]
>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]
>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]
>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]
>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]
NSArray *array = [mutableArray copy];
Copy
makes immutable copies. This is quite useful because Apple can make various optimizations. For example sending copy
to a immutable array only retains the object and returns self
.
If you don't use garbage collection or ARC remember that -copy
retains the object.
One option is to use altertify, this gives a nice looking alert box.
Simply include the required libraries from here, and use the following piece of code to display the alert box.
alertify.confirm("This is a confirm dialog.",
function(){
alertify.success('Ok');
},
function(){
alertify.error('Cancel');
});
The output will look like this. To see it in action here is the demo
Change the backend to automatic:
Tools > preferences > IPython console > Graphics > Graphics backend > Backend: Automatic
Then close and open Spyder.
To add to @akilat90's update about sklearn.metrics.plot_confusion_matrix
:
You can use the ConfusionMatrixDisplay
class within sklearn.metrics
directly and bypass the need to pass a classifier to plot_confusion_matrix
. It also has the display_labels
argument, which allows you to specify the labels displayed in the plot as desired.
The constructor for ConfusionMatrixDisplay
doesn't provide a way to do much additional customization of the plot, but you can access the matplotlib axes obect via the ax_
attribute after calling its plot()
method. I've added a second example showing this.
I found it annoying to have to rerun a classifier over a large amount of data just to produce the plot with plot_confusion_matrix
. I am producing other plots off the predicted data, so I don't want to waste my time re-predicting every time. This was an easy solution to that problem as well.
Example:
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()
Example using ax_
:
cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()
cmd.ax_.set(xlabel='Predicted', ylabel='True')
The best and the most bulletproof solution is to add ::before
and ::after
pseudoelements to the container. So if you have for example a list like:
<ul class="clearfix">
<li></li>
<li></li>
<li></li>
</ul>
And every elements in the list has float:left
property, then you should add to your css:
.clearfix::after, .clearfix::before {
content: '';
clear: both;
display: table;
}
Or you could try display:inline-block;
property, then you don't need to add any clearfix.
Here's a solution for Bootstrap4. You just need to put the card-header
class in the a
tag. This is a modified from an example in W3Schools.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div id="accordion">_x000D_
<div class="card">_x000D_
<a class="card-link card-header" data-toggle="collapse" href="#collapseOne" >_x000D_
Collapsible Group Item #1_x000D_
</a>_x000D_
<div id="collapseOne" class="collapse" data-parent="#accordion">_x000D_
<div class="card-body">_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<a class="collapsed card-link card-header" data-toggle="collapse" href="#collapseTwo">_x000D_
Collapsible Group Item #2_x000D_
</a>_x000D_
<div id="collapseTwo" class="collapse" data-parent="#accordion">_x000D_
<div class="card-body">_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<a class="card-link card-header" data-toggle="collapse" href="#collapseThree">_x000D_
Collapsible Group Item #3_x000D_
</a>_x000D_
<div id="collapseThree" class="collapse" data-parent="#accordion">_x000D_
<div class="card-body">_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
@Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records
$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
it gives records having date form 2015-10-16 to less than 2015-10-23. If value of recur_at is 2015-10-23 00:00:00 then only it shows that record else if it is 2015-10-23 12:00:45 then it is not shown.
Here my solution including seconds:
function convert_to_24h(time_str) {
// Convert a string like 10:05:23 PM to 24h format, returns like [22,5,23]
var time = time_str.match(/(\d+):(\d+):(\d+) (\w)/);
var hours = Number(time[1]);
var minutes = Number(time[2]);
var seconds = Number(time[3]);
var meridian = time[4].toLowerCase();
if (meridian == 'p' && hours < 12) {
hours += 12;
}
else if (meridian == 'a' && hours == 12) {
hours -= 12;
}
return [hours, minutes, seconds];
};
UNSIGNED
only stores positive numbers (or zero). On the other hand, signed can store negative numbers (i.e., may have a negative sign).
Here's a table of the ranges of values each INTEGER
type can store:
Source: http://dev.mysql.com/doc/refman/5.6/en/integer-types.html
UNSIGNED
ranges from 0
to n
, while signed ranges from about -n/2
to n/2
.
In this case, you have an AUTO_INCREMENT
ID column, so you would not have negatives. Thus, use UNSIGNED
. If you do not use UNSIGNED
for the AUTO_INCREMENT
column, your maximum possible value will be half as high (and the negative half of the value range would go unused).
The problem is that you are trying to access resources (in this case, strings) using getResources().getString(), which will try to get the resources from the Activity. See this source code of the Fragment class:
/**
* Return <code>getActivity().getResources()</code>.
*/
final public Resources getResources() {
if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
return mHost.getContext().getResources();
}
mHost
is the object that holds your Activity.
Because the Activity might not be attached, your getResources() call will throw an Exception.
The accepted solution IMHO is not the way to go as you are just hiding the problem. The correct way is just to get the resources from somewhere else that is always guaranteed to exist, like the application context:
youApplicationObject.getResources().getString(...)
There is a maven plugin called properties-maven-plugin this one provides a goal set-system-properties
to set system variables. This is especially useful if you have a file containing all these properties. So you're able to read a property file and set them as system variable.
For a Fragment you can simply add
getActivity().onBackPressed();
to your code
The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.
String dateTimeString = "2014-01-16T10:25:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
if (dateTime.isBefore(now)) {
System.out.println(dateTimeString + " is in the past");
} else if (dateTime.isAfter(now)) {
System.out.println(dateTimeString + " is in the future");
} else {
System.out.println(dateTimeString + " is now");
}
When running in 2020 output from this snippet is:
2014-01-16T10:25:00 is in the past
Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar")
. For UTC specify ZoneOffset.UTC
.
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Here is a heavy tutorial that has good stuff in it to pick out:
http://mobile.tutsplus.com/tutorials/mobile-web-apps/jquery_android/
Having following html:
<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>
<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>
<textarea>...</textarea>
You can get to active link with:
// event listener for keyup
function checkTabPress(e) {
"use strict";
// pick passed event or global event object if passed one is empty
e = e || event;
var activeElement;
if (e.keyCode == 9) {
// Here read the active selected link.
activeElement = document.activeElement;
// If HTML element is an anchor <a>
if (activeElement.tagName.toLowerCase() == 'a')
// get it's hyperlink
alert(activeElement.href);
}
}
var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
Here is working example.
This is to answer the part:
I was trying to understand whether dimension tables can be fact table as well or not?
The short answer (INMO) is No.That is because the 2 types of tables are created for different reasons. However, from a database design perspective, a dimension table could have a parent table as the case with the fact table which always has a dimension table (or more) as a parent. Also, fact tables may be aggregated, whereas Dimension tables are not aggregated. Another reason is that fact tables are not supposed to be updated in place whereas Dimension tables could be updated in place in some cases.
More details:
Fact and dimension tables appear in a what is commonly known as a Star Schema. A primary purpose of star schema is to simplify a complex normalized set of tables and consolidate data (possibly from different systems) into one database structure that can be queried in a very efficient way.
On its simplest form, it contains a fact table (Example: StoreSales) and a one or more dimension tables. Each Dimension entry has 0,1 or more fact tables associated with it (Example of dimension tables: Geography, Item, Supplier, Customer, Time, etc.). It would be valid also for the dimension to have a parent, in which case the model is of type "Snow Flake". However, designers attempt to avoid this kind of design since it causes more joins that slow performance. In the example of StoreSales, The Geography dimension could be composed of the columns (GeoID, ContenentName, CountryName, StateProvName, CityName, StartDate, EndDate)
In a Snow Flakes model, you could have 2 normalized tables for Geo information, namely: Content Table, Country Table.
You can find plenty of examples on Star Schema. Also, check this out to see an alternative view on the star schema model Inmon vs. Kimball. Kimbal has a good forum you may also want to check out here: Kimball Forum.
Edit: To answer comment about examples for 4NF:
Sales Fact (ID, BranchID, SalesPersonID, ItemID, Amount, TimeID)
AggregatedSales (BranchID, TotalAmount)
Here the relation is in 4NF
The last example is rather uncommon.
I knew the file name but wanted the directory as well.
find $PWD | fgrep filename
worked perfectly in Mac OS 10.12.1
changing shortcut under Windows System on 8.1 worked for me - another thing I found is that 'Start In:' WORKS when Advanced -> Run as admin is UNCHECKED, however, if CHECKED, it does not work
If you have web.xml then
HTML/JSP
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
</form>
web.xml
<servlet>
<display-name>Servlet Name</display-name>
<servlet-name>myservlet</servlet-name>
<servlet-class>package.SomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
Java SomeController.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Write your code below");
}
The problem with your code is in the line:
for(i in length(namevector))
You need to ask yourself: what is length(namevector)
? It's one number. So essentially you're saying:
for(i in 11)
df[,i] <- NA
Or more simply:
df[,11] <- NA
That's why you're getting an error. What you want is:
for(i in namevector)
df[,i] <- NA
Or more simply:
df[,namevector] <- NA
The following worked for me:
$(':input').val('');
However, it is submitting the form, so it might not be what you are looking for.
I have found something strange here about word-wrap
only works with width
property of CSS properly.
#ONLYwidth {_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
#wordwrapWITHOUTWidth {_x000D_
word-wrap: break-word;_x000D_
}_x000D_
_x000D_
#wordwrapWITHWidth {_x000D_
width: 200px;_x000D_
word-wrap: break-word;_x000D_
}
_x000D_
<b>This is the example of word-wrap only using width property</b>_x000D_
<p id="ONLYwidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap without width property</b>_x000D_
<p id="wordwrapWITHOUTWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap with width property</b>_x000D_
<p id="wordwrapWITHWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>
_x000D_
Here is a working demo that I have prepared about it. http://jsfiddle.net/Hss5g/2/
String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
}
Try this it solved my problem npx browserslist@latest --update-db
Try Run->Show->Expressions
Enter in the name of the array or whatever you're looking for.
I know this is not the case but if you need to keep the original freq column, you can use another tidyverse
approach together with rep
:
library(purrr)
df <- data.frame(var1 = c('a', 'b', 'c'), var2 = c('d', 'e', 'f'), freq = 1:3)
df %>%
map_df(., rep, .$freq)
#> # A tibble: 6 x 3
#> var1 var2 freq
#> <fct> <fct> <int>
#> 1 a d 1
#> 2 b e 2
#> 3 b e 2
#> 4 c f 3
#> 5 c f 3
#> 6 c f 3
Created on 2019-12-21 by the reprex package (v0.3.0)
You can use id(name)
to check if two names represent the same object:
>>> a = b = c = [0, 3, 5]
>>> print(id(a), id(b), id(c))
46268488 46268488 46268488
Lists are mutable; it means you can change the value in place without creating a new object. However, it depends on how you change the value:
>>> a[0] = 1
>>> print(id(a), id(b), id(c))
46268488 46268488 46268488
>>> print(a, b, c)
[1, 3, 5] [1, 3, 5] [1, 3, 5]
If you assign a new list to a
, then its id will change, so it won't affect b
and c
's values:
>>> a = [1, 8, 5]
>>> print(id(a), id(b), id(c))
139423880 46268488 46268488
>>> print(a, b, c)
[1, 8, 5] [1, 3, 5] [1, 3, 5]
Integers are immutable, so you cannot change the value without creating a new object:
>>> x = y = z = 1
>>> print(id(x), id(y), id(z))
507081216 507081216 507081216
>>> x = 2
>>> print(id(x), id(y), id(z))
507081248 507081216 507081216
>>> print(x, y, z)
2 1 1
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
The value
attribute is used to determine the rendered label of a submit input.
<input type="submit" class="like" value="Like" />
Note that if the control is successful (this one won't be as it has no name
) this will also be the submitted value for it.
To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img>
here).
<button type="submit" class="like" name="foo" value="bar">Like</button>
Note that support for <button>
is dodgy in older versions of Internet Explorer.
Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)
I wrote the following function to print dicts, lists, and tuples in a more readable format:
def printplus(obj):
"""
Pretty-prints the object passed in.
"""
# Dict
if isinstance(obj, dict):
for k, v in sorted(obj.items()):
print u'{0}: {1}'.format(k, v)
# List or tuple
elif isinstance(obj, list) or isinstance(obj, tuple):
for x in obj:
print x
# Other
else:
print obj
Example usage in iPython:
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1
>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)
To remove the margins on all rows:
.row {
margin: 0px !important;
}
If the external configuration file is also valid batch file, you can just use:
call externalconfig.bat
inside your script. Try creating following a.bat:
@echo off
call b.bat
echo %MYVAR%
and b.bat:
set MYVAR=test
Running a.bat should generate output:
test
Here's a solution to retrieve the html of a webpage using only standard java libraries:
import java.io.*;
import java.net.*;
String urlToRead = "https://google.com";
URL url; // The URL to read
HttpURLConnection conn; // The actual connection to the web page
BufferedReader rd; // Used to read results from the web page
String line; // An individual line of the web page HTML
String result = ""; // A long string containing all the HTML
try {
url = new URL(urlToRead);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result += line;
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
Yet another option is argh. It builds on argparse, and lets you write things like:
import argh
# declaring:
def echo(text):
"Returns given word as is."
return text
def greet(name, greeting='Hello'):
"Greets the user with given name. The greeting is customizable."
return greeting + ', ' + name
# assembling:
parser = argh.ArghParser()
parser.add_commands([echo, greet])
# dispatching:
if __name__ == '__main__':
parser.dispatch()
It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.
Also as a side note: Mootools has the function toInt() which is used on any native string (or float (or integer)).
"2".toInt() // 2
"2px".toInt() // 2
2.toInt() // 2
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
public static class Helper
{
public static string AsJsonList<T>(List<T> tt)
{
return new JavaScriptSerializer().Serialize(tt);
}
public static string AsJson<T>(T t)
{
return new JavaScriptSerializer().Serialize(t);
}
public static List<T> AsObjectList<T>(string tt)
{
return new JavaScriptSerializer().Deserialize<List<T>>(tt);
}
public static T AsObject<T>(string t)
{
return new JavaScriptSerializer().Deserialize<T>(t);
}
}
$.each(data,function(index,itemData){
$('#dropListBuilding').append($("<option></option>")
.attr("value",key)
.text(value));
});
The solution lies in understanding these two keyword arguments:
usecols
) using column names rather than integer indices.So because you have a header row, passing header=0
is sufficient and additionally passing names
appears to be confusing pd.read_csv
.
Removing names
from the second call gives the desired output:
import pandas as pd
from StringIO import StringIO
csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""
df = pd.read_csv(StringIO(csv),
header=0,
index_col=["date", "loc"],
usecols=["date", "loc", "x"],
parse_dates=["date"])
Which gives us:
x
date loc
2009-01-01 a 1
2009-01-02 a 3
2009-01-03 a 5
2009-01-01 b 1
2009-01-02 b 3
2009-01-03 b 5
^(?!my)\w+$
should work.
It first ensures that it's not possible to match my
at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$
. In this case, backreference 1 will contain the name of the variable.
And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_]
, use
^(?!my)[A-Za-z_]\w*$
Note the change from +
to *
.
Sorry, I solved my problem with the code above:
$("#captureImage").live("change", function() {
if($("#captureImage:checked").val() !== undefined) {
navigator.device.capture.captureImage(function(mediaFiles) {
console.log("works");
}, function(exception) {
$("#captureImage").removeAttr('checked').checkboxradio('refresh');
_callback.error(exception);
}, {});
}
});
performSelector:withObject:afterDelay:
I am taking an example of date given below and print two different format of dates according to your requirements.
String date="01/10/2014 05:54:00 PM";
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa",Locale.getDefault());
try {
Log.i("",""+new SimpleDateFormat("ddMMyyyyHHmmss",Locale.getDefault()).format(simpleDateFormat.parse(date)));
Log.i("",""+new SimpleDateFormat("dd/MM/yyyy HH:mm:ss",Locale.getDefault()).format(simpleDateFormat.parse(date)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you still have any query, Please respond. Thanks.
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
Read up on the configuration settings (e.g., display_errors
, display_startup_errors
, log_errors
) and update your php.ini
or .htaccess
or .user.ini
file, whichever is appropriate.
It works.
You can extend jQuery functionality like this :
Extend :
(function($){
jQuery.fn.checkEmpty = function() {
return !$.trim(this.html()).length;
};
}(jQuery));
Use :
<div id="selector"></div>
if($("#selector").checkEmpty()){
console.log("Empty");
}else{
console.log("Not Empty");
}
the css solution works, however you do not really get control on the styling. In my case I wanted a bit more space after the line break. Here is a directive I created to handle this (typescript):
function preDirective(): angular.IDirective {
return {
restrict: 'C',
priority: 450,
link: (scope, el, attr, ctrl) => {
scope.$watch(
() => el[0].innerHTML,
(newVal) => {
let lineBreakIndex = newVal.indexOf('\n');
if (lineBreakIndex > -1 && lineBreakIndex !== newVal.length - 1 && newVal.substr(lineBreakIndex + 1, 4) != '</p>') {
let newHtml = `<p>${replaceAll(el[0].innerHTML, '\n\n', '\n').split('\n').join('</p><p>')}</p>`;
el[0].innerHTML = newHtml;
}
}
)
}
};
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
}
angular.module('app').directive('pre', preDirective);
Use:
<div class="pre">{{item.description}}</div>
All it does is wraps each part of the text in to a <p>
tag.
After that you can style it however you want.
raise SystemExit
this worked on the first try, where
self.destroy()
root.destroy()
did not
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
all the above @Uday's code is perfect but only one thing is missing(default config in build.gradle)
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, AndroidLocalize.class);
finish();
startActivity(refresh);
}
Mine was not working just because the languages were not mentioned in the config file(build.gradle)
defaultConfig {
resConfigs "en", "hi", "kn"
}
after that, all languages started running
You can take a look at HTML 5, but I don't think you can restrict the area within you can drag it, just the destination:
http://www.w3schools.com/html/html5_draganddrop.asp
And if you don't mind using some great library, I would encourage you to try Dragula.
I figured it out. The problem was that there were still some pages in the project that hadn't been converted to use "namespaces" as needed in a web application project. I guess I thought that it wouldn't compile if there were still any of those pages around, but if the page didn't reference anything from outside itself it didn't appear to squawk. So when it was saying that it didn't inherit from "System.Web.UI.Page" that was because it couldn't actually find the class "BasePage" at run time because the page itself was not in the WebApplication namespace. I went through all my pages one by one and made sure that they were properly added to the WebApplication namespace and now it not only compiles without issue, it also displays normally. yay!
what a trial converting from website to web application project can be!
Here's a way using only the standard Java library (note that the stream is not closed, your mileage may vary).
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
I learned this trick from "Stupid Scanner tricks" article. The reason it works is because Scanner iterates over tokens in the stream, and in this case we separate tokens using "beginning of the input boundary" (\A), thus giving us only one token for the entire contents of the stream.
Note, if you need to be specific about the input stream's encoding, you can provide the second argument to Scanner
constructor that indicates what character set to use (e.g. "UTF-8").
Hat tip goes also to Jacob, who once pointed me to the said article.
You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:
<Grid>
<DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799" ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False"> </Grid>
C#
Public Class Test
{
public string m_field1_Test{get;set;}
public string m_field2_Test { get; set; }
public Test()
{
m_field1_Test = "field1";
m_field2_Test = "field2";
}
public MainWindow()
{
listTest = new List<Test>();
for (int i = 0; i < 10; i++)
{
obj = new Test();
listTest.Add(obj);
}
this.MyDatagrid.ItemsSource = ListTest;
InitializeComponent();
}
As per the django documentation 2.2 you can use:
To get all fields: Model._meta.get_fields()
To get an individual field: Model._meta.get_field('field name')
ex. Session._meta.get_field('expire_date')
I had the same problem. I found that if I use a DOCTYPE like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
it didn't work. But if I use:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
it did work.
I use the csc.exe compiler called from a .vbs script.
In your xyz.cs script, add the following lines after the directives (my example is for the Renci SSH):
using System;
using Renci;//FOR THE SSH
using System.Net;//FOR THE ADDRESS TRANSLATION
using System.Reflection;//FOR THE Assembly
//+ref>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+res>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+ico>"C:\Program Files (x86)\Microsoft CAPICOM 2.1.0.2 SDK\Samples\c_sharp\xmldsig\resources\Traffic.ico"
The ref, res and ico tags will be picked up by the .vbs script below to form the csc command.
Then add the assembly resolver caller in the Main:
public static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
.
...and add the resolver itself somewhere in the class:
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { String resourceName = new AssemblyName(args.Name).Name + ".dll"; using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { Byte[] assemblyData = new Byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); return Assembly.Load(assemblyData); } }
I name the vbs script to match the .cs filename (e.g. ssh.vbs looks for ssh.cs); this makes running the script numerous times a lot easier, but if you aren't an idiot like me then a generic script could pick up the target .cs file from a drag-and-drop:
Dim name_,oShell,fso Set oShell = CreateObject("Shell.Application") Set fso = CreateObject("Scripting.fileSystemObject") 'TAKE THE VBS SCRIPT NAME AS THE TARGET FILE NAME '################################################ name_ = Split(wscript.ScriptName, ".")(0) 'GET THE EXTERNAL DLL's AND ICON NAMES FROM THE .CS FILE '####################################################### Const OPEN_FILE_FOR_READING = 1 Set objInputFile = fso.OpenTextFile(name_ & ".cs", 1) 'READ EVERYTHING INTO AN ARRAY '############################# inputData = Split(objInputFile.ReadAll, vbNewline) For each strData In inputData if left(strData,7)="//+ref>" then csc_references = csc_references & " /reference:" & trim(replace(strData,"//+ref>","")) & " " end if if left(strData,7)="//+res>" then csc_resources = csc_resources & " /resource:" & trim(replace(strData,"//+res>","")) & " " end if if left(strData,7)="//+ico>" then csc_icon = " /win32icon:" & trim(replace(strData,"//+ico>","")) & " " end if Next objInputFile.Close 'COMPILE THE FILE '################ oShell.ShellExecute "c:\windows\microsoft.net\framework\v3.5\csc.exe", "/warn:1 /target:exe " & csc_references & csc_resources & csc_icon & " " & name_ & ".cs", "", "runas", 2 WScript.Quit(0)
Make sure you have no display property set in the li
tag in my case I had a display: flex
property on my li
tag for some reason.
Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"
Explanation : [How it works]
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.
Hope it work
Other warning
objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int
Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"
[caution: It may void other warning of 64 Bits architecture conversion].
Good Question & Matt's was a good answer. To expand on the syntax a little if the oldtable has an identity a user could run the following:
SELECT col1, col2, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
That would be if the oldtable was scripted something as such:
CREATE TABLE [dbo].[oldtable]
(
[oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[col1] [nvarchar](50) NULL,
[col2] [numeric](18, 0) NULL,
)
Please note that inserted, deleted
means the same thing as inserted CROSS JOIN deleted
and gives every combination of every row. I doubt this is what you want.
Something like this may help get you started...
SELECT
CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
WHEN deleted.primaryKey IS NULL THEN 'This is an insert'
ELSE 'This is an update'
END as Action,
*
FROM
inserted
FULL OUTER JOIN
deleted
ON inserted.primaryKey = deleted.primaryKey
Depending on what you want to do, you then reference the table you are interested in with inserted.userID
or deleted.userID
, etc.
Finally, be aware that inserted
and deleted
are tables and can (and do) contain more than one record.
If you insert 10 records at once, the inserted
table will contain ALL 10 records. The same applies to deletes and the deleted
table. And both tables in the case of an update.
EDIT Examplee Trigger after OPs edit.
ALTER TRIGGER [dbo].[UpdateUserCreditsLeft]
ON [dbo].[Order]
AFTER INSERT,UPDATE,DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE
User
SET
CreditsLeft = CASE WHEN inserted.UserID IS NULL THEN <new value for a DELETE>
WHEN deleted.UserID IS NULL THEN <new value for an INSERT>
ELSE <new value for an UPDATE>
END
FROM
User
INNER JOIN
(
inserted
FULL OUTER JOIN
deleted
ON inserted.UserID = deleted.UserID -- This assumes UserID is the PK on UpdateUserCreditsLeft
)
ON User.UserID = COALESCE(inserted.UserID, deleted.UserID)
END
If the PrimaryKey of UpdateUserCreditsLeft
is something other than UserID, use that in the FULL OUTER JOIN instead.
First use command
pip uninstall pyserial
Then run again
pip install pyserial
The above commands will index it with system interpreter.
You can also use this function,
function optionDisable(selectId, optionIndices)
{
for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
{
document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
}
}
I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.
Method overloading and Method overriding are 2 different concepts completely different. Method overloading is having the same method name but with different signatures. Method overriding is changing the default implementation of base class method in the derived class. Below you can find 2 excellent video tutorials explaining these concepts.
you can simply use your own code but add name for the select tag
<form method="POST" action="index.php?action=contact_agent&agent_id=">
<select name="agent_id">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
then you can access it like this
String agent=request.getparameter("agent_id");
Hope this helps :)
begins the session, you need to say this at the top of a page or before you call session code
session_start();
put a user id in the session to track who is logged in
$_SESSION['user'] = $user_id;
Check if someone is logged in
if (isset($_SESSION['user'])) {
// logged in
} else {
// not logged in
}
Find the logged in user ID
$_SESSION['user']
So on your page
<?php
session_start();
if (isset($_SESSION['user'])) {
?>
logged in HTML and code here
<?php
} else {
?>
Not logged in HTML and code here
<?php
}
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
Add Web Reference is the old-style, deprecated ASP.NET webservices (ASMX) technology (using only the XmlSerializer for your stuff) - if you do this, you get an ASMX client for an ASMX web service. You can do this in just about any project (Web App, Web Site, Console App, Winforms - you name it).
Add Service Reference is the new way of doing it, adding a WCF service reference, which gives you a much more advanced, much more flexible service model than just plain old ASMX stuff.
Since you're not ready to move to WCF, you can also still add the old-style web reference, if you really must: when you do a "Add Service Reference", on the dialog that comes up, click on the [Advanced] button in the button left corner:
and on the next dialog that comes up, pick the [Add Web Reference] button at the bottom.
You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven
<repository>
<id>Spark repository</id>
<url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>
And then the dependency:
<dependency>
<groupId>spark</groupId>
<artifactId>spark</artifactId>
<version>1.2.0</version>
</dependency>
In terms of running a file with spark commands: you can simply do this:
echo"
import org.apache.spark.sql.*
ssc = new SQLContext(sc)
ssc.sql("select * from mytable").collect
" > spark.input
Now run the commands script:
cat spark.input | spark-shell
You could use something like the following
scp -r username_Linuxmachine@LinuxMachineAddress:Path/To/File Path/To/Local/System/Directory
This will copy the File
to the specified local directory on the system you are currently working on.
The -r
flag tells scp
to recursively copy if the remote path is indeed a directory.
If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.
The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.
That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).
See the CSS 2.1 standard, section 17.5.3. When you use display:table-row
, the height of the DIV is solely determined by the height of the table-cell
elements in it. Thus, margin, padding, and height on those elements have no effect.
This is by far (after hours of googling and trying scripts) the simplest to set up and nicest uploader I've found
https://github.com/FineUploader/fine-uploader
It doesn't require APC or any other external PHP libraries, I can get file progress feedback on a shared host, and it claims to support html5 drag and drop (personally untested) and multiple file uploads.
Log from Silverlight
When using NLog with Silverlight you can send the trace to the server side via the provided web service. You can also write to a local file in the Isolated Storage, which come in handy if the web server is unavailable. See here for details, i.e. use something like this to make yourself a target:
namespace NLogTargets
{
[Target("IsolatedStorageTarget")]
public sealed class IsolatedStorageTarget : TargetWithLayout
{
IsolatedStorageFile _storageFile = null;
string _fileName = "Nlog.log"; // Default. Configurable through the 'filename' attribute in nlog.config
public IsolatedStorageTarget()
{
}
~IsolatedStorageTarget()
{
if (_storageFile != null)
{
_storageFile.Dispose();
_storageFile = null;
}
}
public string filename
{
set
{
_fileName = value;
}
get
{
return _fileName;
}
}
protected override void Write(LogEventInfo logEvent)
{
try
{
writeToIsolatedStorage(this.Layout.Render(logEvent));
}
catch (Exception e)
{
// Not much to do about his....
}
}
public void writeToIsolatedStorage(string msg)
{
if (_storageFile == null)
_storageFile = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
// The isolated storage is limited in size. So, when approaching the limit
// simply purge the log file. (Yeah yeah, the file should be circular, I know...)
if (_storageFile.AvailableFreeSpace < msg.Length * 100)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Truncate, FileAccess.Write, isolatedStorage))
{ }
}
// Write to isolated storage
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Append, FileAccess.Write, isolatedStorage))
{
using (TextWriter writer = new StreamWriter(stream))
{
writer.WriteLine(msg);
}
}
}
}
}
}