You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.
There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.
Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.
Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:
import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';
@Injectable()
export class MyResolver implements Resolve<MyData> {
constructor(private ms: MyService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
let id = route.params['id'];
return this.ms.getId(id).then(data => {
if (data) {
return data;
} else {
this.router.navigate(['/login']);
return;
}
});
}
}
and in the module:
import { MyResolver } from './my-resolver.service';
@NgModule({
imports: [
RouterModule.forChild(myRoutes)
],
exports: [
RouterModule
],
providers: [
MyResolver
]
})
export class MyModule { }
and you can access it in your Component like this:
/////
ngOnInit() {
this.route.data
.subscribe((data: { mydata: myData }) => {
this.id = data.mydata.id;
});
}
/////
And in the Route something like this (usually in the app.routing.ts file):
////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////
std::max_element
takes two iterators delimiting a sequence and returns an iterator pointing to the maximal element in that sequence. You can additionally pass a predicate to the function that defines the ordering of elements.
Using a clip-path is a new, up and coming alternative. Its starting to get supported more and more and is now becoming well documented. Since it uses SVG to create the shape, it is responsive straight out of the box.
div {_x000D_
width: 200px;_x000D_
min-height: 200px;_x000D_
-webkit-clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 25%, 75% 0);_x000D_
clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 25%, 75% 0);_x000D_
background: lightblue;_x000D_
}
_x000D_
<div>_x000D_
<p>Some Text</p>_x000D_
</div>
_x000D_
I have an alternative to web-tiki's transform answer.
body {_x000D_
background: lightgreen;_x000D_
}_x000D_
div {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: transparent;_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}_x000D_
div.bg {_x000D_
width: 200%;_x000D_
height: 200%;_x000D_
background: lightblue;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: -75%;_x000D_
transform-origin: 50% 50%;_x000D_
transform: rotate(45deg);_x000D_
z-index: -1;_x000D_
}
_x000D_
<div>_x000D_
<div class="bg"></div>_x000D_
<p>Some Text</p>_x000D_
</div>
_x000D_
The environment variable solution doesn't work for me running tensorflow 2.3.1. I assume by the comments in the github thread that the below solution works for versions >=2.1.0.
From tensorflow github:
import tensorflow as tf
# Hide GPU from visible devices
tf.config.set_visible_devices([], 'GPU')
Make sure to do this right after the import with fresh tensorflow instance (if you're running jupyter notebook, restart the kernel).
And to check that you're indeed running on the CPU:
# To find out which devices your operations and tensors are assigned to
tf.debugging.set_log_device_placement(True)
# Create some tensors and perform an operation
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
Expected output:
2.3.1
Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
There is also a plot.background
option in addition to panel.background
:
df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y))
p <- p + opts(
panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank(),
plot.background = theme_rect(fill = "transparent",colour = NA)
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
print(p)
dev.off()
For some reason, the uploaded image is displaying differently than on my computer, so I've omitted it. But for me, I get a plot with an entirely gray background except for the box part of the boxplot which is still white. That can be changed using the fill aesthetic in the boxplot geom as well, I believe.
Edit
ggplot2 has since been updated and the opts()
function has been deprecated. Currently, you would use theme()
instead of opts()
and element_rect()
instead of theme_rect()
, etc.
Call any of these
byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input)
From
If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library
Luckily, we now have a couple of convenience methods in the nio packages. For instance:
byte[] java.nio.file.Files.readAllBytes(Path path)
I’m tired of looking for free translators and the best option for me was Selenium (more precisely selenide and webdrivermanager) and https://translate.google.com
import io.github.bonigarcia.wdm.ChromeDriverManager;
import com.codeborne.selenide.Configuration;
import io.github.bonigarcia.wdm.DriverManagerType;
import static com.codeborne.selenide.Selenide.*;
public class Main {
public static void main(String[] args) throws IOException, ParseException {
ChromeDriverManager.getInstance(DriverManagerType.CHROME).version("76.0.3809.126").setup();
Configuration.startMaximized = true;
open("https://translate.google.com/?hl=ru#view=home&op=translate&sl=en&tl=ru");
String[] strings = /some strings to translate
for (String data: strings) {
$x("//textarea[@id='source']").clear();
$x("//textarea[@id='source']").sendKeys(data);
String translation = $x("//span[@class='tlid-translation translation']").getText();
}
}
}
hi there are 2 solutions :
change the port 80 to 81 in the text file (httpd.conf) and click 127.0.0.1:81
change setting the network go to control panel--network and internet--network and sharing center
click-->local area connection select-->propertis check true in the -allow other ..... and --- allo other .....
Hitting ctrl + c once(wait for traceback), then hitting ctrl+c again did the trick for me :)
If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via javascript post). This usually means that your form definition will look like this (I'm going off of memory, make sure you check the html elements are correct):
<form method="POST" action="page.aspx">
<input id="customerName" name="customerName" type="Text" />
<input id="customerPhone" name="customerPhone" type="Text" />
<input value="Save" type="Submit" />
</form>
You should be able to access the customerName and customerPhone data like this:
string n = String.Format("{0}", Request.Form["customerName"]);
If you have method="GET"
in the form (not recommended, it messes up your URL space), you will have to access the form data like this:
string n = String.Format("{0}", Request.QueryString["customerName"]);
This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback'. (i.e. somebody clicked the 'Save' button, or this was done programatically via javascript.)
Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e. runat="server"
), with server controls the id and name are different.
Use table style Border-collapse at the table level
Both VS Code extensions can be used:
Personally, I'm suggesting: Numbered Bookmarks, with 'navigate through all files' option:
NOTE
Either way, be careful with shortcuts (Ctrl+1, Ctrl+Shift+1,..) that are already assigned.
Personally, mine were in 2 conflicts, with:
Try this:
var keys = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
keys.push(key);
}
}
hasOwnProperty
is needed because it's possible to insert keys into the prototype object of dictionary
. But you typically don't want those keys included in your list.
For example, if you do this:
Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};
and then do a for...in
loop over dictionary
, you'll get a
and b
, but you'll also get c
.
Filter
array of objects, which property matches value, returns array:
var result = jsObjects.filter(obj => {
return obj.b === 6
})
See the MDN Docs on Array.prototype.filter()
const jsObjects = [_x000D_
{a: 1, b: 2}, _x000D_
{a: 3, b: 4}, _x000D_
{a: 5, b: 6}, _x000D_
{a: 7, b: 8}_x000D_
]_x000D_
_x000D_
let result = jsObjects.filter(obj => {_x000D_
return obj.b === 6_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
Find
the value of the first element/object in the array, otherwise undefined
is returned.
var result = jsObjects.find(obj => {
return obj.b === 6
})
See the MDN Docs on Array.prototype.find()
const jsObjects = [_x000D_
{a: 1, b: 2}, _x000D_
{a: 3, b: 4}, _x000D_
{a: 5, b: 6}, _x000D_
{a: 7, b: 8}_x000D_
]_x000D_
_x000D_
let result = jsObjects.find(obj => {_x000D_
return obj.b === 6_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
If you press C-x C-e
command that will open your default editor which defined .bashrc
, after that you can use all powerful features of your editor. When you save and exit, the lines will wait your enter.
If you want to define your editor, just write for Ex. EDITOR=emacs -nw
or EDITOR=vi
inside of ~/.bashrc
Here is a sample code
strFileName = "c:\test.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)
objExcel.Quit
Might sound stupid, But Params doesn't allow multidimensional array. Whereas you can pass a multidimensional array to a function.
Swift: You can do this by checking which textField is being presented.
@objc func keyboardWillShow(notification: NSNotification) {
if self.textField.isFirstResponder == true {
self.view.frame.origin.y -= 150
}
}
@objc func keyboardWillHide(notification: NSNotification){
if self.textField.isFirstResponder == true {
self.view.frame.origin.y += 150
}
}
You may want to use the onLoad
event, as in the following example:
<iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe>
The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)
If the iframe is showing a page within the same domain of the parent, you would be able to access the location with contentWindow.location
, as in the following example:
<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>
MacOS: composer is available on brew now (Tested on Php7+):
brew install composer
Install instructions on the Composer Docs page are quite to the point otherwise.
You can use this awesome plugin
https://github.com/ianrogren/jquery-backDetect
All you need to do is to write this code
$(window).load(function(){
$('body').backDetect(function(){
// Callback function
alert("Look forward to the future, not the past!");
});
});
Best
Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.
Old answer: Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.
if isinstance(target, str) or isinstance(target, unicode):
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
Adding to @ud_an
It is not a good practice to create different folders for layouts. Create your layout such that it works fine with all the screen sizes. To achieve this, play with the layout attributes. You only need to have different images for hdpi, mdpi and ldpi types. The rest will be managed by android OS.
There is an old plugin called HEX Editor here.
According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.
In general this error message means that you have tried to use indexing on a function. You can reproduce this error message with, for example
mean[1]
## Error in mean[1] : object of type 'closure' is not subsettable
mean[[1]]
## Error in mean[[1]] : object of type 'closure' is not subsettable
mean$a
## Error in mean$a : object of type 'closure' is not subsettable
The closure mentioned in the error message is (loosely) the function and the environment that stores the variables when the function is called.
In this specific case, as Joshua mentioned, you are trying to access the url
function as a variable. If you define a variable named url
, then the error goes away.
As a matter of good practise, you should usually avoid naming variables after base-R functions. (Calling variables data
is a common source of this error.)
There are several related errors for trying to subset operators or keywords.
`+`[1]
## Error in `+`[1] : object of type 'builtin' is not subsettable
`if`[1]
## Error in `if`[1] : object of type 'special' is not subsettable
If you're running into this problem in shiny
, the most likely cause is that you're trying to work with a reactive
expression without calling it as a function using parentheses.
library(shiny)
reactive_df <- reactive({
data.frame(col1 = c(1,2,3),
col2 = c(4,5,6))
})
While we often work with reactive expressions in shiny as if they were data frames, they are actually functions that return data frames (or other objects).
isolate({
print(reactive_df())
print(reactive_df()$col1)
})
col1 col2
1 1 4
2 2 5
3 3 6
[1] 1 2 3
But if we try to subset it without parentheses, then we're actually trying to index a function, and we get an error:
isolate(
reactive_df$col1
)
Error in reactive_df$col1 : object of type 'closure' is not subsettable
I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0
I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps
Both styles, with a touch of tweaking, would work.
The first method uses a Javascript Constructor, which like most things has pros and cons.
// By convention, constructors start with an upper case letter
function MakePerson(name,age) {
// The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
this.name = name;
this.age = age;
this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);
On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.
function makePerson(name2, age2) {
var name = name2;
var age = age2;
return {
name: name,
age: age
};
}
To have a centered title in ABS (if you want to have this in the default ActionBar
, just remove the "support" in the method names), you could just do this:
In your Activity, in your onCreate()
method:
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
abs_layout
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/tvTitle"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#FFFFFF" />
</LinearLayout>
Now you should have an Actionbar
with just a title. If you want to set a custom background, set it in the Layout above (but then don't forget to set android:layout_height="match_parent"
).
or with:
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage));
Another idea is to use a setting in the Shared Preferences. Same general idea as checking for an empty file, but then you don't have an empty file floating around, not being used to store anything
line = line.Replace("\\", "");
The best option is to use INSERT...SELECT statement in mysql.
There are a bunch of reasons here: http://macresearch.org/difference-between-alloc-init-and-new
Some selected ones are:
new
doesn't support custom initializers (like initWithString
)alloc-init
is more explicit than new
General opinion seems to be that you should use whatever you're comfortable with.
std::atan2
allows calculating the arctangent of all four quadrants. std::atan
only allows calculating from quadrants 1 and 4.
For newbies, you can extend your partial service class in a separate cs file and add the code the code provided by "imanabidi" to get it integrated
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
I'm the maintainer of Mongoose. findById()
is a built-in method on Mongoose models. findById(id)
is equivalent to findOne({ _id: id })
, with one caveat: findById()
with 0 params is equivalent to findOne({ _id: null })
.
You can read more about findById()
on the Mongoose docs and this findById()
tutorial.
I write a helper class for sharedpreferences:
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by mete_ on 23.12.2016.
*/
public class HelperSharedPref {
Context mContext;
public HelperSharedPref(Context mContext) {
this.mContext = mContext;
}
/**
*
* @param key Constant RC
* @param value Only String, Integer, Long, Float, Boolean types
*/
public void saveToSharedPref(String key, Object value) throws Exception {
SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else {
throw new Exception("Unacceptable object type");
}
editor.commit();
}
/**
* Return String
* @param key
* @return null default is null
*/
public String loadStringFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
String restoredText = prefs.getString(key, null);
return restoredText;
}
/**
* Return int
* @param key
* @return null default is -1
*/
public Integer loadIntegerFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Integer restoredText = prefs.getInt(key, -1);
return restoredText;
}
/**
* Return float
* @param key
* @return null default is -1
*/
public Float loadFloatFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Float restoredText = prefs.getFloat(key, -1);
return restoredText;
}
/**
* Return long
* @param key
* @return null default is -1
*/
public Long loadLongFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Long restoredText = prefs.getLong(key, -1);
return restoredText;
}
/**
* Return boolean
* @param key
* @return null default is false
*/
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Boolean restoredText = prefs.getBoolean(key, false);
return restoredText;
}
}
I'd use absolute positioning:
#play_button {
position:absolute;
transition: .5s ease;
left: 202px;
top: 198px;
}
Maybe specifying a width would work. When you position:absolute
an element, it's width will shrink to the contents I believe.
http://www.quirksmode.org/js/cookies.html
update would just be resetting it using createCookie
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
On my machine (Win10), the uninstaller was located at C:\ProgramData\Anaconda3\Uninstall-Anaconda3.exe
.
another way
$('input:radio[name=theme]').filter(":checked").val()
Execute the following procedure for example as user system.
Set p_owner to the schema owner and p_readonly to the name of the readonly user.
create or replace
procedure createReadOnlyUser(p_owner in varchar2, p_readonly in varchar2)
AUTHID CURRENT_USER is
BEGIN
execute immediate 'create user '||p_readonly||' identified by '||p_readonly;
execute immediate 'grant create session to '||p_readonly;
execute immediate 'grant select any dictionary to '||p_readonly;
execute immediate 'grant create synonym to '||p_readonly;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
execute immediate 'grant select on '||p_owner||'.'||R.object_name||' to '||p_readonly;
END LOOP;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
execute immediate 'grant execute on '||p_owner||'.'||R.object_name||' to '||p_readonly;
END LOOP;
FOR R IN (SELECT owner, object_name FROM all_objects WHERE object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
EXECUTE IMMEDIATE 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
END LOOP;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
execute immediate 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
END LOOP;
END;
Simply put this block of xml in your activity layout file:
<RelativeLayout
android:id="@+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
And when you finish loading, call this one line:
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
The result (and it spins too):
Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/
Html:
<div id="content">
<iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>
Relevant parts of CSS:
div#content {
position: fixed;
top: 80px;
left: 40px;
bottom: 25px;
min-width: 200px;
width: 40%;
background: black;
}
div#content iframe {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
}
I tried all of the answers above but no luck. In my case, there is a generated build/classes folder with some additional ".class" files. I ended up going to the package explorer, right-clicking on the project and selecting the "Refresh" option and that made the build/classes folder available again resolving the issue.
I like Alfonso Tienda responce from HTTP status code for update and delete?
Here are some Tips:
DELETE
200 (if you want send some additional data in the Response) or 204 (recommended).
202 Operation deleted has not been committed yet.
If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)
Other errors:
- 400 Bad Request (Malformed syntax or a bad query is strange but possible).
- 401 Unauthorized Authentication failure
- 403 Forbidden: Authorization failure or invalid Application ID.
- 405 Not Allowed. Sure.
- 409 Resource Conflict can be possible in complex systems.
- And 501, 502 in case of errors.
PUT
If you're updating an element of a collection
- 200/204 with the same reasons as DELETE above.
- 202 if the operation has not been commited yet.
The referenced element doesn't exists:
PUT can be 201 (if you created the element because that is your behaviour)
404 If you don't want to create elements via PUT.
400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).
401 Unauthorized
403 Forbidden: Authentication failure or invalid Application ID.
405 Not Allowed. Sure.
409 Resource Conflict can be possible in complex systems, as in DELETE.
422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values
And 501, 502 in case of errors.
Here's a modified version if you use CloudFlare caching layer Services
function getIP()
{
$fields = array('HTTP_X_FORWARDED_FOR',
'REMOTE_ADDR',
'HTTP_CF_CONNECTING_IP',
'HTTP_X_CLUSTER_CLIENT_IP');
foreach($fields as $f)
{
$tries = $_SERVER[$f];
if (empty($tries))
continue;
$tries = explode(',',$tries);
foreach($tries as $try)
{
$r = filter_var($try,
FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 |
FILTER_FLAG_NO_PRIV_RANGE |
FILTER_FLAG_NO_RES_RANGE);
if ($r !== false)
{
return $try;
}
}
}
return false;
}
get
is a function that is called when you try to read the value player.health
, like in:
console.log(player.health);
It's effectively not much different than:
player.getHealth = function(){
return 10 + this.level*15;
}
console.log(player.getHealth());
The opposite of get is set, which would be used when you assign to the value. Since there is no setter, it seems that assigning to the player's health is not intended:
player.health = 5; // Doesn't do anything, since there is no set function defined
A very simple example:
var player = {_x000D_
level: 5_x000D_
};_x000D_
_x000D_
Object.defineProperty(player, "health", {_x000D_
get: function() {_x000D_
return 10 + (player.level * 15);_x000D_
}_x000D_
});_x000D_
_x000D_
console.log(player.health); // 85_x000D_
player.level++;_x000D_
console.log(player.health); // 100_x000D_
_x000D_
player.health = 5; // Does nothing_x000D_
console.log(player.health); // 100
_x000D_
The mostly used StringUtils class is the Apache Commons Lang StringUtils (org.apache.commons.lang3.StringUtils). To use this class you first have to download the Apache Commons Lang3 package then you have to add it to your project libraries.
You can go to this link to get more details: http://examples.javacodegeeks.com/core-java/apache/commons/lang3/stringutils/org-apache-commons-lang3-stringutils-example/
you can easily access elements by index , by use System.Linq
Here is the sample
First add using in your class file
using System.Linq;
Then
yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value
Hope this helps.
This can be done using list comprehensions as defined in PEP 202
[w.strip() for w in ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]
In order to remove "Whitespace" which causes plenty of indentation errors when running your finished code or programs in Pyhton. Just do the following;obviously if Python keeps telling that the error(s) is indentation in line 1,2,3,4,5, etc..., just fix that line back and forth.
However, if you still get problems about the program that are related to typing mistakes, operators, etc, make sure you read why error Python is yelling at you:
The first thing to check is that you have your indentation right. If you do, then check to see if you have mixed tabs with spaces in your code.
Remember: the code will look fine (to you), but the interpreter refuses to run it. If you suspect this, a quick fix is to bring your code into an IDLE edit window, then choose Edit..."Select All from the menu system, before choosing Format..."Untabify Region. If you’ve mixed tabs with spaces, this will convert all your tabs to spaces in one go (and fix any indentation issues).
Here is another solution to generate a timestamp in JavaScript - including a padding method for single numbers - using day, month, year, hour, minute and seconds in its result (working example at jsfiddle):
var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();
timestamp.day = [
pad(timestamp.getDate()),
pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
timestamp.getFullYear()
];
timestamp.time = [
pad(timestamp.getHours()),
pad(timestamp.getMinutes()),
pad(timestamp.getSeconds())
];
timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);
This actually doesn't work:
char c = reader.next().charAt(0);
There are some good explanations and references in this question: Why doesn't the Scanner class have a nextChar method? "A Scanner breaks its input into tokens using a delimiter pattern", which is pretty open ended. For example when using this
c = lineScanner.next().charAt(0);
for this line of input "(1 + 9) / (3 - 1) + 6 - 2" the call to next returns "(1", c will be set to '(', and you'll end up losing the '1' on the next call to next()
Typically when you want to get a character you would like to ignore whitespace. This worked for me:
c = lineScanner.findInLine("[^\\s]").charAt(0);
Reference: regex to match a single character that is anything but a space
The easiest way I have tested just add a <br>
as in the following:
<div class="col-sm-6">
<br><h3><p class="text-center">Some Text</p></h3>
</div>
The only problem is that a extra line break (generated by that <br>
) is generated when the screen gets smaller and it stacks. But it is quick and simple.
To add yet another potential solution, Helium by Clockworkmod has it's own version of ADB built in that kept being started. Exiting the Helium Desktop application resolves the issue.
Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.
var exportFileName = "export-" + filename;
$('<a></a>', {
"download": exportFileName,
"href": "data:," + JSON.stringify(exportData, null,5),
"id": "exportDataID"
}).appendTo("body")[0].click().remove();
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
c.execute('insert into tablename values (?,?,?)', item)
You can use the Reflection API
Use this query:
UPDATE `table` SET date_date=now();
Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE `table` SET date_date=now()");
mysql_close($con);
?>
You can animate it after the fadeIn completes using the callback as shown below:
$("#Friends").fadeIn('slow',function(){
$(this).animate({'top': '-=30px'},'slow');
});
you can try the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("PayScale", typeof(string));
dt.Columns.Add("IncrementAmt", typeof(string));
dt.Columns.Add("Period", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = TextBox1.Text;
NewRow[1] = TextBox2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
here payscale,incrementamt and period are database field name.
In Selenium IDE you can do:
Command | clickAndWait Target | //input[@value='Next' and @title='next']
It should work fine.
Above shown methods did not work for me, may be i am using bit old jquery, then finally the below shown code snippet works for - posting just in case somebody in my same position
$('#textBox').live('keydown', function(e) {
if (e.keyCode == 9) {
e.preventDefault();
alert('tab');
}
});
IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.
For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:
Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.
Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.
Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.
You can also put DOM elements, like div
on top of the canvas that would represent your canvas elements and be positioned the same way.
Now you can attach event listeners to these divs and run the necessary actions.
You can use re.escape():
re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.
If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_
).
Extending (Kevin Tong) answer.
Step 1: Download & Unzip nssm-2.24.zip
Step 2: From command line type:
C:\> nssm.exe install [servicename]
it will open GUI as below (the example is UT2003 server), then simply browse it to: yourapplication.exe
More information on: https://nssm.cc/usage
I had same requirement.
I have used the below way to get it.
I had session scoped bean.
@ManagedBean(name="mb")
@SessionScopedpublic
class ManagedBean {
--------
}
I have used the below code in my servlet doPost() method.
ManagedBean mb = (ManagedBean) request.getSession().getAttribute("mb");
it solved my problem.
If you are using graphLab, you can use this function. It is really powerfull
products['word_count'] = graphlab.text_analytics.count_words(your_text)
I had a similar but it was dealing with dates. Query to show all items for the last month, works great without conditions until Jan. In order for it work correctly, needed to add a year and month variable
declare @yr int
declare @mth int
set @yr=(select case when month(getdate())=1 then YEAR(getdate())-1 else YEAR(getdate())end)
set @mth=(select case when month(getdate())=1 then month(getdate())+11 else month(getdate())end)
Now I just add the variable into condition: ...
(year(CreationTime)=@yr and MONTH(creationtime)=@mth)
Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE
declaration as a public static final field: Java will instantiate the object the first time the class is referred to.
The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.
For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.
If you have some form data for example sent to home#action, now you want to redirect them to house#act while keeping the parameters, you can do this
redirect_to act_house_path(request.parameters)
On Mac OSX, sleep does not take minutes/etc, only seconds. So for two minutes,
sleep 120
The PIL distribution is mispackaged for egg installation.
Install Pillow instead, the friendly PIL fork.
It sounds like you currently have 3 copies of the entire file in memory: the byte array, the string, and the array of the lines.
Instead of reading the bytes into a byte array and then converting to characters using new String()
it would be better to use an InputStreamReader, which will convert to characters incrementally, rather than all up-front.
Also, instead of using String.split("\n") to get the individual lines, you should read one line at a time. You can use the readLine()
method in BufferedReader
.
Try something like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
try {
while (true) {
String line = reader.readLine();
if (line == null) break;
String[] fields = line.split(",");
// process fields here
}
} finally {
reader.close();
}
The ready event is always execute at the only html page is loaded to the browser and the functions are executed.... But the load event is executed at the time of all the page contents are loaded to the browser for the page..... we can use $ or jQuery when we use the noconflict() method in jquery scripts...
The solution of Rohan will fix the problem as the error message will not be shown but the emulator will not use the hardware acceleration and thus be again very slow.
I recommend instead to install the Intel Hardware Accelerated Execution Manager as described here:
Try this and it will work like a charm. I was having the same error but this approach did the trick for me:
ssh USER@REMOTE "cat file"|xclip -i
That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:
public ActionResult SomeAction()
{
...
return RedirectToAction("SomeAction", "SomeController");
}
Now since I see that in your example you are attempting to redirect to the LogOn
action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize]
attribute:
[Authorize]
public ActionResult SomeProtectedAction()
{
...
}
Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl
).
A static variable inside a function has a lifespan as long as your program runs. It won't be allocated every time your function is called and deallocated when your function returns.
margin: 50%;
You can adjust the percentage as needed. It seems to work for me in responsive emails.
It's good to separate content from layout
But this is a fallacious argument; Cliche Thinking
It's a fallacious argument because HTML tables are layout! The content is the data in the table, the presentation is the table itself. This is why separating CSS from HTML can be very difficult at times. You're not separating content from presentation, you're separating presentation from presentation! A pile of nested divs is no different than a table - it's just a different set of tags.
The other problem with separating the HTML from the CSS is that they need intimate knowledge of one another - you really can't separate them fully. The tag layout in the HTML is tightly coupled with the CSS file no matter what you do.
I think tables vs divs comes down to the needs of your application.
In the application we develop at work, we needed a page layout where the pieces would dynamically size themselves to their content. I spent days trying to get this to work cross-browser with CSS and DIVs and it was a complete nightmare. We switched to tables and it all just worked.
However, we have a very closed audience for our product (we sell a piece of hardware with a web interface) and accessibility issues are not a concern for us. I don't know why screen readers can't deal with tables well, but I guess if that's the way it is then developers have to handle it.
i prefer using React built-in API:
import React, {cloneElement, Component} from "react";
import PropTypes from "prop-types";
export class Test extends Component {
render() {
const {children, wrapper} = this.props;
return (
cloneElement(wrapper, {
...wrapper.props,
children
})
);
}
}
Test.propTypes = {
wrapper: PropTypes.element,
// ... other props
};
Test.defaultProps = {
wrapper: <div/>,
// ... other props
};
then you can replace the wrapper div with what ever you want:
<Test wrapper={<span className="LOL"/>}>
<div>child1</div>
<div>child2</div>
</Test>
The encodings are spelled out in the buffer documentation.
Character Encodings
utf8
: Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.utf16le
: Multi-byte encoded Unicode characters. Unlikeutf8
, each character in the string will be encoded using either 2 or 4 bytes.latin1
: Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters fromU+0000
toU+00FF
.Binary-to-Text Encodings
base64
: Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5.hex
: Encode each byte as two hexadecimal characters.Legacy Character Encodings
ascii
: For 7-bit ASCII data only. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text.binary
: Alias for 'latin1'.ucs2
: Alias of 'utf16le'.
None of the answers worked for me (I am using Ubuntu 16.04 and Python 3.6). So I finally solved the issue as following:
1- connect to the FTP of the server
2- go to the folder "/usr/lib/python3/dist-packages/"
3- duplicate the file "apt_pkg.cpython-35m-x86_64-linux-gnu.so"
4- rename this duplicated file to "apt_pkg.cpython-36m-x86_64-linux-gnu.so"
That's it!
After reading about LVM and being familiar with PV -> VG -> LV, this works for me :
0) #df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 1.9G 0 1.9G 0% /dev
tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs 1.9G 824K 1.9G 1% /run
tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/mapper/fedora-root 15G 2.1G 13G 14% /
tmpfs 1.9G 0 1.9G 0% /tmp
/dev/md126p1 976M 119M 790M 14% /boot
tmpfs 388M 0 388M 0% /run/user/0
1) # vgs
VG #PV #LV #SN Attr VSize VFree
fedora 1 2 0 wz--n- 231.88g 212.96g
2) # vgdisplay
--- Volume group ---
VG Name fedora
System ID
Format lvm2
Metadata Areas 1
Metadata Sequence No 3
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 2
Max PV 0
Cur PV 1
Act PV 1
VG Size 231.88 GiB
PE Size 4.00 MiB
Total PE 59361
Alloc PE / Size 4844 / 18.92 GiB
Free PE / Size 54517 / 212.96 GiB
VG UUID 9htamV-DveQ-Jiht-Yfth-OZp7-XUDC-tWh5Lv
3) # lvextend -l +100%FREE /dev/mapper/fedora-root
Size of logical volume fedora/root changed from 15.00 GiB (3840 extents) to 227.96 GiB (58357 extents).
Logical volume fedora/root successfully resized.
4) #lvdisplay
5) #fd -h
6) # xfs_growfs /dev/mapper/fedora-root
meta-data=/dev/mapper/fedora-root isize=512 agcount=4, agsize=983040 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=1 spinodes=0 rmapbt=0
= reflink=0
data = bsize=4096 blocks=3932160, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=1
log =internal bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 3932160 to 59757568
7) #df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 1.9G 0 1.9G 0% /dev
tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs 1.9G 828K 1.9G 1% /run
tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/mapper/fedora-root 228G 2.3G 226G 2% /
tmpfs 1.9G 0 1.9G 0% /tmp
/dev/md126p1 976M 119M 790M 14% /boot
tmpfs 388M 0 388M 0% /run/user/0
Best Regards,
either ceil and floor should give the same out out put
Math.ceil(x.y) == Math.floor(x.y)
or simply check for equality with double value
x.y == Math.ceil(x.y)
x.y == Math.floor(x.y)
or
Math.round(x.y) == x.y
You can use the strdup
function which has the following prototype
char *strdup(const char *s1);
Example of use:
#include <string.h>
char * my_str = strdup("My string literal!");
char * my_other_str = strdup(some_const_str);
or strcpy/strncpy to your buffer
or rewrite your functions to use const char *
as parameter instead of char *
where possible so you can preserve the const
I was struggling with this question because I was looking for a way to do this in a bash script for OS X, hence /etc/passwd was out of the question, and my script was meant to be executed as root, therefore making the solutions invoking eval or bash -c dangerous as they allowed code injection into the variable specifying the username.
Here is what I found. It's simple and doesn't put a variable inside a subshell. However it does require the script to be ran by root as it sudos into the specified user account.
Presuming that $SOMEUSER contains a valid username:
echo "$(sudo -H -u "$SOMEUSER" -s -- "cd ~ && pwd")"
I hope this helps somebody!
The LEA instruction can be used to avoid time consuming calculations of effective addresses by the CPU. If an address is used repeatedly it is more effective to store it in a register instead of calculating the effective address every time it is used.
I am not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it:
$letters = { 'A', 'B', 'C' }
$letters | % {$counter = 0}{...;$counter++}
Or use a for
loop instead...
for ($counter=0; $counter -lt $letters.Length; $counter++){...}
There´s no problem in making your primary key from various fields, that's a Natural Key.
You can use a Identity column (associated with a unique index on the candidate fields) to make a Surrogate Key.
That´s an old discussion. I prefer surrogate keys in most situations.
But there´s no excuse for the lack of a key.
RE: EDIT
Yeah, there´s a lot of controversy about that :D
I don´t see any obvious advantage on natural keys, besides the fact that they are the natural choice. You will always think in Name, SocialNumber - or something like that - instead of idPerson.
Surrogate keys are the answer to some of the problems that natural keys have (propagating changes for example).
As you get used to surrogates, it seems more clean, and manageable.
But in the end, you´ll find out that it's just a matter of taste - or mindset -. People "think better" with natural keys, and others don´t.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
});
$("input:checked")
$("input:unchecked")
Try this:
module Util
module MyUtil
def self.redondear_up(suma,cantidad, decimales=0)
unless suma.present?
return nil
end
if suma>0
resultado= (suma.to_f/cantidad)
return resultado.round(decimales)
end
return nil
end
end
end
Try this, this should also get rid of those empty lines also:
SELECT prereq FROM test WHERE prereq IS NOT NULL;
Seems like you're extracting audio from a video file & downmixing to stereo channel.
To just extract audio (without re-encoding):
ffmpeg.exe -i in.mp4 -vn -c:a copy out.m4a
To extract audio & downmix to stereo (without re-encoding):
ffmpeg.exe -i in.mp4 -vn -c:a copy -ac 2 out.m4a
To generate an mp3 file, you'd re-encode audio:
ffmpeg.exe -i in.mp4 -vn -ac 2 out.mp3
This is a variation of the anwser by Muhammad Rehan Saeed, with the class getting parasitically attached to the existing .net core MVC class of the same name, so that everything just works.
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static partial class UrlHelperExtensions
{
/// <summary>
/// Generates a fully qualified URL to an action method by using the specified action name, controller name and
/// route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(
this IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}
/// <summary>
/// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
/// virtual (relative) path to an application absolute path.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="contentPath">The content path.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteContent(
this IUrlHelper url,
string contentPath)
{
HttpRequest request = url.ActionContext.HttpContext.Request;
return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
}
/// <summary>
/// Generates a fully qualified URL to the specified route by using the route name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteRouteUrl(
this IUrlHelper url,
string routeName,
object routeValues = null)
{
return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}
}
}
If you don't have access to getDefaultSharedPreferenes()
, you can use getSharedPreferences(name, mode)
instead, you just have to pass in the right name.
Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity
onCreate()
, and seeing what preferencesName
is.
String preferencesName = this.getPreferenceManager().getSharedPreferencesName();
The string should be something like com.example.projectname_preferences
. Hard code that somewhere in your project, and pass it in to getSharedPreferences()
and you should be good to go.
You can also use this code to get LayoutInflater:
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
You can easily use the MODE argument:
MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions
If the mode argument is omitted, the value of the default_week_format system variable is used:
MySQL :: MySQL 5.1 Reference Manual :: 5.1.4 Server System Variables
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"First",@"Second", nil];
NSMutableArray *copiedArray = [array mutableCopy];
NSMutableArray *retainedArray = [array retain];
[retainedArray addObject:@"Retained Third"];
[copiedArray addObject:@"Copied Third"];
NSLog(@"array = %@",array);
NSLog(@"Retained Array = %@",retainedArray);
NSLog(@"Copied Array = %@",copiedArray);
array = (
First,
Second,
"Retained Third"
)
Retained Array = (
First,
Second,
"Retained Third"
)
Copied Array = (
First,
Second,
"Copied Third"
)
Based on the work of Denis Nek, it works well if the sum of item's widths is smaller than the size of the container. other than that, it will make the recyclerview non scrollable and only will show subset of the data.
to solve this problem, i modified the solution alittle so that it choose the min of the provided size and calculated size. see below:
package com.linkdev.gafi.adapters;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.linkdev.gafi.R;
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.c = context;
}
private Context c;
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
int widthDesired = Math.min(widthSize,width);
setMeasuredDimension(widthDesired, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}}
If you are not giving any modifier to your method then as default it will be Default modifier which has scope within package.
for more info you can refer http://wiki.answers.com/Q/What_is_default_access_specifier_in_Java
bundle exec
is a Bundler command to execute a script in the context of the current bundle (the one from your directory's Gemfile). rake db:migrate
is the script where db is the namespace and migrate is the task name defined.
So bundle exec rake db:migrate
executes the rake script with the command db:migrate
in the context of the current bundle.
As to the "why?" I'll quote from the bundler page:
In some cases, running executables without
bundle exec
may work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle.However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine.
We can use AbstractMap Class having SimpleEntry which allows the creation of immutable map
Map<String, String> map5 = Stream.of(
new AbstractMap.SimpleEntry<>("Sakshi","java"),
new AbstractMap.SimpleEntry<>("fine","python")
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(map5.get("Sakshi"));
map5.put("Shiva", "Javascript");
System.out.println(map5.get("Shiva"));// here we can add multiple entries.
Error jet 4 oledb It Can be possible upgrade kb4041678 kb4041681
Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.
document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};
This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.
dplyr::as_data_frame(df, rownames = "your_row_name")
will give you even simpler result.
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link: http://zurb.com/ink/
Hope it helps someone.
Ninja edit: It has since been renamed to Foundation for Emails
and the new link is: https://foundation.zurb.com/emails.html
Silent but deadly edit: New link https://get.foundation/emails.html
from time import clock
from random import sample
n = 500
myList = sample(xrange(10000),n)
#print myList
A,B,C,D = [],[],[],[]
for i in xrange(100):
t0 = clock()
ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
A.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
B.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
C.append(clock()-t0)
t0 = clock()
ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
D.append(clock()-t0)
print '\n'.join(('t1 = '+str(min(A))+' '+'{:.1%}.'.format(min(A)/min(D)),
't2 = '+str(min(B))+' '+'{:.1%}.'.format(min(B)/min(D)),
't3 = '+str(min(C))+' '+'{:.1%}.'.format(min(C)/min(D)),
't4 = '+str(min(D))+' '+'{:.1%}.'.format(min(D)/min(D))))
For n=500:
150.8%.
142.7%.
110.8%.
100.0%.
For n=5000:
153.5%.
176.2%.
109.7%.
100.0%.
Oh, I see now: only the solution 3 with map() fits with the title of the question.
You can try deleting package-lock.json
and running npm install
afterwards.
This worked for me.
I think it is jar file version problem. I had the same issue and I fixed it by changing the commons-codec-1.6.jar file from the build path. Earlier I was using latest version 1.10. Gradually I decreased the versions and 1.6 version fixed my issue.
Here is my solution to this issue:
SQL> Startup mount
ORA-01081: cannot start already-running ORACLE - shut it down first
SQL> shutdown abort
ORACLE instance shut down.
SQL>
SQL> startup mount
ORACLE instance started.
Total System Global Area 1904054272 bytes
Fixed Size 2404024 bytes
Variable Size 570425672 bytes
Database Buffers 1325400064 bytes
Redo Buffers 5824512 bytes
Database mounted.
SQL> Show parameter control_files
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
control_files string C:\APP\USER\ORADATA\ORACLEDB\C
ONTROL01.CTL, C:\APP\USER\FAST
_RECOVERY_AREA\ORACLEDB\CONTRO
L02.CTL
SQL> select a.member,a.group#,b.status from v$logfile a ,v$log b where a.group#=
b.group# and b.status='CURRENT'
2
SQL> select a.member,a.group#,b.status from v$logfile a ,v$log b where a.group#=
b.group# and b.status='CURRENT';
MEMBER
--------------------------------------------------------------------------------
GROUP# STATUS
---------- ----------------
C:\APP\USER\ORADATA\ORACLEDB\REDO03.LOG
3 CURRENT
SQL> shutdown abort
ORACLE instance shut down.
SQL> startup mount
ORACLE instance started.
Total System Global Area 1904054272 bytes
Fixed Size 2404024 bytes
Variable Size 570425672 bytes
Database Buffers 1325400064 bytes
Redo Buffers 5824512 bytes
Database mounted.
SQL> recover database using backup controlfile until cancel;
ORA-00279: change 4234808 generated at 01/21/2014 18:31:05 needed for thread 1
ORA-00289: suggestion :
C:\APP\USER\FAST_RECOVERY_AREA\ORACLEDB\ARCHIVELOG\2014_01_22\O1_MF_1_108_%U_.AR
C
ORA-00280: change 4234808 for thread 1 is in sequence #108
Specify log: {<RET>=suggested | filename | AUTO | CANCEL}
C:\APP\USER\ORADATA\ORACLEDB\REDO03.LOG
Log applied.
Media recovery complete.
SQL> alter database open resetlogs;
Database altered.
And it worked:
Try this:
((.|\n)*)<FooBar>
It basically says "any character or a newline" repeated zero or more times.
For smaller files you could use this:
& C:\windows\system32\more +1 oldfile.csv > newfile.csv | out-null
... but it's not very effective at processing my example file of 16MB. It doesn't seem to terminate and release the lock on newfile.csv.
Looks like you've got the syntax slightly wrong... I'm assuming based on your code that you're trying to scroll down 100px in 800ms, if so then this works (using scrollTo 1.4.1):
$.scrollTo('+=100px', 800, { axis:'y' });
I was able to use nginx to handle the 301 redirect to the aws signin page.
Go to your nginx conf folder (in my case it's /etc/nginx/sites-available
in which I create a symlink to /etc/nginx/sites-enabled
for the enabled conf files).
Then add a redirect path
server {
listen 80;
server_name aws.example.com;
return 301 https://myaccount.signin.aws.amazon.com/console;
}
If you are using nginx, you will most likely have additional server blocks (virtualhosts in apache terminology) to handle your zone apex (example.com) or however you have it setup. Make sure that you have one of them set to be your default server.
server {
listen 80 default_server;
server_name example.com;
# rest of config ...
}
In Route 53, add an A record
for aws.example.com
and set the value to the same IP used for your zone apex.
If the value
returned is null, use:
if(value.isEmpty());
Sometime to check null, if(value == null)
in java, it might not give true even the String is null.
Executive summary / TL;DR:
Try doing a find & replace of "=" with "=". Yes, replace the equals sign with itself. For my scenario, it forced everything to update.
Background:
I frequently make formulas across multiple columns then concatenate them together. After doing such, I'll copy & paste them as values to extract my created formula. After this process, they're typically stuck displaying a formula, and not displaying a value, unless I enter the cell and press Enter. Pressing F2 & Enter repeatedly is not fun.
There could be a few things happening here. Start by first figuring out your library location:
Sys.getenv("R_LIBS_USER")
or
.libPaths()
We already know yours from the info you gave: C:\Program Files\R\R-3.0.1\library
I believe you have a file in there called: 00LOCK
. From ?install.packages
:
Note that it is possible for the package installation to fail so badly that the lock directory is not removed: this inhibits any further installs to the library directory (or for --pkglock, of the package) until the lock directory is removed manually.
You need to delete that file. If you had the pacman
package installed you could have simply used p_unlock()
and the 00LOCK
file is removed. You can't install pacman
now until the 00LOCK
file is removed.
To install pacman
use:
install.packages("pacman")
There may be a second issue. This is where you somehow corrupted MASS
. This can occur, in my experience, if you try to update a package while it is in use in another R session. I'm sure there's other ways to cause this as well. To solve this problem try:
Sys.getenv("R_LIBS_USER")
. In your case this is: C:\Program Files\R\R-3.0.1\libraryMASS
packageMASS
via install.packages("MASS")
If any of this works please let me know what worked.
private List<Url> AddURLToFile(Urls urls, Url url)
{
string filePath = @"D:\test\file.json";
urls.UrlList.Add(url);
//if (!System.IO.File.Exists(filePath))
// using (System.IO.File.Delete(filePath));
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(urls.UrlList));
//using (StreamWriter sw = (System.IO.File.Exists(filePath)) ? System.IO.File.AppendText(filePath) : System.IO.File.CreateText(filePath))
//{
// sw.WriteLine(JsonConvert.SerializeObject(urls.UrlList));
//}
return urls.UrlList;
}
private List<Url> ReadURLToFile()
{
// string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"App_Data\file.json");
string filePath = @"D:\test\file.json";
List<Url> result = new List<Url>(); ;
if (!System.IO.File.Exists(filePath))
using (System.IO.File.CreateText(filePath)) ;
using (StreamReader file = new StreamReader(filePath))
{
result = JsonConvert.DeserializeObject<List<Url>>(file.ReadToEnd());
file.Close();
}
if (result == null)
result = new List<Url>();
return result;
}
neither fgets nor getchar works to solve the problem. the only workaround is keeping a space before %c while using scanf scanf(" %c",ch); // will only work
In the follwing fgets also not work..
char line[256];
char ch;
int i;
printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
If this helps, you can also use FileSystemObject to retrieve all subfolders of a folder. You need to check the reference "Microsot Scripting Runtime" to get Intellisense and use the "new" keyword.
Sub GetSubFolders()
Dim fso As New FileSystemObject
Dim f As Folder, sf As Folder
Set f = fso.GetFolder("D:\Proj\")
For Each sf In f.SubFolders
'Code inside
Next
End Sub
It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"
You already specified the culture, so try escaping the slashes.
The correct, fully Pythonic way to read a file is the following:
with open(...) as f:
for line in f:
# Do something with 'line'
The with
statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f
treats the file object f
as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.
There should be one -- and preferably only one -- obvious way to do it.
Ways to show Navigation Bar in Swift:
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.navigationBar.isHidden = false
self.navigationController?.isNavigationBarHidden = false
Quite late to this party, today I had the same problem.
The right answer on macOs I think is use jenv
brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11
And then add into Intellij IDEA as new SDK the following path:
~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/
The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.
For set the time life in php, you can use the function session_set_cookie_params, before the session_start:
session_set_cookie_params(3600,"/");
session_start();
For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.
But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.
You can have a Table "Sessions":
And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:
On login:
setcookie('sessid', $sessionid, 604800); // One week or seven days
setcookie('sesshash', $sessionhash, 604800); // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function
If the user return:
if (isset($_COOKIE['sessid'])) {
if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
$_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
} else {
// Dont validate the hash, possible session falsification
}
}
Obviously, save all session/cookies calls, before sending data.
mkdir -p ~/.ssh/
cat your_key > ~/.ssh/authorized_keys
cat your_key >> ~/.ssh/authorized_keys
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.
After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:
Dim xlApp as Excel.Application
Let's say you added an Excel Workbook Object in your Form and named it xLObject.
Here is how you Access a Sheet of this Object and change a Range
Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"
(I copied the above from my answer to this question)
Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)
In C, you don't need to cast the return value of malloc
. The pointer to void returned by malloc
is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:
int *sieve = malloc(sizeof *sieve * length);
which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve
.
Casts are bad, as people have pointed out. Especially pointer casts.
Query to add column with comment are :
alter table table_name
add( "NISFLAG" NUMBER(1,0) )
comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'
commit;
Try This :
document.getElementById(<element_ID>).readOnly=true;
A little convenience script expanding on previous answers.
#!/bin/bash
# Uninstall node.js
#
# Options:
#
# -d Actually delete files, otherwise the script just _prints_ a command to delete.
# -p Installation prefix. Default /usr/local
# -f BOM file. Default /var/db/receipts/org.nodejs.pkg.bom
CMD="echo sudo rm -fr"
BOM_FILE="/var/db/receipts/org.nodejs.pkg.bom"
PREFIX="/usr/local"
while getopts "dp:f:" arg; do
case $arg in
d)
CMD="sudo rm -fr"
;;
p)
PREFIX=$arg
;;
f)
BOM_FILE=$arg
;;
esac
done
lsbom -f -l -s -pf ${BOM_FILE} \
| while read i; do
$CMD ${PREFIX}/${i}
done
$CMD ${PREFIX}/lib/node \
${PREFIX}/lib/node_modules \
${BOM_FILE}
Save it to file and run with:
# bash filename.sh
In addition to Ian's answer, I had to allow the font extensions in the request filtering module to make it work.
<system.webServer>
<staticContent>
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/x-font-woff" />
</staticContent>
<security>
<requestFiltering>
<fileExtensions>
<add fileExtension=".woff" allowed="true" />
<add fileExtension=".ttf" allowed="true" />
<add fileExtension=".woff2" allowed="true" />
</fileExtensions>
</requestFiltering>
</security>
</system.webServer>
The order of execution of ng-click
and ng-model
is ambiguous since they do not define clear priorities. Instead you should use ng-change
or a $watch
on the $scope
to ensure that you obtain the correct values of the model variable.
In your case, this should work:
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
If you'd like to see side-by-side diffs in a browser without involving GitHub, you might enjoy git webdiff, a drop-in replacement for git diff
:
$ pip install webdiff
$ git webdiff
This offers a number of advantages over traditional GUI difftools like tkdiff
in that it can give you syntax highlighting and show image diffs.
Read more about it here.
Not an exact answer because you're using xml data and there is currently no pd.read_xml()
function (as of v0.23.4), but pandas (starting with v0.21.0) can uncompress the file for you! Thanks Wes!
import pandas as pd
import os
fn = '../data/file_to_load.json.gz'
print(os.path.isfile(fn))
df = pd.read_json(fn, lines=True, compression='gzip')
df.tail()
copssh - OpenSSH for Windows
http://www.itefix.no/i2/copssh
Packages essential Cygwin binaries.
PHPMailer has the ability to automatically embed images from your HTML email. You have to give full path in the file system, when writing your HTML:
<img src="/var/www/host/images/photo.png" alt="my photo" />
It will automaticaly convert to:
<img src="cid:photo.png" alt="my photo" />
In your request options, try including the following:
var req = https.request({
host: '192.168.1.1',
port: 443,
path: '/',
method: 'GET',
rejectUnauthorized: false,
requestCert: true,
agent: false
},
When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like
public interface Thunk { void apply(); }
somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.
In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
Swift 4 (adapted from Kristopher Johnson's answer)
textfield.clearButtonMode = .always
textfield.clearButtonMode = .whileEditing
textfield.clearButtonMode = .unlessEditing
textfield.clearButtonMode = .never
Did you see this? If I haven't misunderstand that answer, you may try to create a new virtualenv on top of the old one. You just need to know which python is going to use your virtualenv (you will need to see your virtualenv version).
If your virtualenv is installed with the same python version of the old one and upgrading your virtualenv package is not an option, you may want to read this in order to install a virtualenv with the python version you want.
EDIT
I've tested this approach (the one that create a new virtualenv on top of the old one) and it worked fine for me. I think you may have some problems if you change from python 2.6 to 2.7 or 2.7 to 3.x but if you just upgrade inside the same version (staying at 2.7 as you want) you shouldn't have any problem, as all the packages are held in the same folders for both python versions (2.7.x and 2.7.y packages are inside your_env/lib/python2.7/).
If you change your virtualenv python version, you will need to install all your packages again for that version (or just link the packages you need into the new version packages folder, i.e: your_env/lib/python_newversion/site-packages)
I do this all the time. Here's a look at an example and how you would implement it.
Change your XAML to use the Command property of the button instead of the Click event. I am using the name SaveCommand since it is easier to follow then something named Command.
<Button Command="{Binding Path=SaveCommand}" />
Your CustomClass that the Button is bound to now needs to have a property called SaveCommand of type ICommand
. It needs to point to the method on the CustomClass that you want to run when the command is executed.
public MyCustomClass
{
private ICommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(
param => this.SaveObject(),
param => this.CanSave()
);
}
return _saveCommand;
}
}
private bool CanSave()
{
// Verify command can be executed here
}
private void SaveObject()
{
// Save command execution logic
}
}
The above code uses a RelayCommand which accepts two parameters: the method to execute, and a true/false value of if the command can execute or not. The RelayCommand class is a separate .cs file with the code shown below. I got it from Josh Smith :)
/// <summary>
/// A command whose sole purpose is to
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
return _canExecute == null ? true : _canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
_execute(parameters);
}
#endregion // ICommand Members
}
Another simpler option is to do:
> x = c(1, 1, 2, 4, 5, 2, 1, 3, 2)
> x[x==1] <- 0
> x
[1] 0 0 2 4 5 2 0 3 2
You want to pass these extra parameters to subprocess.Popen
:
bufsize=1, universal_newlines=True
Then you can iterate as in your example. (Tested with Python 3.5)
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
// not using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
// jquery is prettier. :-)
You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
when using String array, you have to give size of array while initializing
eg
String[] str = new String[10];
you can use index 0-9 to store values
str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"
if you are using ArrayList instread of string array, you can use it without initializing size of array ArrayList str = new ArrayList();
you can add value by using add method of Arraylist
str.add("Value1");
get retrieve a value from arraylist, you can use get method
String s = str.get(0);
find total number of items by size method
int nCount = str.size();
read more from here
Here is better resolution
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public static InputStream bitmapToInputStream(Bitmap bitmap) {
int size = bitmap.getHeight() * bitmap.getRowBytes();
ByteBuffer buffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(buffer);
return new ByteArrayInputStream(buffer.array());
}
Code from How to read drawable bits as InputStream
i use firebase-database in html signup but last error i cannot understand if anybody know tell me . error is "Failed to load resource: the server responded with a status of 404 ()"
Just for reference, here is an example Singleton implementation of Jack Wu/hpique's Nested Struct implementation. The implementation also shows how archiving could work, as well as some accompanying functions. I couldn't find this complete of an example, so hopefully this helps somebody!
import Foundation
class ItemStore: NSObject {
class var sharedStore : ItemStore {
struct Singleton {
// lazily initiated, thread-safe from "let"
static let instance = ItemStore()
}
return Singleton.instance
}
var _privateItems = Item[]()
// The allItems property can't be changed by other objects
var allItems: Item[] {
return _privateItems
}
init() {
super.init()
let path = itemArchivePath
// Returns "nil" if there is no file at the path
let unarchivedItems : AnyObject! = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
// If there were archived items saved, set _privateItems for the shared store equal to that
if unarchivedItems {
_privateItems = unarchivedItems as Array<Item>
}
delayOnMainQueueFor(numberOfSeconds: 0.1, action: {
assert(self === ItemStore.sharedStore, "Only one instance of ItemStore allowed!")
})
}
func createItem() -> Item {
let item = Item.randomItem()
_privateItems.append(item)
return item
}
func removeItem(item: Item) {
for (index, element) in enumerate(_privateItems) {
if element === item {
_privateItems.removeAtIndex(index)
// Delete an items image from the image store when the item is
// getting deleted
ImageStore.sharedStore.deleteImageForKey(item.itemKey)
}
}
}
func moveItemAtIndex(fromIndex: Int, toIndex: Int) {
_privateItems.moveObjectAtIndex(fromIndex, toIndex: toIndex)
}
var itemArchivePath: String {
// Create a filepath for archiving
let documentDirectories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
// Get the one document directory from that list
let documentDirectory = documentDirectories[0] as String
// append with the items.archive file name, then return
return documentDirectory.stringByAppendingPathComponent("items.archive")
}
func saveChanges() -> Bool {
let path = itemArchivePath
// Return "true" on success
return NSKeyedArchiver.archiveRootObject(_privateItems, toFile: path)
}
}
And if you didn't recognize some of those functions, here is a little living Swift utility file I've been using:
import Foundation
import UIKit
typealias completionBlock = () -> ()
extension Array {
func contains(#object:AnyObject) -> Bool {
return self.bridgeToObjectiveC().containsObject(object)
}
func indexOf(#object:AnyObject) -> Int {
return self.bridgeToObjectiveC().indexOfObject(object)
}
mutating func moveObjectAtIndex(fromIndex: Int, toIndex: Int) {
if ((fromIndex == toIndex) || (fromIndex > self.count) ||
(toIndex > self.count)) {
return
}
// Get object being moved so it can be re-inserted
let object = self[fromIndex]
// Remove object from array
self.removeAtIndex(fromIndex)
// Insert object in array at new location
self.insert(object, atIndex: toIndex)
}
}
func delayOnMainQueueFor(numberOfSeconds delay:Double, action closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue()) {
closure()
}
}
The error your are getting is because your-ubuntu-username is not a valid Postgres user.
You need to tell psql what database username to use
psql -U postgres
You may also need to specify the database to connect to
psql -U postgres -d <dbname>
You don't even have to set a specific width for the cells, table-layout: fixed
suffices to spread the cells evenly.
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid hotpink;_x000D_
vertical-align: middle;_x000D_
word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz</li>_x000D_
</ul>
_x000D_
Note that for
table-layout
to work the table styled element must have a width set (100% in my example).
Using a char when the variable is a string won't work. Using
switch (hello.charAt(0))
you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside
case 'a '
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
For the benefit of others, I though I'd include what I did.
Since you cannot get Visual Studio (2010 in my case) to ignore the LNK4204 warnings, my approach was to give it what it wanted: the pdb files. As I was using open source libraries in my case, I have the code building the pdb files already.
BUT, the default is to name all of the PDF files the same thing: vc100.pdb in my case. As you need a .pdb for each and every .lib, this creates a problem, especially if you are using something like ImageMagik, which creates about 20 static .lib files. You cannot have 20 lib files in one directory (which your application's linker references to link in the libraries from) and have all the 20 .pdb files called the same thing.
My solution was to go and rebuild my static library files, and configure VS2010 to name the .pdb file with respect to the PROJECT. This way, each .lib gets a similarly named .pdb, and you can put all of the LIBs and PDBs in one directory for your project to use.
So for the "Debug" configuraton, I edited:
Properties->Configuration Properties -> C/C++ -> Output Files -> Program Database File Name from
$(IntDir)vc$(PlatformToolsetVersion).pdb
to be the following value:
$(OutDir)vc$(PlatformToolsetVersion)D$(ProjectName).pdb
Now rather than somewhere in the intermediate directory, the .pdb files are written to the output directory, where the .lib files are also being written, AND most importantly, they are named with a suffix of D+project name. This means each library project produduces a project .lib and a project specific .pdb.
I'm now able to copy all of my release .lib files, my debug .lib files and the debug .pdb files into one place on my development system, and the project that uses that 3rd party library in debug mode, has the pdb files it needs in debug mode.
From the Tools menu, click on Options, select Designers from the side menu and untick prevent changes that can lead to recreation of a table. Then save the changes
Your value:
this.element = $(id);
is a jQuery object, not a pure Canvas element.
To turn it back so you can call getContext()
, call this.element.get(0)
, or better yet store the real element and not the jQuery object:
function canvasLayer(location, id) {
this.width = $(window).width();
this.height = $(window).height();
this.element = document.createElement('canvas');
$(this.element)
.attr('id', id)
.text('unsupported browser')
.attr('width', this.width) // for pixels
.attr('height', this.height)
.width(this.width) // for CSS scaling
.height(this.height)
.appendTo(location);
this.context = this.element.getContext("2d");
}
See running code at http://jsfiddle.net/alnitak/zbaMh/, ideally using the Chrome Javascript Console so you can see the resulting object in the debug output.
In the interests of adding more situations to this question (because this is where I looked because I was having the exact same problem), here's my answer:
In my case, I cut/pasted the text from the generic error saying in effect if you want to see what's wrong, put
<system.web>
<customErrors mode="Off"/>
</system.web>
So this should have fixed it, but of course not! My problem was that there was a <system.web> node several lines above (before a compilation and authentication node), and a closing tag </system.web> a few lines below that. Once I corrected this, OK, problem solved. What I should have done is copy/pasted only this line:
<customErrors mode="Off"/>
This is from the annals of Stupid Things I Keep Doing Over and Over Again, in the chapter entitled "Copy and Paste Your Way to Destruction".
As Ciro Santilli notes using command substitutions will drop trailing newlines. Their workaround adding trailing characters is great, but after using it for quite some time I decided I needed a solution that didn't use command substitution at all.
My approach now uses read
along with the printf
builtin's -v
flag in order to read the contents of stdin directly into a variable.
# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
# Use unusual variable names to avoid colliding with a variable name
# the user might pass in (notably "contents")
: "${1:?Must provide a variable to read into}"
if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
echo "Cannot store contents to $1, use a different name." >&2
return 1
fi
local _line _contents=()
while IFS='' read -r _line; do
_contents+=("$_line"$'\n')
done
# include $_line once more to capture any content after the last newline
printf -v "$1" '%s' "${_contents[@]}" "$_line"
}
This supports inputs with or without trailing newlines.
Example usage:
$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file
Use Integer.parseInt
(see javadoc), that converts your String
to int
using base two:
int decimalValue = Integer.parseInt(c, 2);
If the file is local as your comment about SITE_PATH
suggest, it's pretty simple just execute the script and cache the result in a variable using the output control functions :
function print_xml_data_file()
{
include(XML_DATA_FILE_DIRECTORY . 'cms/data.php');
}
function get_xml_data()
{
ob_start();
print_xml_data_file();
$xml_file = ob_get_contents();
ob_end_clean();
return $xml_file;
}
If it's remote as lot of others said curl
is the way to go. If it isn't present try socket_create
or fsockopen
. If nothing work... change your hosting provider.
In jquery set focus
$(function() {
$("#txtBox1").focus();
});
or in Javascript you can do
window.onload = function() {
document.getElementById("txtBox1").focus();
};
Robert Sedgewick, "Algorithms in C", Addison-Wesley, 3rd Edition, 1997, [Section 3.4]
In case that is not a cyclic list ,hence NULL is the last link.
typedef struct node* link;
struct node{
int item;
link next;
};
/* you send the existing list to reverse() and returns the reversed one */
link reverse(link x){
link t, y = x, r = NULL;
while(y != NULL){
t = y->next;
y-> next = r;
r = y;
y = t;
}
return r;
}
If you want logs in a separate file other than the console: Double click on the server--> Open Launch Configuration--> Arguments --> add -Dlog.dir = "Path where you want to store this file" and restart the server.
Tip: Make sure that the server is not running when you are trying to add the argument. You should have log4j or similar logging framework in place.
I think it's asking you to do this:
SELECT ID
FROM (SELECT ID,
msisdn
FROM (SELECT * FROM TT2) as myalias
) as anotheralias;
But why would you write this query in the first place?
Actually, there's a solution with a moment.js plugin and it's very easy.
Don't reinvent the wheel again.
Just plug Moment.js Date Range Plugin.
var starts = moment('2014-02-03 12:53:12');_x000D_
var ends = moment();_x000D_
_x000D_
var duration = moment.duration(ends.diff(starts));_x000D_
_x000D_
// with ###moment precise date range plugin###_x000D_
// it will tell you the difference in human terms_x000D_
_x000D_
var diff = moment.preciseDiff(starts, ends, true); _x000D_
// example: { "years": 2, "months": 7, "days": 0, "hours": 6, "minutes": 29, "seconds": 17, "firstDateWasLater": false }_x000D_
_x000D_
_x000D_
// or as string:_x000D_
var diffHuman = moment.preciseDiff(starts, ends);_x000D_
// example: 2 years 7 months 6 hours 29 minutes 17 seconds_x000D_
_x000D_
document.getElementById('output1').innerHTML = JSON.stringify(diff)_x000D_
document.getElementById('output2').innerHTML = diffHuman
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>_x000D_
_x000D_
<script src="https://raw.githubusercontent.com/codebox/moment-precise-range/master/moment-precise-range.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<h2>Difference between "NOW and 2014-02-03 12:53:12"</h2>_x000D_
<span id="output1"></span>_x000D_
<br />_x000D_
<span id="output2"></span>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
You can do it by using Flexbox which is a good technique these days.
For using Flexbox you should give display: flex;
and align-items: center;
to your parent or #outer
div element. The code should be like this:
#outer {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">Foo foo</div>_x000D_
</div>
_x000D_
This should center your child or #inner
div horizontally. But you can't actually see any changes. Because our #outer
div has no height or in other words, its height is set to auto, so it has the same height as all of its child elements. So after a little of visual styling, the result code should be like this:
#outer {_x000D_
height: 500px;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
#inner {_x000D_
height: 100px;_x000D_
background: yellow;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">Foo foo</div>_x000D_
</div>
_x000D_
You can see #inner
div is now centered. Flexbox is the new method of positioning elements in horizontal or vertical stacks with CSS and it's got 96% of global browsers compatibility. So you are free to use it and if you want to find out more about Flexbox visit CSS-Tricks article. That is the best place to learn using Flexbox in my opinion.
How to search all columns of all tables in a database for a keyword?
http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm
EDIT: Here's the actual T-SQL, in case of link rot:
CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
Nouns.h
doesn't include <string>
, but it needs to. You need to add
#include <string>
at the top of that file, otherwise the compiler doesn't know what std::string
is when it is encountered for the first time.
The Tkinter library is built-in with every Python installation. And since you are on Windows, I believe you installed Python through the binaries on their website?
If so, Then most probably you are typing the command wrong. It should be:
import Tkinter as tk
Note the capital T at the beginning of Tkinter.
For Python 3,
import tkinter as tk
git checkout --[ours/theirs] .
will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.
One can avoid the AttributeError
brought about by set_axis_labels()
method by using the matplotlib.pyplot.xlabel
and matplotlib.pyplot.ylabel
.
matplotlib.pyplot.xlabel
sets the x-axis label while the matplotlib.pyplot.ylabel
sets the y-axis label of the current axis.
Solution code:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)
Output figure:
Not fitting 100% to this particular question but if you want to split from the back you can do it like this:
theStringInQuestion[::-1].split('/', 1)[1][::-1]
This code splits once at symbol '/' from behind.
If none of the above worked, try these as well:
In Component services >Computes >My Computer>Dcom config>Microsoft Excel Application>Properties
, go to security tab, click on customize on all three sections and add the user that want to run the application, and give full permissions to the user.
Go to C:\Windows\Temp
make sure it exists and it doesn't prompt you for entering.
While you have to checkout a repository, you can skip checking out any files with --no-checkout
and --depth 1
:
$ time git clone --no-checkout --depth 1 https://github.com/torvalds/linux .
Cloning into '.'...
remote: Enumerating objects: 75646, done.
remote: Counting objects: 100% (75646/75646), done.
remote: Compressing objects: 100% (71197/71197), done.
remote: Total 75646 (delta 6176), reused 22237 (delta 3672), pack-reused 0
Receiving objects: 100% (75646/75646), 201.46 MiB | 7.27 MiB/s, done.
Resolving deltas: 100% (6176/6176), done.
real 0m46.117s
user 0m13.412s
sys 0m19.641s
And while there is only a .git
directory:
$ ls -al
total 0
drwxr-xr-x 3 root staff 96 Dec 26 23:57 .
drwxr-xr-x+ 71 root staff 2272 Dec 27 00:03 ..
drwxr-xr-x 12 root staff 384 Dec 26 23:58 .git
you can get a directory listing via:
$ git ls-tree --full-name --name-only -r HEAD | head
.clang-format
.cocciconfig
.get_maintainer.ignore
.gitattributes
.gitignore
.mailmap
COPYING
CREDITS
Documentation/.gitignore
Documentation/ABI/README
or get the number of files via:
$ git ls-tree -r HEAD | wc -l
71259
or get the total file size via:
$ git ls-tree -l -r HEAD | awk '/^[^-]/ {s+=$4} END {print s}'
1006679487
I suggest another way to solve to this problem. The idea is wrapping your viewPager by a scrollView, so that when this scrollView is non-scrollable, your viewPager is non-scrollable too.
Here is my XML layout:
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</HorizontalScrollView>
No code needed.
Works fine for me.
its even simpler than that. Using HTML you can just add this metatag to your page (first thing on the page):
<meta http-equiv="X-UA-Compatible" content="IE=7" />
If you wanted to do it using.net, you just have to send your http request with that meta information in the header. This would require a page refresh to work though.
Also, you can look at a similar question here: Compatibility Mode in IE8 using VBScript
$(function() {
$('#sortable').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
change: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var index = ui.placeholder.index();
if (start_pos < index) {
$('#sortable li:nth-child(' + index + ')').addClass('highlights');
} else {
$('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
}
},
update: function(event, ui) {
$('#sortable li').removeClass('highlights');
}
});
});
Easiest Way!!!
If you are using Entity Framework and your Visual Studio Version is 2012 or higher,then
Its done. Now restart your visual studio and build your code.
What do these packages do?
After installing these packages no additional Oracle client software is required to be installed to connect to database.
This is almost the same as @Brocco 's answer, but with a slight twist: only pass optional parameters in an object. (And also make params object optional).
It ends up being kind of like Python's **kwargs, but not exactly.
export interface IErrorParams {
title?: string;
autoHideAfter?: number;
}
export interface INotificationService {
// make params optional so you don't have to pass in an empty object
// in the case that you don't want any extra params
error(message: string, params?: IErrorParams);
}
// all of these will work as expected
error('A message with some params but not others:', {autoHideAfter: 42});
error('Another message with some params but not others:', {title: 'StackOverflow'});
error('A message with all params:', {title: 'StackOverflow', autoHideAfter: 42});
error('A message with all params, in a different order:', {autoHideAfter: 42, title: 'StackOverflow'});
error('A message with no params at all:');
AFAIK, both substring()
and indexOf()
are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).
Your post indicates that you already know how to do it using substring()
and indexOf()
, so I'm not posting a code sample.
Add set clipboard=unnamed
to your .vimrc
. So it will use the clipboard register '*' instead of the unnamed register for all yank, delete, change and put operations (note it does not only affect the mouse).
The behavior of register '*' depends on your platform and how your vim
has been compiled (or if you use neovim
).
If it does not work, you can try with set clipboard=unnamedplus
, but this option only makes sense on X11 systems (and gvim therefore).
string = "firstName:name1, lastName:last1";
This will work:
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split(':');
fieldObject[c[0]] = c[1];
});
}
However it's not efficient. What happens when you have something like this:
string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";
split()
will split 'http'. So i suggest you use a special delimiter like pipe
string = "firstName|name1, lastName|last1";
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split('|');
fieldObject[c[0]] = c[1];
});
}
If you are using Linux and you got the permission error, you will need to raise the allowed limit in the /etc/limits.conf
or /etc/security/limits.conf
file (where the file is located depends on your specific Linux distribution).
For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the limits.conf
file.
* hard nofile 10000
Then logout and relogin to your system and you should be able to do:
ulimit -n 10000
without a permission error.