I you only want to apply the change only for one field, you could try serializing the field
class MyModel < ActiveRecord::Base
serialize :content
attr_accessible :content, :title
end
I just used the event input and it worked fine as follows:
in .html file :
<input type="text" class="form-control" (input)="onSearchChange($event.target.value)">
in .ts file :
onSearchChange(searchValue: string): void {
console.log(searchValue);
}
If you want only the scheme and authority part of the request (protocol, host and port) use
Request.Url.GetLeftPart(UriPartial.Authority)
You can add global variable:
private Context context;
then assign the context from here:
@Override
public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}
Happy Codding :)
Just use the below code. It will shadow surround the entire DIV
-webkit-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
-moz-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
Hope this will work
please remove " runat="server" " from "form" tag then it will definetly works.
The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.
You can't follow the cursor with a DIV
, but you can draw a DIV
when moving the cursor!
$(document).on('mousemove', function(e){
$('#your_div_id').css({
left: e.pageX,
top: e.pageY
});
});
That div must be off the float, so position: absolute
should be set.
If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m
in with backticks like so:
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh
link_to "+ Service", controller_action_path(:account_id => acct.id)
If it is still not working check the path:
$ rake routes
I removed these lines as below :
before :
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar1"
android:layout_width="match_parent"
android:layout_height="@attr/actionBarSize"
android:minHeight="@attr/actionBarSize"
android:layout_alignParentTop="true" >
after :
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true" >
Instead of "@attr/actionBarSize" put specific dimens it works for me.
I also had this problem. In my case it was because of no grants were assigned to MySQL user. Assigning grants to MySQL user which my app uses resolved the issue:
grant select, insert, delete, update on my_db.* to 'my_user'@'%';
You probably have a forward declaration of the class, but haven't included the header:
#include <sstream>
//...
QString Stats_Manager::convertInt(int num)
{
std::stringstream ss; // <-- also note namespace qualification
ss << num;
return ss.str();
}
I'm reposting my answer from here because I saw it also fits in here. It allows removing multiple values or removing only duplicates of these values and returns either a new list or modifies the given list in place.
def removed(items, original_list, only_duplicates=False, inplace=False):
"""By default removes given items from original_list and returns
a new list. Optionally only removes duplicates of `items` or modifies
given list in place.
"""
if not hasattr(items, '__iter__') or isinstance(items, str):
items = [items]
if only_duplicates:
result = []
for item in original_list:
if item not in items or item not in result:
result.append(item)
else:
result = [item for item in original_list if item not in items]
if inplace:
original_list[:] = result
else:
return result
Docstring extension:
"""
Examples:
---------
>>>li1 = [1, 2, 3, 4, 4, 5, 5]
>>>removed(4, li1)
[1, 2, 3, 5, 5]
>>>removed((4,5), li1)
[1, 2, 3]
>>>removed((4,5), li1, only_duplicates=True)
[1, 2, 3, 4, 5]
# remove all duplicates by passing original_list also to `items`.:
>>>removed(li1, li1, only_duplicates=True)
[1, 2, 3, 4, 5]
# inplace:
>>>removed((4,5), li1, only_duplicates=True, inplace=True)
>>>li1
[1, 2, 3, 4, 5]
>>>li2 =['abc', 'def', 'def', 'ghi', 'ghi']
>>>removed(('def', 'ghi'), li2, only_duplicates=True, inplace=True)
>>>li2
['abc', 'def', 'ghi']
"""
You should be clear about what you really want to do, modify an existing list, or make a new list with the specific items missing. It's important to make that distinction in case you have a second reference pointing to the existing list. If you have, for example...
li1 = [1, 2, 3, 4, 4, 5, 5]
li2 = li1
# then rebind li1 to the new list without the value 4
li1 = removed(4, li1)
# you end up with two separate lists where li2 is still pointing to the
# original
li2
# [1, 2, 3, 4, 4, 5, 5]
li1
# [1, 2, 3, 5, 5]
This may or may not be the behaviour you want.
This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:
I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM")
, drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".
Processors today work with many levels of cascading memory areas. So the CPU will have a bunch of memory that is on the CPU chip itself. It has very fast access to this memory. There are different levels of cache each one slower access ( and larger ) than the next, until you get to system memory which is not on the CPU and is relatively much slower to access.
Logically, to the CPU's instruction set you just refer to memory addresses in a giant virtual address space. When you access a single memory address the CPU will go fetch it. in the old days it would fetch just that single address. But today the CPU will fetch a bunch of memory around the bit you asked for, and copy it into the cache. It assumes that if you asked for a particular address that is is highly likely that you are going to ask for an address nearby very soon. For example if you were copying a buffer you would read and write from consecutive addresses - one right after the other.
So today when you fetch an address it checks the first level of cache to see if it already read that address into cache, if it doesn't find it, then this is a cache miss and it has to go out to the next level of cache to find it, until it eventually has to go out into main memory.
Cache friendly code tries to keep accesses close together in memory so that you minimize cache misses.
So an example would be imagine you wanted to copy a giant 2 dimensional table. It is organized with reach row in consecutive in memory, and one row follow the next right after.
If you copied the elements one row at a time from left to right - that would be cache friendly. If you decided to copy the table one column at a time, you would copy the exact same amount of memory - but it would be cache unfriendly.
make sure that u have used this one
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBEwmfL0GaZmdVqdTxxxxxxxx-rVgvY" />
not this..
<meta-data
android:name="com.google.android.gms.version"
android:value="AIzaSyBEwmfL0GaZmdVqdTCvxxxxxxx-rVgvY" />
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host
). After clearing the cookies on a domain try the following to see the results:
if (document.cookie.length==0)
{
document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Cookies disabled');}
else
{
document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
else {alert('document.cookies.length = '+document.cookies.length);}
}
}
Unfortunately, no. You will have to cast each value individually.
Here is another way to find out apps package name and launcher activity.
Step1: Start "adb logcat" in command prompt.
Step2: Open the app (either in emulator or real device)
Your Ubuntu definitely has a sufficiently recent version of g++
. The flag to use is -std=c++0x
.
The answer helped me a lot in my situation so thanks for that. However for future reference people should bind to a model and then validate. This post from Phil Haack describes this for MVC 2. http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
Hope this helps someone.
This whole setup seems a little unstable to me.
Talk to the ffmpegx folks about having a GUI front-end over a command-line backend. It doesn't seem to bother them.
Indeed, I submit that a GUI (or web) front-end over a command-line backend is actually more stable, since you have a very, very clean interface between GUI and command. The command can evolve at a different pace from the web, as long as the command-line options are compatible, you have no possibility of breakage.
While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.
Logging has greatly improved in heroku!
$ heroku logs -n 500
Better!
$ heroku logs --tail
references: http://devcenter.heroku.com/articles/logging
UPDATED
These are no longer add-ons, but part of the default functionality :)
I do just like below, after you set your column AsEnumarable you can sort, order or how you want.
_dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();
first, check that the array actually exists, you could try something like
if (isset($votes)) {
// Do bad things to the votes array
}
Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.
var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.5472,12.282715),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
This will produce a string 96 characters in length, from the Base64 range (uppers, lowers, numbers, + and /). Adding 3 "NEWID()" will increase the length by 32, with no Base64 padding (=).
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
If you are applying this to a set, make sure to introduce something from that set so that the NEWID() is recomputed, otherwise you'll get the same value each time:
SELECT
U.UserName
, LEFT(PseudoRandom.StringValue, LEN(U.Pwd)) AS FauxPwd
FROM Users U
CROSS APPLY (
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), U.UserID) -- Causes a recomute of all NEWID() calls
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
) PseudoRandom
I had a similar problem and for encrypt/decrypt i came up with this solution:
public static byte[] generateKey(String password) throws Exception
{
byte[] keyStart = password.getBytes("UTF-8");
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(keyStart);
kgen.init(128, sr);
SecretKey skey = kgen.generateKey();
return skey.getEncoded();
}
public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(fileData);
return decrypted;
}
To save a encrypted file to sd do:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();
To decode a file use:
byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);
For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/
Actually this is kind of strange, with the string conversions - which the membership provider does to put them into config files. Hashes and salts are binary blobs, you don't need to convert them to strings unless you want to put them into text files.
In my book, Beginning ASP.NET Security, (oh finally, an excuse to pimp the book) I do the following
static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)
{
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextWithSaltBytes =
new byte[plainText.Length + salt.Length];
for (int i = 0; i < plainText.Length; i++)
{
plainTextWithSaltBytes[i] = plainText[i];
}
for (int i = 0; i < salt.Length; i++)
{
plainTextWithSaltBytes[plainText.Length + i] = salt[i];
}
return algorithm.ComputeHash(plainTextWithSaltBytes);
}
The salt generation is as the example in the question. You can convert text to byte arrays using Encoding.UTF8.GetBytes(string)
. If you must convert a hash to its string representation you can use Convert.ToBase64String
and Convert.FromBase64String
to convert it back.
You should note that you cannot use the equality operator on byte arrays, it checks references and so you should simply loop through both arrays checking each byte thus
public static bool CompareByteArrays(byte[] array1, byte[] array2)
{
if (array1.Length != array2.Length)
{
return false;
}
for (int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
Always use a new salt per password. Salts do not have to be kept secret and can be stored alongside the hash itself.
These steps are working on CentOS 6.5 so they should work on CentOS 7 too:
(EDIT - exactly the same steps work for MariaDB 10.3 on CentOS 8)
yum remove mariadb mariadb-server
rm -rf /var/lib/mysql
If your datadir in /etc/my.cnf points to a different directory, remove that directory instead of /var/lib/mysqlrm /etc/my.cnf
the file might have already been deleted at step 1rm ~/.my.cnf
yum install mariadb mariadb-server
[EDIT] - Update for MariaDB 10.1 on CentOS 7
The steps above worked for CentOS 6.5 and MariaDB 10.
I've just installed MariaDB 10.1 on CentOS 7 and some of the steps are slightly different.
Step 1 would become:
yum remove MariaDB-server MariaDB-client
Step 5 would become:
yum install MariaDB-server MariaDB-client
The other steps remain the same.
For anyone finding this, swipe on carousel appears to be native as of about 5 days ago (20 Oct 2018) as per
https://github.com/twbs/bootstrap/pull/25776
https://deploy-preview-25776--twbs-bootstrap4.netlify.com/docs/4.1/components/carousel/
The following function will allow differentiating between empty strings and undefined cookies. Undefined cookies will correctly return undefined
and not an empty string unlike some of the other answers here.
function getCookie(name) {
return (document.cookie.match('(^|;) *'+name+'=([^;]*)')||[])[2];
}
The above worked fine for me on all browsers I checked, but as mentioned by @vanovm in comments, as per the specification the key/value may be surrounded by whitespace. Hence the following is more standard compliant.
function getCookie(name) {
return (document.cookie.match('(?:^|;)\\s*'+name.trim()+'\\s*=\\s*([^;]*?)\\s*(?:;|$)')||[])[1];
}
According to W3Schools.com,
The center element was deprecated in HTML 4.01, and is not supported in XHTML 1.0 Strict DTD.
The HTML 4.01 spec gives this reason for deprecating the tag:
The CENTER element is exactly equivalent to specifying the DIV element with the align attribute set to "center".
The following will give you an array of the type you want while preserving type safety.
PCB[] getAll(Class<PCB[]> arrayType) {
PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
list.clear();
return res;
}
How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.
This is what worked for me
When I tried the Accepted ans my Android Studio hangs on start-up
This is the link
and This is the Command
$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1
Just for diversity I will post variation of https://stackoverflow.com/a/2173421/102484 , because that solution leads to message "Terminated" in my environment:
trap 'test -z "$intrap" && export intrap=1 && kill -- -$$' SIGINT SIGTERM EXIT
For people who want to use another diff tool not listed in git, say with nvim
. here is what I ended up using:
git config --global alias.d difftool -x <tool name>
In my case, I set <tool name>
to nvim -d
and invoke the diff command with
git d <file>
There is a lot of confusion about Repositories and Projects. In the past both terms were used pretty much interchangeably by the users and the GitHub's very own documentation. This is reflected by some of the answers and comments here that explain the subtle differences between those terms and when the one was preferred over the other. The difference were always subtle, e.g. like the issue tracker being part of the project but not part of the repository which might be thought of as a strictly git thing etc.
Currently repos and projects refer to a different kinds of entities that have separate APIs:
Since then it is no longer correct to call the repo a project or vice versa. Note that it is often confused in the official documentation and it is unfortunate that a term that was already widely used has been chosen as the name of the new entity but this is the case and we have to live with that.
The consequence is that repos and projects are usually confused and every time you read about GitHub projects you have to wonder if it's really about the projects or about repos. Had they chosen some other name or an abbreviation like "proj" then we could know that what is discussed is the new type of entity, a precise object with concrete properties, or a general speaking repo-like projectish kind of thingy.
The term that is usually unambiguous is "project board".
The first endpoint in the documentation of the Projects API:
is described as: List repository projects. It means that a repository can have many projects. So those two cannot mean the same thing. It includes Response if projects are disabled:
{
"message": "Projects are disabled for this repo",
"documentation_url": "https://developer.github.com/v3"
}
which means that some repos can have projects disabled. Again, those cannot be the same thing when a repo can have projects disabled.
There are some other interesting endpoints:
POST /repos/:owner/:repo/projects
POST /orgs/:org/projects
but there is no:
POST /users/:user/projects
Which leads us to another difference:
1. Repositories can belong to users or organizations
2. Projects can belong to repositories or organizations
or, more importantly:
1. Projects can belong to repositories but not the other way around
2. Projects can belong to organizations but not to users
3. Repositories can belong to organizations and to users
See also:
I know it's confusing. I tried to explain it as precisely as I could.
It's good practise to extend from a baseController
and implement some base functions
implement a function to check if the user instance is null like this
if the user form the Userinterface
then there is no user logged in
/**
*/
class BaseController extends AbstractController
{
/**
* @return User
*/
protected function getUser(): ?User
{
return parent::getUser();
}
/**
* @return bool
*/
protected function isUserLoggedIn(): bool
{
return $this->getUser() instanceof User;
}
}
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
SQL doesn't return any ordering by default because it's faster this way. It doesn't have to go through your data first and then decide what to do.
You need to add an order by clause, and probably order by which ever ID you expect. (There's a duplicate of names, thus I'd assume you want One.ID)
select * From one
inner join two
ON one.one_name = two.one_name
ORDER BY one.ID
Add new column to Table with default value.
ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE
Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.
The .add() method adds the selected elements to the result set:
// classA OR classB
jQuery('.classA').add('.classB');
It's more verbose than '.classA, .classB'
, but lets you build more complex selectors like the following:
// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));
#######################
### the img page ###
#######################
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#f').live('change' ,function(){
$('#fo').ajaxForm({target: '#d'}).submit();
});
});
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
<input type="file" name="f" id="f" value="start upload" />
<input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>
#############################
### the nextimg page ###
#############################
<?php
$name=$_FILES['f']['name'];
$tmp=$_FILES['f']['tmp_name'];
$new=time().$name;
$new="upload/".$new;
move_uploaded_file($tmp,$new);
if($_FILES['f']['error']==0)
{
?>
<h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
}
?>
There is no built-in way. You can have MyClass implement the IClonable
interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code.
For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code.
Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc.
You can simply override BaseActivity onActivityResult
on fragment baseActivity.startActivityForResult
.
On BaseActivity add interface and override onActivityResult.
private OnBaseActivityResult baseActivityResult;
public static final int BASE_RESULT_RCODE = 111;
public interface OnBaseActivityResult{
void onBaseActivityResult(int requestCode, int resultCode, Intent data);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(getBaseActivityResult() !=null && requestCode == BASE_RESULT_RCODE){
getBaseActivityResult().onBaseActivityResult(requestCode, resultCode, data);
setBaseActivityResult(null);
}
On Fragment implements OnBaseActivityResult
@Override
public void onBaseActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("RQ","OnBaseActivityResult");
if (data != null) {
Log.d("RQ","OnBaseActivityResult + Data");
Bundle arguments = data.getExtras();
}
}
This workaround will do the trick.
Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:
- Install Visual Studio 2008
- Install the service Package 1 (SP1)
- Install SQL Server 2008 r2
Look at SignalR Tests for the feature.
Test "SendToUser" takes automatically the user identity passed by using a regular owin authentication library.
The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.
If there are are no duplicate elements or you don't care about them, then you can use the Set class:
a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false
Behind the scenes this uses
all? { |o| set.include?(o) }
This is a mintty version problem alternatively use cmd. To kill server process just run this command:
taskkill -F -IM node.exe
Using Scanner
s, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().
On the other hand, If you split by space (line.split(" ")
), the code will fail if you try to read a file with a different whitespace delimiter. If split()
expects you to write a regular expression, and it does matching anyway, use split("\\s")
instead, that matches a "bit" more whitespace than just a space character.
P.S.: Sorry, I don't have right to comment on already given answers.
This is coming from JPA
. In a very simple way:
persist(entity)
should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).
merge(entity)
should be used, to put entity back to persistence context if the entity was detached and was changed.
Old thread but thought I would update;
File theFile = .......
String theName = theFile.getName(); // Get the file name
String thePath = theFile.getAbsolutePath(); // Get the full
More info can be found here; Android File Class
awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'
Add the numbers in $2
(second column) in sum
(variables are auto-initialized to zero by awk
) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.
awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'
If you want to use the shebang notation, you could write:
#!/bin/awk
{ sum += $2 }
END { if (NR > 0) print sum / NR }
You can also control the format of the average with printf()
and a suitable format ("%13.6e\n"
, for example).
You can also generalize the code to average the Nth column (with N=2
in this sample) using:
awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'
You put your template in the wrong place. From the Flask docs:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates
Assuming the simplest option (installing rsync on the remote host) isn't feasible, you can use sshfs to mount the remote locally, and rsync from the mount directory. That way you can use all the options rsync offers, for example --exclude
.
Something like this should do:
sshfs user@server: sshfsdir
rsync --recursive --exclude=whatever sshfsdir/path/on/server /where/to/store
Note that the effectiveness of rsync (only transferring changes, not everything) doesn't apply here. This is because for that to work, rsync must read every file's contents to see what has changed. However, as rsync runs only on one host, the whole file must be transferred there (by sshfs). Excluded files should not be transferred, however.
If your solution contains two projects interacting with each other and both using one same reference, And if version of respective reference is different in both projects; Then also such errors occurred. Keep updating all references to latest one.
Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.
f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:
alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
List Of Key codes:
a - z-> 29 - 54
"0" - "9"-> 7 - 16
BACK BUTTON - 4, MENU BUTTON - 82
UP-19, DOWN-20, LEFT-21, RIGHT-22
SELECT (MIDDLE) BUTTON - 23
SPACE - 62, SHIFT - 59, ENTER - 66, BACKSPACE - 67
$("body").stop().animate({
scrollTop: 0
}, 500, 'swing', function () {
console.log(confirm('Like This'))
}
);
Yes , Provisioning profiles which are for distribution purpose, i.e. Distrutions provisioning profiles do not support debugging and gives this error. Simply create and use debug provisioning profile (take care of this when creating provisioning profile from developer.apple.com account).
Use this library: https://github.com/lukas-krecan/JsonUnit
Pom:
<dependency>
<groupId>net.javacrumbs.json-unit</groupId>
<artifactId>json-unit-assertj</artifactId>
<version>2.24.0</version>
<scope>test</scope>
</dependency>
IGNORING_ARRAY_ORDER - ignores order in arrays
assertThatJson("{\"test\":[1,2,3]}")
.when(Option.IGNORING_ARRAY_ORDER)
.isEqualTo("{\"test\": [3,2,1]}");
Change
OnClientClick="return validateView();ShowDiv1();">
to
OnClientClick="javascript: if(validateView()) ShowDiv1();">
Well, I don't understand why are you used transaction in case when you make a select
.
Transaction is useful when you make changes (add, edit or delete) data from database.
Remove transaction unless you use insert
, update
or delete
statements
Also you can convert any number in any base to hex. Use this one line code here it's easy and simple to use:
hex(int(n,x)).replace("0x","")
You have a string n
that is your number and x
the base of that number. First, change it to integer and then to hex but hex has 0x
at the first of it so with replace
we remove it.
Try:
select id, game, min(point) from t
group by id
You can just use return
.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined
to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
Switch to the branch from which you created the pull request:
$ git checkout pull-request-branch
Overwrite the modified file(s) with the file in another branch, let's consider it's master:
git checkout origin/master -- src/main/java/HelloWorld.java
Commit and push it to the remote:
git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch
Note: This answer is a pure Gradle answer, I use this in IntelliJ on a regular basis but I don't know how the integration is with Android Studio. I am a believer in knowing what is going on for me, so this is how I use Gradle and Android.
TL;DR Full Example - https://github.com/ethankhall/driving-time-tracker/
Disclaimer: This is a project I am/was working on.
Gradle has a defined structure ( that you can change, link at the bottom tells you how ) that is very similar to Maven if you have ever used it.
Project Root
+-- src
| +-- main (your project)
| | +-- java (where your java code goes)
| | +-- res (where your res go)
| | +-- assets (where your assets go)
| | \-- AndroidManifest.xml
| \-- instrumentTest (test project)
| \-- java (where your java code goes)
+-- build.gradle
\-- settings.gradle
If you only have the one project, the settings.gradle file isn't needed. However you want to add more projects, so we need it.
Now let's take a peek at that build.gradle file. You are going to need this in it (to add the android tools)
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.3'
}
}
Now we need to tell Gradle about some of the Android parts. It's pretty simple. A basic one (that works in most of my cases) looks like the following. I have a comment in this block, it will allow me to specify the version name and code when generating the APK.
build.gradle
apply plugin: "android"
android {
compileSdkVersion 17
/*
defaultConfig {
versionCode = 1
versionName = "0.0.0"
}
*/
}
Something we are going to want to add, to help out anyone that hasn't seen the light of Gradle yet, a way for them to use the project without installing it.
build.gradle
task wrapper(type: org.gradle.api.tasks.wrapper.Wrapper) {
gradleVersion = '1.4'
}
So now we have one project to build. Now we are going to add the others. I put them in a directory, maybe call it deps, or subProjects. It doesn't really matter, but you will need to know where you put it. To tell Gradle where the projects are you are going to need to add them to the settings.gradle.
Directory Structure:
Project Root
+-- src (see above)
+-- subProjects (where projects are held)
| +-- reallyCoolProject1 (your first included project)
| \-- See project structure for a normal app
| \-- reallyCoolProject2 (your second included project)
| \-- See project structure for a normal app
+-- build.gradle
\-- settings.gradle
settings.gradle:
include ':subProjects:reallyCoolProject1'
include ':subProjects:reallyCoolProject2'
The last thing you should make sure of is the subProjects/reallyCoolProject1/build.gradle has apply plugin: "android-library"
instead of apply plugin: "android"
.
Like every Gradle project (and Maven) we now need to tell the root project about it's dependency. This can also include any normal Java dependencies that you want.
build.gradle
dependencies{
compile 'com.fasterxml.jackson.core:jackson-core:2.1.4'
compile 'com.fasterxml.jackson.core:jackson-databind:2.1.4'
compile project(":subProjects:reallyCoolProject1")
compile project(':subProjects:reallyCoolProject2')
}
I know this seems like a lot of steps, but they are pretty easy once you do it once or twice. This way will also allow you to build on a CI server assuming you have the Android SDK installed there.
NDK Side Note: If you are going to use the NDK you are going to need something like below. Example build.gradle file can be found here: https://gist.github.com/khernyo/4226923
build.gradle
task copyNativeLibs(type: Copy) {
from fileTree(dir: 'libs', include: '**/*.so' ) into 'build/native-libs'
}
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }
clean.dependsOn 'cleanCopyNativeLibs'
tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
pkgTask.jniDir new File('build/native-libs')
}
Sources:
In addition to ways already mentioned.. can use 'viewitems', 'viewkeys', 'viewvalues'
>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]
Or
>>> list(d.iteritems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.iterkeys())
[320, 321, 322]
>>> list(d.itervalues())
[1, 0, 3]
or using itemgetter
>>> from operator import itemgetter
>>> map(itemgetter(0), dd.items()) #### for keys
['323', '332']
>>> map(itemgetter(1), dd.items()) #### for values
['3323', 232]
I have had to do this several times and have researched many different solutions.
The solution I find in most elegant and easy to accomplish can be implemented as such.
the interface will contain signatures of any members you wish to call.
public interface IExampleProxy
{
string HelloWorld( string name );
}
Its important to keep this project clean and lite. It is a project that both AppDomain
's can reference and will allow us to not reference the Assembly
we wish to load in seprate domain from our client assembly.
AppDomain
.This project as with the client proj will reference the proxy proj and you will implement the interface.
public interface Example : MarshalByRefObject, IExampleProxy
{
public string HelloWorld( string name )
{
return $"Hello '{ name }'";
}
}
AppDomain
.So, now we create a new AppDomain
. Can specify the base location for assembly references. Probing will check for dependent assemblies in GAC and in current directory and the AppDomain
base loc.
// set up domain and create
AppDomainSetup domaininfo = new AppDomainSetup
{
ApplicationBase = System.Environment.CurrentDirectory
};
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain exampleDomain = AppDomain.CreateDomain("Example", adevidence, domaininfo);
// assembly ant data names
var assemblyName = "<AssemblyName>, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null|<keyIfSigned>";
var exampleTypeName = "Example";
// Optional - get a reflection only assembly type reference
var @type = Assembly.ReflectionOnlyLoad( assemblyName ).GetType( exampleTypeName );
// create a instance of the `Example` and assign to proxy type variable
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( assemblyName, exampleTypeName );
// Optional - if you got a type ref
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( @type.Assembly.Name, @type.Name );
// call any members you wish
var stringFromOtherAd = proxy.HelloWorld( "Tommy" );
// unload the `AppDomain`
AppDomain.Unload( exampleDomain );
if you need to, there are a ton of different ways to load an assembly. You can use a different way with this solution. If you have the assembly qualified name then I like to use the CreateInstanceAndUnwrap
since it loads the assembly bytes and then instantiates your type for you and returns an object
that you can simple cast to your proxy type or if you not that into strongly-typed code you could use the dynamic language runtime and assign the returned object to a dynamic
typed variable then just call members on that directly.
This allows to load an assembly that your client proj doesnt have reference to in a seperate AppDomain
and call members on it from client.
The key is to either make sure you code either derives MarshalByRefObject
or is serializable.
`MarshalByRefObject will allow you to configure the lifetime of the domain its in. Example, say you want the domain to destroy if the proxy hasnt been called in 20 minutes.
can this help?
select
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d
It's a horrible thing to do, as everybody else has said, but if you really are intent on doing it, use this code, and put a load of returns at the top of the page's source:
<html>
<head>
<script>
function disableClick(){
document.onclick=function(event){
if (event.button == 2) {
alert('Right Click Message');
return false;
}
}
}
</script>
</head>
<body onLoad="disableClick()">
</body>
</html>
Apache Commons offers commons-graph. Under http://svn.apache.org/viewvc/commons/sandbox/graph/trunk/ one can inspect the source. Sample API usage is in the SVN, too. See https://issues.apache.org/jira/browse/SANDBOX-458 for a list of implemented algorithms, also compared with Jung, GraphT, Prefuse, jBPT
Google Guava if you need good datastructures only.
JGraphT is a graph library with many Algorithms implemented and having (in my oppinion) a good graph model. Helloworld Example. License: LGPL+EPL.
JUNG2 is also a BSD-licensed library with the data structure similar to JGraphT. It offers layouting algorithms, which are currently missing in JGraphT. The most recent commit is from 2010 and packages hep.aida.*
are LGPL (via the colt library, which is imported by JUNG). This prevents JUNG from being used in projects under the umbrella of ASF and ESF. Maybe one should use the github fork and remove that dependency. Commit f4ca0cd is mirroring the last CVS commit. The current commits seem to remove visualization functionality. Commit d0fb491c adds a .gitignore
.
Prefuse stores the graphs using a matrix structure, which is not memory efficient for sparse graphs. License: BSD
Eclipse Zest has built in graph layout algorithms, which can be used independently of SWT. See org.eclipse.zest.layouts.algorithms. The graph structure used is the one of Eclipse Draw2d, where Nodes are explicit objects and not injected via Generics (as it happens in Apache Commons Graph, JGraphT, and JUNG2).
That is because you have an output:
?>
<?php
results in blank line output.
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
Combine all your PHP codes and make sure you don't have any spaces at the beginning of the file.
also after header('location: index.php');
add exit();
if you have any other scripts bellow.
Also move your redirect header after the last if
.
If there is content, then you can also redirect by injecting javascript:
<?php
echo "<script>window.location.href='target.php';</script>";
exit;
?>
Hope this will help you..
var list = [];
$(document).ready(function () {
$('#test').click(function () {
var oRows = $('#MainContent_Table1 tr').length;
$('#MainContent_Table1 tr').each(function (index) {
list.push(this.cells[0].innerHTML);
});
});
});
My answer
/**
* Display form to reply comment
*/
function displayReplyForm(commentId) {
var replyForm = $('#reply-form-' + commentId);
if (replyForm.css('display') == 'block') { // Current display
replyForm.css('display', 'none');
} else { // Hide reply form
replyForm.css('display', 'block');
}
}
Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.
I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.
If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.
I was having this same problem, and tried all the above solutions with no success. I finally solved the problem by deleting the entire query and creating a new one.
The new one had the exact same settings as the one that didn't work (literally the same query definition as I simply copied the old one).
I have no idea why this solved the problem, but it did.
What are the problems of static and stack?
The problem with "static" allocation is that the allocation is made at compile-time: you can't use it to allocate some variable number of data, the number of which isn't known until run-time.
The problem with allocating on the "stack" is that the allocation is destroyed as soon as the subroutine which does the allocation returns.
I could write an entire application without allocate variables in the heap?
Perhaps but not a non-trivial, normal, big application (but so-called "embedded" programs might be written without the heap, using a subset of C++).
What garbage collector does ?
It keeps watching your data ("mark and sweep") to detect when your application is no longer referencing it. This is convenient for the application, because the application doesn't need to deallocate the data ... but the garbage collector might be computationally expensive.
Garbage collectors aren't a usual feature of C++ programming.
What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?
Learn the C++ mechanisms for deterministic memory deallocation:
Simply just append your fields and their values to the elements:
$user->roles()->sync([
1 => ['F1' => 'F1 Updated']
]);
You can use filter for it:
filter(lambda x: self.states[x], range(len(self.states)))
The range
here enumerates elements of your list and since we want only those where self.states
is True
, we are applying a filter based on this condition.
For Python > 3.0:
list(filter(lambda x: self.states[x], range(len(self.states))))
I've written a class to perform text with outline and still support all the other attributes and drawing of a normal text view.
it basically uses the super.onDraw(Canves canvas)
on the TextView
but draws twice with different styles.
hope this helps.
public class TextViewOutline extends TextView {
// constants
private static final int DEFAULT_OUTLINE_SIZE = 0;
private static final int DEFAULT_OUTLINE_COLOR = Color.TRANSPARENT;
// data
private int mOutlineSize;
private int mOutlineColor;
private int mTextColor;
private float mShadowRadius;
private float mShadowDx;
private float mShadowDy;
private int mShadowColor;
public TextViewOutline(Context context) {
this(context, null);
}
public TextViewOutline(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(attrs);
}
private void setAttributes(AttributeSet attrs){
// set defaults
mOutlineSize = DEFAULT_OUTLINE_SIZE;
mOutlineColor = DEFAULT_OUTLINE_COLOR;
// text color
mTextColor = getCurrentTextColor();
if(attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.TextViewOutline);
// outline size
if (a.hasValue(R.styleable.TextViewOutline_outlineSize)) {
mOutlineSize = (int) a.getDimension(R.styleable.TextViewOutline_outlineSize, DEFAULT_OUTLINE_SIZE);
}
// outline color
if (a.hasValue(R.styleable.TextViewOutline_outlineColor)) {
mOutlineColor = a.getColor(R.styleable.TextViewOutline_outlineColor, DEFAULT_OUTLINE_COLOR);
}
// shadow (the reason we take shadow from attributes is because we use API level 15 and only from 16 we have the get methods for the shadow attributes)
if (a.hasValue(R.styleable.TextViewOutline_android_shadowRadius)
|| a.hasValue(R.styleable.TextViewOutline_android_shadowDx)
|| a.hasValue(R.styleable.TextViewOutline_android_shadowDy)
|| a.hasValue(R.styleable.TextViewOutline_android_shadowColor)) {
mShadowRadius = a.getFloat(R.styleable.TextViewOutline_android_shadowRadius, 0);
mShadowDx = a.getFloat(R.styleable.TextViewOutline_android_shadowDx, 0);
mShadowDy = a.getFloat(R.styleable.TextViewOutline_android_shadowDy, 0);
mShadowColor = a.getColor(R.styleable.TextViewOutline_android_shadowColor, Color.TRANSPARENT);
}
a.recycle();
}
PFLog.d("mOutlineSize = " + mOutlineSize);
PFLog.d("mOutlineColor = " + mOutlineColor);
}
private void setPaintToOutline(){
Paint paint = getPaint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(mOutlineSize);
super.setTextColor(mOutlineColor);
super.setShadowLayer(mShadowRadius, mShadowDx, mShadowDy, mShadowColor);
}
private void setPaintToRegular() {
Paint paint = getPaint();
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(0);
super.setTextColor(mTextColor);
super.setShadowLayer(0, 0, 0, Color.TRANSPARENT);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setPaintToOutline();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public void setTextColor(int color) {
super.setTextColor(color);
mTextColor = color;
}
@Override
public void setShadowLayer(float radius, float dx, float dy, int color) {
super.setShadowLayer(radius, dx, dy, color);
mShadowRadius = radius;
mShadowDx = dx;
mShadowDy = dy;
mShadowColor = color;
}
public void setOutlineSize(int size){
mOutlineSize = size;
}
public void setOutlineColor(int color){
mOutlineColor = color;
}
@Override
protected void onDraw(Canvas canvas) {
setPaintToOutline();
super.onDraw(canvas);
setPaintToRegular();
super.onDraw(canvas);
}
}
attr.xml
<declare-styleable name="TextViewOutline">
<attr name="outlineSize" format="dimension"/>
<attr name="outlineColor" format="color|reference"/>
<attr name="android:shadowRadius"/>
<attr name="android:shadowDx"/>
<attr name="android:shadowDy"/>
<attr name="android:shadowColor"/>
</declare-styleable>
One can issue the SQL*Plus command SET TIMING ON
to get wall-clock times, but one can't take, for example, fetch time out of that trivially.
The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY
will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.
Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".
DECLARE @start [datetime] = 2010/4/1;
Should be...
DECLARE @start [datetime] = '2010-04-01';
The one you have is dividing 2010 by 4, then by 1, then converting to a date. Which is the 57.5th day from 1900-01-01.
Try SELECT @start
after your initialisation to check if this is correct.
value_counts
is a Series method rather than a DataFrame method (and you are trying to use it on a DataFrame, clean
). You need to perform this on a specific column:
clean[column_name].value_counts()
It doesn't usually make sense to perform value_counts
on a DataFrame, though I suppose you could apply it to every entry by flattening the underlying values array:
pd.value_counts(df.values.flatten())
If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:
You can also click the 'n commits' link below their name on the repo's "contributors" page:
Alternatively, you can directly append ?author=<theusername>
or ?author=<emailaddress>
to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:
For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress>
to the URL - the author's name will not be clickable from the commits list.
You can also get the list of commits by a particular author from the command line using
git log --author=[your git name]
Example:
git log --author=Prem
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
Thing
is an inner class with an automatic connection to an instance of Hello
. You get a compile error because there is no instance of Hello
for it to attach to. You can fix it most easily by changing it to a static nested class which has no connection:
static class Thing
Get rid of the escape characters before storing or manipulating the raw string:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
>>> mypath = os.getcwd().replace('\\','/')
>>> os.path.exists(mypath)
True
>>>
Way more elegant solution than $parent.$index
is using ng-init
:
<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>
What about constructing the element using jQuery? e.g.
$("<div></div>")
creates a new div element, ready to be added to the page. Can be shortened further to
$("<div>")
then you can chain on commands that you need, set up event handlers and append it to the DOM. For example
$('<div id="myid">Div Content</div>')
.bind('click', function(e) { /* event handler here */ })
.appendTo('#myOtherDiv');
To be relative to the root directory, just start the URI with a /
<link type="text/css" rel="stylesheet" href="/style.css" />
<script src="/script.js" type="text/javascript"></script>
I experienced this error with my WordPress site but I saw that there were two indexes showing in my developer tools sources.
Chrome Developer Tool Error So I had the thought that if there are two indexes starting at the first line of code then there's a replication and they're conflicting with each other. So I thought that then perhaps it's my HTML minification from my caching plugin tool.
So I turned off the HTML minify setting and deleted my cache. And poof! It worked!
I can't leave this question in this state with that final code in the question hanging over me...
dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:
There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.
The with
statement (recommended in another answer) removes the bother of closing the file through the context handler.
Use a dictionary instead of two lists.
A generator comprehension ((x for y in z)
) is used to do the translation in one line.
Wrap as little code as you can in a try
/except
block to reduce the probability of catching an exception you didn't mean to.
Use the input()
argument rather than print()
ing first - Use '\n'
to get the new line you want.
Don't write code across multiple lines or with intermediate variables like this just for the sake of it:
a = a.b()
a = a.c()
b = a.x()
c = b.y()
Instead, write these constructs like this, chaining the calls as is perfectly valid:
a = a.b().c()
c = a.x().y()
code = {}
with open('morseCode.txt', 'r') as morse_code_file:
# line format is <letter>:<morse code translation>
for line in morse_code_file:
line = line.rstrip() # Remove NL
code[line[0]] = line[2:]
user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
try:
print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
except KeyError:
print("Error in input. Only alphanumeric characters, a comma, and period allowed")
user_input = input("Try again or press <enter> to quit\n")
To remove nil values do:
['a', nil, 'b'].compact ## o/p => ["a", "b"]
To remove empty strings:
['a', 'b', ''].select{ |a| !a.empty? } ## o/p => ["a", "b"]
To remove both nil and empty strings:
['a', nil, 'b', ''].select{ |a| a.present? } ## o/p => ["a", "b"]
Just match /^index\.php/
then reject whatever matches it.
Typically, you would use a hash table and function object, both available in Boost, TR1 and C++0x.
void func1() {
}
std::unordered_map<std::string, std::function<void()>> hash_map;
hash_map["Value1"] = &func1;
// .... etc
hash_map[mystring]();
This is a little more overhead at runtime but a bajillion times more maintainable. Hash tables offer O(1) insertion, lookup, and etc, which makes them the same complexity as the assembly-style jump-table.
U can use something like this....
function (field,value) {
var newItemOrder= value;
// Make sure user hasnt already added this item
angular.forEach(arr, function(item) {
if (newItemOrder == item.value) {
arr.splice(arr.pop(item));
} });
submitFields.push({"field":field,"value":value});
};
I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.
<form id="form">
...
<button type="submit"></button>
</form>
<script>
$(document).ready(function() {
$("#form_selector").submit(function() {
$.ajax({
type: "POST",
url: "form_handler.php",
data: $(this).serialize(),
success: function() {
// callback code here
}
})
})
})
</script>
Thanks to @Pax Diablo, @bvmou and @Arachnid for the suggestion of using full datetimes throughout. If I have to accept datetime.time objects from an external source, then this seems to be an alternative add_secs_to_time()
function:
def add_secs_to_time(timeval, secs_to_add):
dummy_date = datetime.date(1, 1, 1)
full_datetime = datetime.datetime.combine(dummy_date, timeval)
added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)
return added_datetime.time()
This verbose code can be compressed to this one-liner:
(datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()
but I think I'd want to wrap that up in a function for code clarity anyway.
Wikipedia explains both reasonably well: UTF-8 vs Latin-1 (ISO-8859-1). Former is a variable-length encoding, latter single-byte fixed length encoding. Latin-1 encodes just the first 256 code points of the Unicode character set, whereas UTF-8 can be used to encode all code points. At physical encoding level, only codepoints 0 - 127 get encoded identically; code points 128 - 255 differ by becoming 2-byte sequence with UTF-8 whereas they are single bytes with Latin-1.
You could always just up or downcase the strings first.
string title = "string":
title.ToUpper().Contains("STRING") // returns true
Oops, just saw that last bit. A case insensitive compare would *
probably*
do the same anyway, and if performance is not an issue, I don't see a problem with creating uppercase copies and comparing those. I could have sworn that I once saw a case-insensitive compare once...
create host file = manifest.json
html tag head
<link rel="manifest" href="/manifest.json">
file
manifest.json
{
"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"news",
"business"
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"related_applications": [
{
"platform": "play",
"url": "https://play.google.com/store/apps/details?id=ir.divar"
}
],
"prefer_related_applications": true
}
While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.
So for everyone in need here is a full working example:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)
myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
POD is the official way to do multi line comments in Perl,
From faq.perl.org[perlfaq7]
The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with
=cut
, ending the Pod section:
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.
The
=begin
directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments withcomment
. End the comment using=end
with the same label. You still need the=cut
to go back to Perl code from the Pod comment:
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
Kindly try this code when str is less than 5.
string strModified = str.Substring(0,str.Length>5?5:str.Length);
Here is the best Maven-Environment Setup tutorial for Windows, Unix and Mac Operating systems.
But in the last you have to set value of PATH
variable as ";%M2_HOME%\bin"
instead of "%M2%"
, because PATH
variable is not able to reduce the value using "%M2%"
Can we re-visit the basic reason we wanted our class to behave as a Thread
?
There is no reason at all, we just wanted to execute a task, most likely in an asynchronous mode, which precisely means that the execution of the task must branch from our main thread and the main thread if finishes early, may or may not wait for the branched path(task).
If this is the whole purpose, then where do I see the need of a specialized Thread. This can be accomplished by picking up a RAW Thread from the System's Thread Pool and assigning it our task (may be an instance of our class) and that is it.
So let us obey the OOPs concept and write a class of the type we need. There are many ways to do things, doing it in the right way matters.
We need a task, so write a task definition which can be run on a Thread. So use Runnable.
Always remember implements
is specially used to impart a behaviour and extends
is used to impart a feature/property.
We do not want the thread's property, instead we want our class to behave as a task which can be run.
I'd print out the result of an2.getNodeName()
as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.
Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.
Perhaps iterate the children of your tag node and see what types are there?
Tried this code and it works for me:
String xml = "<add job=\"351\">\n" +
" <tag>foobar</tag>\n" +
" <tag>foobar2</tag>\n" +
"</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;
for (int i=0; i < nl.getLength(); i++) {
an = nl.item(i);
if(an.getNodeType()==Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for(int i2=0; i2<nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
Output was:
#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2
here is a function that fix your problem
public static void fixID(Connection conn, String table) {
try {
Statement myStmt = conn.createStatement();
ResultSet myRs;
int i = 1, id = 1, n = 0;
boolean b;
String sql;
myRs = myStmt.executeQuery("select max(id) from " + table);
if (myRs.next()) {
n = myRs.getInt(1);
}
while (i <= n) {
b = false;
myRs = null;
while (!b) {
myRs = myStmt.executeQuery("select id from " + table + " where id=" + id);
if (!myRs.next()) {
id++;
} else {
b = true;
}
}
sql = "UPDATE " + table + " set id =" + i + " WHERE id=" + id;
myStmt.execute(sql);
i++;
id++;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}
size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.
An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).
To summarize : use size_t to represent the size of an object and int (or long) in other cases.
The link provided in the accepted answer shows a nice way to implement the pub/sub system using jQuery, but I found the code somewhat difficult to read, so here is my simplified version of the code:
$(document).on('testEvent', function(e, eventInfo) {
subscribers = $('.subscribers-testEvent');
subscribers.trigger('testEventHandler', [eventInfo]);
});
$('#myButton').on('click', function() {
$(document).trigger('testEvent', [1011]);
});
$('#notifier1').on('testEventHandler', function(e, eventInfo) {
alert('(notifier1)The value of eventInfo is: ' + eventInfo);
});
$('#notifier2').on('testEventHandler', function(e, eventInfo) {
alert('(notifier2)The value of eventInfo is: ' + eventInfo);
});
If you do not want to change the display format permanently, and perhaps apply a new format later on, I personally favour the use of a resource manager (the with
statement in Python). In your case you could do something like this:
with pd.option_context('display.float_format', '${:0.2f}'.format):
print(df)
If you happen to need a different format further down in your code, you can change it by varying just the format in the snippet above.
It is called an interface. Many OO languages have this feature. You might want to read through the php explanation here: http://de2.php.net/interface
OK, the big difference is start from where they are coming from, so constructor
is the constructor of your class in JavaScript, on the other side, getInitialState
is part of the lifecycle
of React
.
constructor
is where your class get initialised...
Constructor
The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.
A constructor can use the super keyword to call the constructor of a parent class.
In the React v16 document, they didn't mentioned any preference, but you need to getInitialState
if you using createReactClass()
...
Setting the Initial State
In ES6 classes, you can define the initial state by assigning this.state in the constructor:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}
With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:
var Counter = createReactClass({
getInitialState: function() {
return {count: this.props.initialCount};
},
// ...
});
Visit here for more information.
Also created the image below to show few lifecycles of React Compoenents:
I met a similar problem.But the error report is about
[SSL: TLSV1_ALERT_ACCESS_DENIED] tlsv1 alert access denied (_ssl.c:777)
First I tried this https://python-forum.io/Thread-All-pip-install-attempts-are-met-with-SSL-error#pid_28035 ,but seems it couldn't solve my problems,and still repeat the same issue.
And Second if you are working on a business computer,generally it may exist a web content filter(but I can access https://pypi.python.org through browser directly).And solve this issue by adding a proxy server.
For windows,open the Internet properties
through IE or Chrome or whatsoever ,then set valid proxy address and port,and this way solve my problems
Or just adding the option pip --proxy [proxy-address]:port install mitmproxy
.But you always need to add this option while installing by pypi
The above two solution is alternative for you demand.
I have written down the steps:
? Add gem 'newrelic_rpm' to your Gemfile under staging & production
? bundle install
? Login to heroku control panel and add newrelic addon
? Once added, setup automatic pinging to your website so that it does not idle
? Browse to Menu > Availability Monitoring (under Settings)
? Click “Turn on Availability Monitoring”
? Enter the url to ping (eg: http://spokenvote.org)
? Select 1 minute for the interval
Its depends on your locale system time settings, make 24 hours then it will show you 24 hours time.
I know I'm late to the party but I find the zerofill is helpful for boolean representations of TINYINT(1). Null doesn't always mean False, sometimes you don't want it to. By zerofilling a tinyint, you're effectively converting those values to INT and removing any confusion ur application may have upon interaction. Your application can then treat those values in a manner similar to the primitive datatype True = Not(0)
Yes.
Add DisableCacheViewer Registry Key
Create a new dword key under HKLM\Software\Microsoft\Fusion\ with the name DisableCacheViewer and set it’s [DWORD] value to 1.
Go back to Windows Explorer to the assembly folder and it will be the normal file system view.
Since Java 1.5, you can get a more precise time value with System.nanoTime()
, which obviously returns nanoseconds instead.
There is probably some caching going on in the instances when you get an immediate result.
The easiest way to write console output to text file is
//create a file first
PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
outputfile.print("your output");
outputfile.close();
You can also use viewport-percentage lengths to achieve this:
5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
Where 100vh
represents the height of the viewport, and likewise 100vw
represents the width.
body {_x000D_
margin: 0; /* Reset default margin */_x000D_
}_x000D_
iframe {_x000D_
display: block; /* iframes are inline by default */_x000D_
background: #000;_x000D_
border: none; /* Reset default border */_x000D_
height: 100vh; /* Viewport-relative units */_x000D_
width: 100vw;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
This is supported in most modern browsers - support can be found here.
In case you're interested in a solution using Java 7 and NIO.2, it could go like this:
private static class DirectoriesFilter implements Filter<Path> {
@Override
public boolean accept(Path entry) throws IOException {
return Files.isDirectory(entry);
}
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(FileSystems.getDefault().getPath(root), new DirectoriesFilter())) {
for (Path p : ds) {
System.out.println(p.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}
There's a note on top of the docs:
Note: The Google Web Search API has been officially deprecated as of November 1, 2010. It will continue to work as per our deprecation policy, but the number of requests you may make per day will be limited. Therefore, we encourage you to move to the new Custom Search API.
The deprecation policy says that they will continue to run the API for 3 years. So if you already have an application that uses the old API, you don't have to rush to change things just yet. If you're writing a new application, use the Custom Search API. See my answer here for how to do this in Python, but the idea's the same for any language.
You can also include these attributes in the modal definition itself:
<div class="modal hide fade" data-keyboard="false" data-backdrop="static">
I've got a YouTube video on this.
Short answer: Use mock
when you're passing in the thing that you want mocked, and patch
if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.
Silly example:
# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
sentence.replace('cks','x') # We're cool and hip.
twitter_api.send(sentence)
# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
twitter_api = Twitter(user="XXX", password="YYY")
sentence.replace('cks','x')
twitter_api.send(sentence)
java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-01882: timezone region not found
For this type of error, just change your system time to your country's standard GMT format
e.g. Indian time zone is chennai,kolkata.
Have not yet seen this answer, so here's how you can do this with vi
or vim
:
vi -c '%s/\(http:\/\/.\{-}\/\).*/\1/ge | wq' file &>/dev/null
This runs the vi
:%s
substitution globally (the trailing g
), refrains from raising an error if the pattern is not found (e
), then saves the resulting changes to disk and quits. The &>/dev/null
prevents the GUI from briefly flashing on screen, which can be annoying.
I like using vi
sometimes for super complicated regexes, because (1) perl is dead dying, (2) vim has a very advanced regex engine, and (3) I'm already intimately familiar with vi
regexes in my day-to-day usage editing documents.
Go to menu File → Preferences → User Settings.
It will open up Default Settings and settings.json
automatically. Just add the following in the settings.json
file and save it. This will overwrite the default settings.
// Place your settings in this file to overwrite the default settings
{ "editor.wrappingColumn": 0 }
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
You are right, the function you're looking for is array_multisort()
.
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
As of PHP 5.5.0 you can use array_column()
instead of that foreach:
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5
if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
if viewController.isKind(of: LoginViewController.self) {
}
}
}
To get this working with YAML, do this:
property-name: '{
key1: "value1",
key2: "value2"
}'
Apple recommends for stylistic purposes.If you write this code:
@property (nonatomic,assign) BOOL working;
Then you can not use [object isWorking].
It will show an error. But if you use below code means
@property (assign,getter=isWorking) BOOL working;
So you can use [object isWorking] .
I use SourceTree git client, and I see that their initial commit/push command is:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master
I have tried over a half-dozen solutions suggested on Stack Overflow, and the only thing that worked for me was this:
<div class="row" style="display: flex; flex-wrap: wrap">
<div class="col-md-6">
Column A
</div>
<div class="col-md-6">
Column B
</div>
</div>
I got the solution from https://codepen.io/ondrejsvestka/pen/gWPpPo
Note that it seems to affect the column margins. I had to apply adjustments to those.
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
Click OK in each window and you're done.
Read about using docstrings in your Python code.
As per the Python docstring conventions:
The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
There will be no golden rule, but rather provide comments that mean something to the other developers on your team (if you have one) or even to yourself when you come back to it six months down the road.
For IntelliJ 13.1, go to File -> Settings -> Project Settings -> Compiler -> Java Compiler, and on the right-hand side, for Additional command line parameters
enter "-Xlint:unchecked"
.
Here is how I made monthly page in similar manner as Fernando:
I made five weeks on every page and on fifth week I made function
=IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
that empties fifth week if this month has only four weeks. C12 holds the number of weeks.
Insert following function on the first day field starting sheet #2:
=INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.
During the dark ages of SQL in the 1990s it was a good practice as the SQL designers were trying to add each word in the dictionary as keyword for endless avalanche of new features and they called it the SQL3 draft.
So it keeps forward compatibility.
And i found that it has another nice side effect, it helps a lot when you use grep in code reviews and refactoring.
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
You can also get the value of an item in the jObject like this:
JToken value;
if (json.TryGetValue(key, out value))
{
DoSomething(value);
}
Both are used to send some data and receive some response using that data.
GET: Get information stored in the server. (i.e. search, tweet, person information). If you want to send information then get request send request using process.php?name=subroto
So it basically sends information through url. Url cannot handle more than 2036 char. So for blog post can you remember it is not possible?
POST: Post do same thing as GET. User registration, User login, Big data send, Blog Post. If you need to send secure information then use post or for big data as it not go through url.
AJAX: $.get()
and $.post()
contain features that are subsets of $.ajax()
. It has more configuration.
$.get ()
method, which is a kind of shorthand for $.ajax()
. When using $.get ()
, instead of passing in an object, you pass in arguments. At minimum, you’ll need the first two arguments, which are the URL of the file you want to retrieve (eg. test.txt) and a success callback.
var format = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
// ^ ^
document.write(format.test("My @string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("My StringContainingNoSpecialChars"));
_x000D_
//create and fill polygon
CanvasRenderingContext2D.prototype.fillPolygon = function (pointsArray, fillColor, strokeColor) {
if (pointsArray.length <= 0) return;
this.moveTo(pointsArray[0][0], pointsArray[0][1]);
for (var i = 0; i < pointsArray.length; i++) {
this.lineTo(pointsArray[i][0], pointsArray[i][1]);
}
if (strokeColor != null && strokeColor != undefined)
this.strokeStyle = strokeColor;
if (fillColor != null && fillColor != undefined) {
this.fillStyle = fillColor;
this.fill();
}
}
//And you can use this method as
var polygonPoints = [[10,100],[20,75],[50,100],[100,100],[10,100]];
context.fillPolygon(polygonPoints, '#F00','#000');
You also can give a name to your script:
<script>
... (your code here)
//# sourceURL=somename.js
</script>
ofcourse replace "somename" by some name ;) and then you will see it in the chrome debugger at "Sources > top > (no domain) > somename.js" as a normal script and you will be able to debug it like other scripts
You can do:
timeStamp.toLocalDateTime().toLocalDate();
Note that
timestamp.toLocalDateTime()
will use theClock.systemDefaultZone()
time zone to make the conversion. This may or may not be what you want.
If one want to keep getting updated processes (on the example, 2 seconds) on a shell session without having to manually interact with it use:
watch -n 2 'mysql -h 127.0.0.1 -P 3306 -u some_user -psome_pass some_database -e "show full processlist;"'
The only bad thing about the show [full] processlist
is that you can't filter the output result. On the other hand, issuing the SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST
open possibilities to remove from the output anything you don't want to see:
SELECT * from INFORMATION_SCHEMA.PROCESSLIST
WHERE DB = 'somedatabase'
AND COMMAND <> 'Sleep'
AND HOST NOT LIKE '10.164.25.133%' \G
The combination of Sids and Koreys answers worked for me.
Extending the Navigation Controller:
extension UINavigationController {
public override func shouldAutorotate() -> Bool {
return visibleViewController.shouldAutorotate()
}
}
Then disabling rotation on the single View
class ViewController: UIViewController {
override func shouldAutorotate() -> Bool {
return false
}
}
And rotating to the appropriate orientation before the segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "SomeSegue")
{
let value = UIInterfaceOrientation.Portrait.rawValue;
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
}
$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used
The most famous library to create some GUI in C language is certainly GTK.
With this library you can easily create some buttons (for your example). When a user clicks on the button, a signal is emitted and you can write a handler to do some actions.
Add to your panel's style code something like this:
<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>
I use
\pagenumbering{roman}
for everything in the frontmatter and then switch over to
\pagenumbering{arabic}
for the actual content. With pdftex, the page numbers come out right in the PDF file.
As far as I know, this is impossible to achieve for an unknown width.
You could - if that works in your scenario - absolutely position an invisible element with 100% width and height, and have the element centered in there using margin: auto and possibly vertical-align. Otherwise, you'll need JavaScript to do that.
I just had to implement a RESTfull api where I need to pass parameters. I did this by passing the parameters in the query string in the same style as described by Mark's first example "api/controller?start=date1&end=date2"
In the controller I used a tip from URL split in C#?
// uri: /api/courses
public IEnumerable<Course> Get()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var system = nvc["System"];
// BL comes here
return _courses;
}
In my case I was calling the WebApi via Ajax looking like:
$.ajax({
url: '/api/DbMetaData',
type: 'GET',
data: { system : 'My System',
searchString: '123' },
dataType: 'json',
success: function (data) {
$.each(data, function (index, v) {
alert(index + ': ' + v.name);
});
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
I hope this helps...
Sadly git is so unrelable :( I just lost 2 days of work :(
It's best to manual backup anything before doing commit. I just did "git commit" and git just destroy all my changes without saying anything.
I learned my lesson - next time backup first and only then commit. Never trust git for anything.
Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.
Other than sharing same unicode number for given character, each one is their own format.
UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...
UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.
Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.
Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.
Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )
So, people use UTF-8 where ever possible.
This doesn't use TEMP Tables, but real tables instead. If the problem is just about temp tables and not about table creation or dropping tables, this will work:
SELECT DISTINCT * INTO TableA_Verify FROM TableA;
DROP TABLE TableA;
RENAME TABLE TableA_Verify TO TableA;
best solution:
echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
No need to include your http://domain.com in your if you're submitting a form to the same domain.
Could you use an insert trigger? If it fails, do an update.
You could also disable the cascade delete convention in global scope of your application by doing this:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()
For Kotlin fans:
private fun Bitmap.addOverlay(@DimenRes marginTop: Int, @DimenRes marginLeft: Int, overlay: Bitmap): Bitmap? {
val bitmapWidth = this.width
val bitmapHeight = this.height
val marginLeft = shareBitmapWidth - overlay.width - resources.getDimension(marginLeft)
val finalBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, this
.config)
val canvas = Canvas(finalBitmap)
canvas.drawBitmap(this, Matrix(), null)
canvas.drawBitmap(overlay, marginLeft, resources.getDimension(marginTop), null)
return finalBitmap
}
bitmap.addOverlay( R.dimen.top_margin, R.dimen.left_margin, overlayBitmap)
Taken from this link:
Build means compile and link only the source files that have changed since the last build, while Rebuild means compile and link all source files regardless of whether they changed or not. Build is the normal thing to do and is faster. Sometimes the versions of project target components can get out of sync and rebuild is necessary to make the build successful. In practice, you never need to Clean.
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
In android resources it's rather simple
<string name="smth">%1$02d</string>
I can't understand why this issue gets pounded into the ground when in 30 seconds you can code a two-column table and solve the problem.
This div column height problem comes up all over a typical layout. Why resort to scripting when a plain old basic HTML tag will do it? Unless there are huge and numerous tables on a layout, I don't buy the argument that tables are significantly slower.
try this
{
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
Map<String, String> headers = new HashMap<String, String>();
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
Thanks for Ben's solution, my use case to display only particular fields in order
with object
Code:
handlebars.registerHelper('eachToDisplayProperty', function(context, toDisplays, options) {
var ret = "";
var toDisplayKeyList = toDisplays.split(",");
for(var i = 0; i < toDisplayKeyList.length; i++) {
toDisplayKey = toDisplayKeyList[i];
if(context[toDisplayKey]) {
ret = ret + options.fn({
property : toDisplayKey,
value : context[toDisplayKey]
});
}
}
return ret;
});
Source object:
{ locationDesc:"abc", name:"ghi", description:"def", four:"you wont see this"}
Template:
{{#eachToDisplayProperty this "locationDesc,description,name"}}
<div>
{{property}} --- {{value}}
</div>
{{/eachToDisplayProperty}}
Output:
locationDesc --- abc
description --- def
name --- ghi
You can use this:
String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));
In the bash shell, try cat -v <filename>
. This should display carriage-returns for windows files.
(This worked for me in rxvt via Cygwin on Windows XP).
Editor's note: cat -v
visualizes \r
(CR) chars. as ^M
. Thus, line-ending \r\n
sequences will display as ^M
at the end of each output line. cat -e
will additionally visualize \n
, namely as $
. (cat -et
will additionally visualize tab chars. as ^I
.)
IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:
the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])
Edit: Note that join wants an iterable (e.g. a list) as its single argument.
This exact example is present on mozilla developers page:
As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);
, and store it in data-descr="ADD"
attribute of your HTML tag (which is nice because you can e.g translate it)
CSS content
can only be usef with :after
and :before
pseudo-elements, so you can try to proceed with something like this:
.item a p.new-label span:after{
position: relative;
content: 'NEW'
}
.item:hover a p.new-label span:after {
content: 'ADD';
}
The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.
If you don't wan't to use ng-model there is ng-value
you can try.
Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/
also you can use "AND" instead of "OR" if you want both attributes to be applied.
select * from tickets where (assigned_to='1') and (status='open') order by created_at desc;
^[+-]?\d{1,18}(\.\d{1,2})?$
accepts positive or negative decimal values.
I know this is an old post but try using an extension method:
public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
{
return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
}
and use it like this
var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));
Feel free to choose your own dates, you don't have to restrict yourself to January 2000.
You should be able to break to a label, like so:
function foo ()
{
dance:
for(var k = 0; k < 4; k++){
for(var m = 0; m < 4; m++){
if(m == 2){
break dance;
}
}
}
}
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
The accepted answer didn't work for me for two reasons:
BackColor
set so setting AutoSize = false
and Dock = Fill
causes the background color to fill the whole formAutoSize
set to false anyway because my label text was dynamicInstead, I simply used the form's width and the width of the label to calculate the left offset:
MyLabel.Left = (this.Width - MyLabel.Width) / 2;
Keep scroll position by using @DawnYu answer to wrap notifyDataSetChanged()
like this:
val recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState()
adapter.notifyDataSetChanged()
recyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)
faster to read than non cluster as data is physically storted in index order we can create only one per table.(cluster index)
quicker for insert and update operation than a cluster index. we can create n number of non cluster index.
As I found the best way is doing is preloading a stylesheet that contains the font face, and then let browser to load it automatically. I used the font-face in other locations (in the html page), but then I could observe the font changing effect briefly.
<link href="fonts.css?family=Open+Sans" rel="preload stylesheet" as="style">
then in the font.css file, specify as following.
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'),
url('open-sans-v16-latin-regular.woff2') format('woff2'); /* Super Modern Browsers */
}
You can't assign a name to fonts when it's preloaded through link tag (correct me if I was wrong I couldn't find a way yet), and thus you have to use font-face to assign the name to the font. Even though it's possible to load a font through link tag, it's not recommended as you can't assign a name to the font with it. Without a name as with font-face, you won't be able to use it anywhere in the web page. According to gtmetrix, style sheet loads at the beginning, then rest of the scripts/style by order, then the font before dom is loaded, and therefore you don't see font changing effect.
More differences: "printf" returns an integer value (equal to the number of characters printed) and "cout" does not return anything
And.
cout << "y = " << 7;
is not atomic.
printf("%s = %d", "y", 7);
is atomic.
cout performs typechecking, printf doesn't.
There's no iostream equivalent of "% d"
For another approach, note that all the standard library functions work with floating point types. You can implement an integer type function like this:
unsigned power(unsigned base, unsigned degree)
{
unsigned result = 1;
unsigned term = base;
while (degree)
{
if (degree & 1)
result *= term;
term *= term;
degree = degree >> 1;
}
return result;
}
This effectively does repeated multiples, but cuts down on that a bit by using the bit representation. For low integer powers this is quite effective.
This is for anyone that is trying to get a list of all files in a folder and its sub-folders and save it in a text document.
Below is the full code including the “using” statements, “namespace”, “class”, “methods” etc.
I tried commenting as much as possible throughout the code so you could understand what each part is doing.
This will create a text document that contains a list of all files in all folders and sub-folders of any given root folder. After all, what good is a list (like in Console.WriteLine) if you can’t do something with it.
Here I have created a folder on the C drive called “Folder1” and created a folder inside that one called “Folder2”. Next I filled folder2 with a bunch of files, folders and files and folders within those folders.
This example code will get all the files and create a list in a text document and place that text document in Folder1.
Caution: you shouldn’t save the text document to Folder2 (the folder you are reading from), that would be just bad practice. Always save it to another folder.
I hope this helps someone down the line.
using System;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
public static void Main(string[] args)
{
// Create a header for your text file
string[] HeaderA = { "****** List of Files ******" };
System.IO.File.WriteAllLines(@"c:\Folder1\ListOfFiles.txt", HeaderA);
// Get all files from a folder and all its sub-folders. Here we are getting all files in the folder
// named "Folder2" that is in "Folder1" on the C: drive. Notice the use of the 'forward and back slash'.
string[] arrayA = Directory.GetFiles(@"c:\Folder1/Folder2", "*.*", SearchOption.AllDirectories);
{
//Now that we have a list of files, write them to a text file.
WriteAllLines(@"c:\Folder1\ListOfFiles.txt", arrayA);
}
// Now, append the header and list to the text file.
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"c:\Folder1\ListOfFiles.txt"))
{
// First - call the header
foreach (string line in HeaderA)
{
file.WriteLine(line);
}
file.WriteLine(); // This line just puts a blank space between the header and list of files.
// Now, call teh list of files.
foreach (string name in arrayA)
{
file.WriteLine(name);
}
}
}
// These are just the "throw new exception" calls that are needed when converting the array's to strings.
// This one is for the Header.
private static void WriteAllLines(string v, string file)
{
//throw new NotImplementedException();
}
// And this one is for the list of files.
private static void WriteAllLines(string v, string[] arrayA)
{
//throw new NotImplementedException();
}
}
}
Here is the correct implementation using numpy (np.log()
is the natural logarithm)
import numpy as np
p = 100
r = 0.06 / 12
FV = 4000
n = np.log(1 + FV * r/ p) / np.log(1 + r)
print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
You can use LENGTH() for CHAR / VARCHAR2 and DBMS_LOB.GETLENGTH() for CLOB. Both functions will count actual characters (not bytes).
See the linked documentation if you do need bytes.
Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable
using not empty operator on my dataModel
that extends javax.faces.model.ListDataModel
Code sample:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class EntityDataModel extends ListDataModel<Entity> implements
Collection<Entity>, SelectableDataModel<Entity>, Serializable {
public EntityDataModel(List<Entity> data) { super(data); }
@Override
public Entity getRowData(String rowKey) {
// In a real app, a more efficient way like a query by rowKey should be
// implemented to deal with huge data
List<Entity> entitys = (List<Entity>) getWrappedData();
for (Entity entity : entitys) {
if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
}
return null;
}
@Override
public Object getRowKey(Entity entity) {
return entity.getId();
}
@Override
public boolean isEmpty() {
List<Entity> entity = (List<Entity>) getWrappedData();
return (entity == null) || entity.isEmpty();
}
// ... other not implemented methods of Collection...
}