you can use a static array in your method, to avoid lose of your array when your function ends :
char * createStr()
{
char char1= 'm';
char char2= 'y';
static char str[3];
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)
I'd just use a simple regex, you can do something like this
import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
print item
Use the -H
header again before the Authorization:Basic things. So it will be
curl -i \
-H 'Accept:application/json' \
-H 'Authorization:Basic BASE64_string' \
http://example.com
Here, BASE64_string
= Base64 of username:password
Anyone looking for a jquery "combo box" seems to be directed to this question. My post is for people coming to this page to find a "traditional" combo box, rather than an answer to the original question. The above solutions all focus on using the input as a means to filtering and autocompleting to an existing select value. (great for large datasets)
If you're looking for the traditional combo box, which is simply "Type something or select from these pre-defined values" (no we won't hide the ones that don't match while you're typing), all you may need to do is
<select id="combo4" style="width: 200px;"
onchange="$('input#text4').val($(this).val());">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
<input id="text4"
style="margin-left: -203px; width: 180px; height: 1.2em; border: 0;" />
See http://bit.wisestamp.com/uncategorized/htmljquery-editable-combo-2/
Should be easy to wrap this into a plugin that converts an existing select tag, though I haven't seen that done yet.
P.S.: The main problem I see with "jQuery Editable Combobox" is that it remains a select list, and it is not obvious at all that you can just start typing something new.
I just installed vim by:
brew install vim
now the new vim is accessed by vim
and the old vim (built-in vim) by vi
Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH%
is used to represent value of existing path variable in Windows while ${PATH}
is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:
export CLASSPATH=${CLASSPATH}:/new/path
but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:
-cp
options overrides CLASSPATH
environment variable.-cp
and CLASSPATH
envorinment variable.Reference: How Classpath works in Java.
If you are using DataGrip you can do the following:
SELECT * FROM <your_table>;
*
and press Alt+Enter
Expand column list
option*
with full list of columnsYou can't have a non-keyword argument after a keyword argument.
Make sure you re-arrange your function arguments like so:
def a(len1,til,hgt=len1,col=0):
system('mode con cols='+len1,'lines='+hgt)
system('title',til)
system('color',col)
a(64,"hi",25,"0b")
Hello UdayaLakmal,
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication getInstance(){
return instance;
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if(appDir.exists()){
String[] children = appDir.list();
for(String s : children){
if(!s.equals("lib")){
deleteDir(new File(appDir, s));
Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Please check this and let me know...
You can download code from here
You should use the logging
library, which has this capability built in. You simply add handlers to a logger to determine where to send the output.
Here is a method for getting a random color:
private static Random sRandom;
public static synchronized int randomColor() {
if (sRandom == null) {
sRandom = new Random();
}
return 0xff000000 + 256 * 256 * sRandom.nextInt(256) + 256 * sRandom.nextInt(256)
+ sRandom.nextInt(256);
}
Benefits:
java.awt.Color
or android.graphics.Color
Random
.You can use :+
to append element to array and +:
to prepend it:
0 +: array :+ 4
should produce:
res3: Array[Int] = Array(0, 1, 2, 3, 4)
It's the same as with any other implementation of Seq
.
If number
could be None
or a number, and you wanted to include 0
, filter on None
instead:
if number is not None:
If number
can be any number of types, test for the type; you can test for just int
or a combination of types with a tuple:
if isinstance(number, int): # it is an integer
if isinstance(number, (int, float)): # it is an integer or a float
or perhaps:
from numbers import Number
if isinstance(number, Number):
to allow for integers, floats, complex numbers, Decimal
and Fraction
objects.
update: in the comments, Goerge says " This works on Chrome, Firefox and Edge, but not Safari."
This is the W3C solution. You can use it in 3012!
ul { list-style-type: "*"; } /* Sets the marker to a "star" character */
You may also use:
request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137]
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]
Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).
I was getting this env: node: No such file or directory
error when running the job through Jenkins.
What I did to fix it - added export PATH="$PATH:"/usr/local/bin/
at the beginning of the script that Jenkins job executes.
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with >
, >>
, or |
. stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:
command &> /some/file
EDIT: thanks to Zack for pointing out that the above solution is not portable--use instead:
*command* > file 2>&1
If you want to silence the error, do:
*command* 2> /dev/null
You could simply use an empty View with a bottom border.
<View
style={{
borderBottomColor: 'black',
borderBottomWidth: 1,
}}
/>
Try this one in your css document,
-fx-background-color : #ffaadd;
or
-fx-base : #ffaadd;
Also, you can set background color on your object with this code directly.
yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
shorter way: 1-Alt + Shift + R 2-Ctrl + 4 second way:(in menus of netBeans) 1-go to window tab 2-go to IDE tools 3-click on Test Result 4-again in window tab click on Output
I know this is an old question, but I wanted to make an answer of my own. here is another way to do this if you "really" want to add to the end of the list instead of using list.add(str)
you can do it this way, but I don't recommend.
String[] items = new String[]{"Hello", "World"};
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, items);
int endOfList = list.size();
list.add(endOfList, "This goes end of list");
System.out.println(Collections.singletonList(list));
this is the 'Compact' way of adding the item to the end of list. here is a safer way to do this, with null checking and more.
String[] items = new String[]{"Hello", "World"};
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, items);
addEndOfList(list, "Safer way");
System.out.println(Collections.singletonList(list));
private static void addEndOfList(List<String> list, String item){
try{
list.add(getEndOfList(list), item);
} catch (IndexOutOfBoundsException e){
System.out.println(e.toString());
}
}
private static int getEndOfList(List<String> list){
if(list != null) {
return list.size();
}
return -1;
}
Heres another way to add items to the end of list, happy coding :)
You should probably try to get rid of the warning completely, but if that's not possible, you can prepend the call with @ (i.e. @dns_get_record(...)) and then use any information you can get to figure out if the warning happened or not.
Try using this:
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
I had this issue recently and I resolved it by simply rolling IE8 back to IE7.
My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.
Oracle 11g provides a PIVOT
operation that does what you want.
Oracle 11g solution
select * from
(select id, k, v from _kv)
pivot(max(v) for k in ('name', 'age', 'gender', 'status')
(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)
I obtained this solution from: http://orafaq.com/wiki/PIVOT
EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml
option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)
select * from
(select id, k, v from _kv)
pivot xml (max(v)
for k in (any) )
(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)
Edit2: Changed v
in the pivot
and pivot xml
statements to max(v)
since it is supposed to be aggregated as mentioned in one of the comments. I also added the in
clause which is not optional for pivot
. Of course, having to specify the values in the in
clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.
Following is a sample of five different ways to summate values. The first is a naive way to perform the summation (and fails). The second attempts to use sprintf()
, but it too fails. The third uses sprintf()
successfully while the final two (4th & 5th) use floor($value + 0.5)
.
use strict;
use warnings;
use POSIX;
my @values = (26.67,62.51,62.51,62.51,68.82,79.39,79.39);
my $total1 = 0.00;
my $total2 = 0;
my $total3 = 0;
my $total4 = 0.00;
my $total5 = 0;
my $value1;
my $value2;
my $value3;
my $value4;
my $value5;
foreach $value1 (@values)
{
$value2 = $value1;
$value3 = $value1;
$value4 = $value1;
$value5 = $value1;
$total1 += $value1;
$total2 += sprintf('%d', $value2 * 100);
$value3 = sprintf('%1.2f', $value3);
$value3 =~ s/\.//;
$total3 += $value3;
$total4 += $value4;
$total5 += floor(($value5 * 100.0) + 0.5);
}
$total1 *= 100;
$total4 = floor(($total4 * 100.0) + 0.5);
print '$total1: '.sprintf('%011d', $total1)."\n";
print '$total2: '.sprintf('%011d', $total2)."\n";
print '$total3: '.sprintf('%011d', $total3)."\n";
print '$total4: '.sprintf('%011d', $total4)."\n";
print '$total5: '.sprintf('%011d', $total5)."\n";
exit(0);
#$total1: 00000044179
#$total2: 00000044179
#$total3: 00000044180
#$total4: 00000044180
#$total5: 00000044180
Note that floor($value + 0.5)
can be replaced with int($value + 0.5)
to remove the dependency on POSIX
.
I noticed following line from error.
exact fetch returns more than requested number of rows
That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.
Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.
So, I truncated dual
table and inserted only row which X
value. And, everything working fine.
Extending the Quote idea for Objective-C:
#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]
NSString *sql = NSStringMultiline(
SELECT name, age
FROM users
WHERE loggedin = true
);
The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:
Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.
EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage
function with Jcrop.
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6
You can't inject content from another site (domain) using AJAX. The reason an iFrame is suited for these kinds of things is that you can specify the source to be from another domain.
Some of the answers given here are either overcomplicated or just will not work (at least, not in all browsers). If you take a step back, you can see that the MySQL timestamp has each component of time in the same order as the arguments required by the Date()
constructor.
All that's needed is a very simple split on the string:
// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
console.log(d);
// -> Wed Jun 09 2010 14:12:01 GMT+0100 (BST)
Fair warning: this assumes that your MySQL server is outputting UTC dates (which is the default, and recommended if there is no timezone component of the string).
position:absolute;
top:0px;
margin:5px;
Solved my problem.
You can quote the entire path as in windows or you can escape the spaces like in:
/foo\ folder\ with\ space/foo.sh -help
Both ways will work!
First navigate to your Java/jre/bin folder in cmd cd c:\Program Files (x86)\Java\jre7\bin
Then use : [change debug.keystore path to the correct location on your system] install openssl (for windows 32 or 64 as per your needs at c:\openssl )
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.exe" sha1 -binary | "c:\openssl\bin\openssl.exe" base64
So the whole command goes like this : [prompts to enter keystore password on execution ]
c:\Program Files (x86)\Java\jre7\bin>keytool -exportcert -alias androiddebugkey
-keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.ex
e" sha1 -binary | "c:\openssl\bin\openssl.exe" base64
Enter keystore password:
I have a very simple solution for this problem: process.argv
gives you a list of arguments passed to node app.
So if you run:
node server.js 0.0.0.0
You'll get:
process.argv[0] //=> "node"
process.argv[1] //=> "server.js"
process.argv[2] //=> "0.0.0.0"
So you can use process.argv[2]
to specify that as the IP address you want to listen to:
http.listen(3000, process.argv[2]);
Now, your app is listening to "all" IP addresses, for example http://192.168.1.4:3000/your_app.
I hope this will help someone!
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir")
directory. This should be the working directory or the directory you ran the java command from.
Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...
Consider following example, suppose we have DataTable like below.
DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));
Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.
Area | Quantity | Breath | Length | Price = Quantity * breath *Length
Than we have to fire following query which will give us exact result as we want.
var data = ObjDt.AsEnumerable().Select
(r => new
{
Area = r.Field<string>("Area"),
Que = r.Field<int>("Quantity"),
Breath = r.Field<decimal>("Breath"),
Length = r.Field<decimal>("Length"),
totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
}).ToList();
We just have to assign this data variable as Data Source.
By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…
I was having issues because I updated my AdHoc provisioning profile with some new devices for use on TestFlight. Assumedly this is happening because Xcode has an old reference to your provisioning profile in either the codesigning build settings for the project or the targets. The way I fixed mine was to:
I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.
The easier is add [0]
- select first value of list with one element:
dfb = df[df['A']==5].index.values.astype(int)[0]
dfbb = df[df['A']==8].index.values.astype(int)[0]
dfb = int(df[df['A']==5].index[0])
dfbb = int(df[df['A']==8].index[0])
But if possible some values not match, error is raised, because first value not exist.
Solution is use next
with iter
for get default parameetr if values not matched:
dfb = next(iter(df[df['A']==5].index), 'no match')
print (dfb)
4
dfb = next(iter(df[df['A']==50].index), 'no match')
print (dfb)
no match
Then it seems need substract 1
:
print (df.loc[dfb:dfbb-1,'B'])
4 0.894525
5 0.978174
6 0.859449
Name: B, dtype: float64
Another solution with boolean indexing
or query
:
print (df[(df['A'] >= 5) & (df['A'] < 8)])
A B
4 5 0.894525
5 6 0.978174
6 7 0.859449
print (df.loc[(df['A'] >= 5) & (df['A'] < 8), 'B'])
4 0.894525
5 0.978174
6 0.859449
Name: B, dtype: float64
print (df.query('A >= 5 and A < 8'))
A B
4 5 0.894525
5 6 0.978174
6 7 0.859449
If this is nullable int field then yes.
update TableName
set FiledName = null
where Id = SomeId
buttion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new com.google.zxing.integration.android.IntentIntegrator(Fragment.this).initiateScan();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
compile 'com.google.zxing:core:3.2.1'
compile 'com.android.support:appcompat-v7:23.1.0'
}
I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).
The solution is here : check your /etc/redis/redis.conf
, and make sure to change the default
bind 127.0.0.1
to
bind 0.0.0.0
Then restart your service (service redis-server restart
)
You can then now check that redis is listening on non-local interface with
redis-cli -h 192.168.x.x ping
(replace 192.168.x.x with your IP adress)
Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.
Found the solution.
In the parent I declare a new instance of the ChildClass() then bind the event handler in that class to the local method in the parent
In the child class I add a public event handler:
public EventHandler UpdateProgress;
In the parent I create a new instance of this child class then bind the local parent event to the public
eventhandler
in the child
ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);
Then in the LoadData()
of the child class I can call
private LoadData() {
this.OnMyMethod();
}
Where OnMyMethod
is:
public void OnMyMethod()
{
// has the event handler been assigned?
if (this.UpdateProgress!= null)
{
// raise the event
this.UpdateProgress(this, new EventArgs());
}
}
This runs the event in the parent class
If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!
Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element
in the example below) that we know exists when the page loads. Here's how:
$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})
Some more reading on the subject:
var url = "http://www.example.com";
window.open(url, '_blank');
Most of the time, the problem is due to some error on the human side. In my case, I was using some classes whose names are similar. I have added the empty() method under one class; however, my code was calling the empty() method from another class. At that moment, the mind was stuck. I was running make clean, and remake thinking that it was some older version of the header got used. After walking away for a moment, I found that problem right away. We programmers tends to blame others first. Maybe we should insist on ourselves to be wrong first.
Sometimes, I forget to write the latest update to disk and looking at the correct version of the code, but the compiler is seeing the wrong version of the code. This situation may be less a issue on IDE (I use vi to do coding).
import sys
sys.executable
will give you the interpreter. You can select the interpreter you want when you create a new notebook. Make sure the path to your anaconda interpreter is added to your path (somewhere in your bashrc/bash_profile most likely).
For example I used to have the following line in my .bash_profile, that I added manually :
export PATH="$HOME/anaconda3/bin:$PATH"
EDIT: As mentioned in a comment, this is not the proper way to add anaconda to the path. Quoting Anaconda's doc, this should be done instead after install, using conda init
:
Should I add Anaconda to the macOS or Linux PATH?
We do not recommend adding Anaconda to the PATH manually. During installation, you will be asked “Do you wish the installer to initialize Anaconda3 by running conda init?” We recommend “yes”. If you enter “no”, then conda will not modify your shell scripts at all. In order to initialize after the installation process is done, first run
source <path to conda>/bin/activate
and then runconda init
Using following commands to uninstall :
npm uninstall -g @angular/cli
npm cache clean --force
To verify: ng --version /* You will get the error message, then u have uninstalled */
Using following commands to re-install :
npm install -g @angular/cli
Notes :
- Using --force for clean all the caches
- On Windows run this using administrator
- On Mac use sudo ($ sudo <command>
)
npm>5
you may need to use cache verify instead. ($ npm cache verify
)The bottom line is that virtual functions make life easier. Let's use some of M Perry's ideas and describe what would happen if we didn't have virtual functions and instead only could use member-function pointers. We have, in the normal estimation without virtual functions:
class base {
public:
void helloWorld() { std::cout << "Hello World!"; }
};
class derived: public base {
public:
void helloWorld() { std::cout << "Greetings World!"; }
};
int main () {
base hwOne;
derived hwTwo = new derived();
base->helloWorld(); //prints "Hello World!"
derived->helloWorld(); //prints "Hello World!"
Ok, so that is what we know. Now let's try to do it with member-function pointers:
#include <iostream>
using namespace std;
class base {
public:
void helloWorld() { std::cout << "Hello World!"; }
};
class derived : public base {
public:
void displayHWDerived(void(derived::*hwbase)()) { (this->*hwbase)(); }
void(derived::*hwBase)();
void helloWorld() { std::cout << "Greetings World!"; }
};
int main()
{
base* b = new base(); //Create base object
b->helloWorld(); // Hello World!
void(derived::*hwBase)() = &derived::helloWorld; //create derived member
function pointer to base function
derived* d = new derived(); //Create derived object.
d->displayHWDerived(hwBase); //Greetings World!
char ch;
cin >> ch;
}
While we can do some things with member-function pointers, they aren't as flexible as virtual functions. It is tricky to use a member-function pointer in a class; the member-function pointer almost, at least in my practice, always must be called in the main function or from within a member function as in the above example.
On the other hand, virtual functions, while they might have some function-pointer overhead, do simplify things dramatically.
EDIT: There is another method which is similar by eddietree: c++ virtual function vs member function pointer (performance comparison) .
The CSS Tooltip allows you to format the popup as you like as any div
section! And no Javascript needed.
A friendly method to use is the following, once prop updates it will automatically rerender component:
render {
let textWhenComponentUpdate = this.props.text
return (
<View>
<Text>{textWhenComponentUpdate}</Text>
</View>
)
}
You can try console.log("%cI am red %cI am green", "color: red", "color: green");
Using basename
assumes that you know what the file extension is, doesn't it?
And I believe that the various regular expression suggestions don't cope with a filename containing more than one "."
The following seems to cope with double dots. Oh, and filenames that contain a "/" themselves (just for kicks)
To paraphrase Pascal, "Sorry this script is so long. I didn't have time to make it shorter"
#!/usr/bin/perl
$fullname = $ARGV[0];
($path,$name) = $fullname =~ /^(.*[^\\]\/)*(.*)$/;
($basename,$extension) = $name =~ /^(.*)(\.[^.]*)$/;
print $basename . "\n";
What about this?
(function($) {
$(function() {
// more code using $ as alias to jQuery
// will be fired when document is ready
});
})(jQuery);
I got the similiar issue, and resolved it by the following. The issue looks not related to the Route definition but definition of the parameters, just need to give it a default value.
----Code with issue: Message: "No HTTP resource was found that matches the request URI
[HttpGet]
[Route("students/list")]
public StudentListResponse GetStudents(int? ClassId, int? GradeId)
{
...
}
----Code without issue.
[HttpGet]
[Route("students/list")]
public StudentListResponse GetStudents(int? ClassId=null, int? GradeId=null)
{
...
}
ocw.mit.edu is a great resource that has helped me a bunch. randi is the best option, but if your into number fun try using the floor function with rand to get what you want.
I drew a number line and came up with
floor(rand*8) + 13
I find this way more readable:
$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";
Not that I have anything against arrays...
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:
For radio button:
var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();
For textbox:
var txt=$('input:text[name=DrugDurationLength]').val();
Do a quick 'record macro' to see the color number associated with the color you're looking for (yellow highlight is 65535). Then erase the code and put
Sub Name()
Selection.Interior.Color = 65535 '(your number may be different depending on the above)
End Sub
What you are talking about is the way a parameterized query is written. '@' just signifies that it is a parameter. You can add the value for that parameter during execution process
eg:
sqlcommand cmd = new sqlcommand(query,connection);
cmd.parameters.add("@custid","1");
sqldatareader dr = cmd.executequery();
If you don't need to go through Git itself, you can also delete heads under .git/refs/heads manually or programmatically. The following should work with minimal tweaking under Bash:
shopt -s extglob
rm -rf .git/refs/heads/!(master)
This will delete every local branch except your master branch. Since your upstream branches are stored under .git/refs/remotes, they will remain untouched.
If you are not using Bash, or want to recurse a lot of Git repositories at once, you can do something similar with GNU find:
find . \
-path remotes -path logs -prune -o \
-wholename \*.git/refs/heads/\* \! -name master -print0 |
xargs -0 rm -rf
The find solution is probably more portable, but pruning paths and filenames is tricky and potentially more error-prone.
Did you try adding the self prefix to the fileName and replacing the method above the Button ? With the self, it becomes visible between methods.
...
def load_file(self):
self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
...
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
this.state.myArray.push('new value')
returns the length of the extended array, instead of the array itself.Array.prototype.push().
I guess you expect the returned value to be the array.
It seems it's rather the behaviour of React:
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.React.Component.
I guess, you would do it like this (not familiar with React):
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })
Setting the slice to nil
is the best way to clear a slice. nil
slices in go are perfectly well behaved and setting the slice to nil
will release the underlying memory to the garbage collector.
package main
import (
"fmt"
)
func dump(letters []string) {
fmt.Println("letters = ", letters)
fmt.Println(cap(letters))
fmt.Println(len(letters))
for i := range letters {
fmt.Println(i, letters[i])
}
}
func main() {
letters := []string{"a", "b", "c", "d"}
dump(letters)
// clear the slice
letters = nil
dump(letters)
// add stuff back to it
letters = append(letters, "e")
dump(letters)
}
Prints
letters = [a b c d]
4
4
0 a
1 b
2 c
3 d
letters = []
0
0
letters = [e]
1
1
0 e
Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil
will remove that aliasing.
This method changes the capacity to zero though.
My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.
//To align it to the left
p.add(b, BorderLayout.WEST);
//To align it to the right
p.add(b, BorderLayout.EAST);
//To align it at the top
p.add(b, BorderLayout.NORTH);
//To align it to the bottom
p.add(b, BorderLayout.SOUTH);
//To align it to the center
p.add(b, BorderLayout.CENTER);
Don't forget to import it as well by typing:
import java.awt.BorderLayout;
There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!
I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.
Saying that there is a way to allow "Friend" assemblies access to internals:
In the AssemblyInfo.cs file of the project you add a line for each assembly.
[assembly: InternalsVisibleTo("name of assembly here")]
this info is available here.
Hope this helps.
Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.
Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec
executable, SSIS will not be able to find the Oracle client.
The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.
If you are using your own CustomView extending View class, you need to call canvas.invalidate() method which will internally call onDraw method. You can use default API for canvas to draw a circle. The x, y cordinate define the center of the circle. You can also define color and styling in paint & pass the paint object.
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
setupPaint();
}
}
Define default paint settings and canvas (Initialise paint in constructor so that you can reuse the same object everywhere and change only specific settings wherever required)
private Paint drawPaint;
// Setup paint with color and stroke styles
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(Color.BLUE);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.FILL_AND_STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
And initialise canvas object
private Canvas canvas;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
canvas.drawCircle(xCordinate, yCordinate, RADIUS, drawPaint);
}
And finally, for every view refresh or new draw on the screen, you need to call invalidate method. Remember your entire view is redrawn, hence this is an expensive call. Make sure you do only the necessary operations in onDraw
canvas.invalidate();
For more details on canvas drawing refer https://medium.com/@mayuri.k18/android-canvas-for-drawing-and-custom-views-e1a3e90d468b
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
cleaner way to do this is using foreach
foreach(var item in li.Where(w => w.name =="di"))
{
item.age=10;
}
$ErrorActionPreference = "Stop"
will get you part of the way there (i.e. this works great for cmdlets).
However for EXEs you're going to need to check $LastExitCode
yourself after every exe invocation and determine whether that failed or not. Unfortunately I don't think PowerShell can help here because on Windows, EXEs aren't terribly consistent on what constitutes a "success" or "failure" exit code. Most follow the UNIX standard of 0 indicating success but not all do. Check out the CheckLastExitCode function in this blog post. You might find it useful.
Outliers are quite similar to peaks, so a peak detector can be useful for identifying outliers. The method described here has quite good performance using z-scores. The animation part way down the page illustrates the method signaling on outliers, or peaks.
Peaks are not always the same as outliers, but they're similar frequently.
An example is shown here: This dataset is read from a sensor via serial communications. Occasional serial communication errors, sensor error or both lead to repeated, clearly erroneous data points. There is no statistical value in these point. They are arguably not outliers, they are errors. The z-score peak detector was able to signal on spurious data points and generated a clean resulting dataset:
var countChange = function (money,coins) {
function countChangeSub(money,coins,n) {
if(money==0) return 1;
if(money<0 || coins.length ==n) return 0;
return countChangeSub(money-coins[n],coins,n) + countChangeSub(money,coins,n+1);
}
return countChangeSub(money,coins,0);
}
it's as simple as this
$.post({url: "som_page.php",
data: { data1: value1, data2: value2 }
).done(function( data ) {
$( "body" ).html(data);
});
});
I had to solve this to make a screen lock of my application where I had to pass sensitive data as user and the url where he was working. Then create a function that executes this code
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
If you are using CustomBinding then you would rather need to make changes in httptransport element. Set it as
<customBinding>
<binding ...>
...
<httpsTransport maxReceivedMessageSize="2147483647"/>
</binding>
</customBinding>
Concatenation of words in the package name is something most developers don't do.
You can use something like.
com.stackoverflow.mypackage
Refer JLS Name Declaration
Just ran into this problem after installing material-ui.
Solved it by simply running npm install
again.
There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.
After importing the HOC you can then use it like this with the necessary methods:
/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
// start off with the existing state
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
}
/**
* Toggle all checkboxes for select table
*/
toggleAll() {
const selectAll = !this.state.selectAll;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.checkboxTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we just push all the IDs onto the selection array
currentRecords.forEach(item => {
selection.push(item._original._id);
});
}
this.setState({ selectAll, selection });
}
/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
return this.state.selection.includes(key);
}
<CheckboxTable
ref={r => (this.checkboxTable = r)}
toggleSelection={this.toggleSelection}
selectAll={this.state.selectAll}
toggleAll={this.toggleAll}
selectType="checkbox"
isSelected={this.isSelected}
data={data}
columns={columns}
/>
See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable
Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw
Sorry for necro.
I have too run into the same issue and found out that rJava
expects JAVA_HOME
to point to JRE. If you have JDK installed, most probably your JAVA_HOME
points to JDK. My quick solution:
Sys.setenv(JAVA_HOME=paste(Sys.getenv("JAVA_HOME"), "jre", sep="\\"))
JSTool is the best for stability.
Steps:
Reference:
You need to build query from "data" object using the following function
function buildQuery(obj) {
var Result= '';
if(typeof(obj)== 'object') {
jQuery.each(obj, function(key, value) {
Result+= (Result) ? '&' : '';
if(typeof(value)== 'object' && value.length) {
for(var i=0; i<value.length; i++) {
Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
}
} else {
Result+= [key, encodeURIComponent(value)].join('=');
}
});
}
return Result;
}
and then proceed with
var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: buildQuery(data),
error: function(e) {
console.log(e);
}
});
This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project
Just compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}
This constructor of string
takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since rbegin()
is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of input
added to it in reverse, reversing the string.
Then you just compare it to input
and if they are equal, it is a palindrome.
This does not take into account capitalisation or spaces, so you'll have to improve on it yourself.
Found the reason!! If Android Studio has a proxy server setting and can't reach the server then it takes a long time to build, probably its trying to reach the proxy server and waiting for a timeout. When I removed the proxy server setting its working fine.
Removing proxy: File > Settings > Appearance & Behavior > System settings > HTTP Proxy
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid()
function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
You can press q to exit.
git hist
is using a pager tool so you can scroll up and down the results before returning to the console.
input type = number
When you want to provide a number input, you can use the HTML5 input type="number" attribute value.
<input type="number" name="n" />
Here is the keyboard that comes up on iPhone 4:
iPhone Screenshot of HTML5 input type number Android 2.2 uses this keyboard for type=number:
Android Screenshot of HTML5 input type number
In your terminal run: docker exec -it container_name /bin/bash
Then: mysql
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
Easily: Your data frame is A
b <- A[,1]
b <- b==1
b <- cumsum(b)
Then you get the column b.
From Laravel 5.6 you can use whereDate:
$users = Users::where('status_id', 'active')
->whereDate( 'created_at', '>', now()->subDays(30))
->get();
You also have whereMonth / whereDay / whereYear / whereTime
For all kind of files, subdirectories included:
import os
list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files
Only files (avoiding subdirectories):
import os
onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)
If you're not using AngularJS UI Bootstrap, here's how I did it.
I created a directive that will hold that entire element of your modal, and recompile the element to inject your scope into it.
angular.module('yourApp', []).
directive('myModal',
['$rootScope','$log','$compile',
function($rootScope, $log, $compile) {
var _scope = null;
var _element = null;
var _onModalShow = function(event) {
_element.after($compile(event.target)(_scope));
};
return {
link: function(scope, element, attributes) {
_scope = scope;
_element = element;
$(element).on('show.bs.modal',_onModalShow);
}
};
}]);
I'm assuming your modal template is inside the scope of your controller, then add directive my-modal to your template. If you saved the clicked user to $scope.aModel, the original template will now work.
Note: The entire scope is now visible to your modal so you can also access $scope.users in it.
<div my-modal id="encouragementModal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h3>Confirm encouragement?</h3>
</div>
<div class="modal-body">
Do you really want to encourage <b>{{aModel.userName}}</b>?
</div>
<div class="modal-footer">
<button class="btn btn-info"
ng-click="encourage('${createLink(uri: '/encourage/')}',{{aModel.userName}})">
Confirm
</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
</div>
</div>
Here's a function that does what you want:
import re
def is_match(regex, text):
pattern = re.compile(regex, text)
return pattern.search(text) is not None
The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.
Examples:
>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False
Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.
The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.
Here is a good article about fluid vs. flex.
I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (i.e. using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.
Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;
var customer = new Customer(); //no Id yet;
var order = new Order(); //requires Customer.Id to link it to customer;
context.Customers.Add(customer);
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id
However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId
All I had to do was this;
var customer = new Customer(); //no Id yet;
var order = new Order{Customer = customer};
context.Orders.Add(order);
context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order
Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps
I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.
This also means that updates complete in a single transaction, potentially avoiding orphin data (either all updates complete, or none do).
I had a 12GB file to edit today. The vim LargeFile plugin did not work for me. It still used up all my memory and then printed an error message :-(. I could not use hexedit for either, as it cannot insert anything, just overwrite. Here is an alternative approach:
You split the file, edit the parts and then recombine it. You still need twice the disk space though.
Grep for something surrounding the line you would like to edit:
grep -n 'something' HUGEFILE | head -n 1
Extract that range of the file. Say the lines you want to edit are at line 4 and 5. Then do:
sed -n -e '4,5p' -e '5q' HUGEFILE > SMALLPART
-n
option is required to suppress the default behaviour of sed to print everything4,5p
prints lines 4 and 55q
aborts sed after processing line 5 Edit SMALLPART
using your favourite editor.
Combine the file:
(head -n 3 HUGEFILE; cat SMALLPART; sed -e '1,5d' HUGEFILE) > HUGEFILE.new
HUGEFILE.new
will now be your edited file, you can delete the original HUGEFILE
.
i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:
RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
to your .htaccess file
Use the following:
WHERE datex BETWEEN GETDATE() AND DATEADD(DAY, -7, GETDATE())
Hope this helps.
You just have to read the laravel installation page:
composer global require "laravel/installer"
Inside your htdocs or www directory, use either:
laravel new appName
(this can lead to an error on windows computers while using latest Laravel (1.3.2)) or:
composer create-project --prefer-dist laravel/laravel appName
(this works also on windows) to create a project called "appName".
To use "php artisan xyz" you have to be inside your project root! as artisan is a file php is going to use... Simple as that ;)
I think you conclusions are correct but not accurate.
As the docs indicates, socket.recv
is majorly focused on the network buffers.
When socket is blocking, socket.recv
will return as long as the network buffers have bytes. If bytes in the network buffers are more than socket.recv
can handle, it will return the maximum number of bytes it can handle. If bytes in the network buffers are less than socket.recv
can handle, it will return all the bytes in the network buffers.
VAR=8675309
echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1'
where VAR
contains what you want to replace the field with
For renaming the columns here is the simple one which will work for both Default(0,1,2,etc;)
and existing columns but not much useful for a larger data sets(having many columns).
For a larger data set we can slice the columns that we need and apply the below code:
df.columns = ['new_name','new_name1','old_name']
I just wanted to append to Imanou Petit's answer #2. To ensure margins are exact regardless of screen width, I use an iterative solver with a desired margin, and the # of columns as inputs. I also added a directional flag on where their final margins will be compared to their target.
The iterative solver is shown below and returns cellWidth and margin.
private func iterativeCellSpacing(targetMargins : CGFloat,
cellsPerRow : Int,
isMinTarget : Bool) -> (CGFloat, CGFloat)
{
var w : CGFloat = 0
var m : CGFloat = targetMargins
let cols : CGFloat = CGFloat(cellsPerRow)
let numMargins : CGFloat = cols + 1.0
let screenWidth : CGFloat = collectionView!.bounds.size.width
var delta = CGFloat.greatestFiniteMagnitude
while abs(delta) > 0.001
{
let totalMarginSpacing = numMargins * m
let totalCellSpacing = screenWidth - totalMarginSpacing
if (isMinTarget)
{
w = floor(totalCellSpacing / cols)
m = ceil((screenWidth - cols * w) / numMargins)
}
else
{
w = ceil(totalCellSpacing / cols)
m = floor((screenWidth - cols * w) / numMargins)
}
delta = screenWidth - w * CGFloat(cellsPerRow) - m * numMargins
}
return (w, m)
}
I call it as such:
fileprivate var margin: CGFloat = 20
fileprivate var cellWidth : CGFloat = 80
fileprivate let cellsPerRow = 4
override func viewDidLoad()
{
super.viewDidLoad()
(cellWidth, margin) = iterativeCellSpacing(targetMargins: margin, cellsPerRow: 4, isMinTarget: true)
...
}
I then apply the cellWidth and margin values to the flow layout as such:
extension MyCollectionController : UICollectionViewDelegateFlowLayout
{ func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: cellWidth, height: cellWidth) }
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
return UIEdgeInsetsMake(margin, margin, margin, margin)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
return margin
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
{
return margin
}
}
Hope this helps. There probably is an easier way to ensure margins are exact, but this is one method. Also, this code hasn't been tested for devices that allow rotating collectionviews.
Thanks,
Use unlist
with use.names = FALSE
argument.
unlist(myList, use.names=FALSE)
I had the same issue. The issue was that the "google-play-services.jar" was not properly imported into my project even though it was part of the google_play_service_lib project. If you are using Eclipse, please check and see if you can see the play services jar file in the Android Private Libraries section and if this is exported by the library.
I am using Android SDK platform tools version 17 (not 19) and Android SDK tools version 22.0.1
For Windows 10: What worked for me was clearing the credentials in the Windows Credentials in the Credential Manager.
You could use XDocument:
new XDocument(
new XElement("root",
new XElement("someNode", "someValue")
)
)
.Save("foo.xml");
If the file you want to create is very big and cannot fit into memory you might use XmlWriter.
The easiest way would be
Section = 'Sec_' + Section
But for efficiency, see: https://waymoot.org/home/python_string/
Assuming your page size is 20 record, and you wanna get page number 2, here is how you would do it:
SQL Server, Oracle:
SELECT * -- <-- pick any columns here from your table, if you wanna exclude the RowNumber
FROM (SELECT ROW_NUMBER OVER(ORDER BY ID DESC) RowNumber, *
FROM Reflow
WHERE ReflowProcessID = somenumber) t
WHERE RowNumber >= 20 AND RowNumber <= 40
MySQL:
SELECT *
FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 20 OFFSET 20
SET search_path TO public;
DROP EXTENSION IF EXISTS "uuid-ossp";
CREATE EXTENSION "uuid-ossp" SCHEMA public;
If this is a fresh installation you can skip SET
and DROP
. Credits to @atomCode (details)
After this, you should see uuid_generate_v4() function IN THE RIGHT SCHEMA (when execute \df
query in psql command-line prompt).
schemaname.
qualifier):CREATE TABLE public.my_table (
id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
This is an old question, but it came up first for me in google results when searching "mongoose insert array of documents".
There are two options model.create() [mongoose] and model.collection.insert() [mongodb] which you can use. View a more thorough discussion here of the pros/cons of each option:
Simple, send one header location.
My site, contains one image, and after upload the image, there not change, then I add this code:
<?php header("Location: pagelocalimage.php"); ?>
Work's for me.
My problem was in my application.yml file. My database url
on heroku
was not using port 5342. Check your heroku
config var DATABASE_URL
. Make sure that matches exactly with was in your application.yml for the applicable database.
The following command may help you..
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
The plugin's author says you should use "square brackets without the quotes", []
http://bassistance.de/2011/10/07/release-validation-plugin-1-9-0/
Release: Validation Plugin 1.9.0: "...Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes)."
To change this setting for all forms:
$.validator.setDefaults({
ignore: [],
// any other default options and/or rules
});
(It is not required that .setDefaults()
be within the document.ready
function)
OR for one specific form:
$(document).ready(function() {
$('#myform').validate({
ignore: [],
// any other options and/or rules
});
});
EDIT:
See this answer for how to enable validation on some hidden fields but still ignore others.
EDIT 2:
Before leaving comments that "this does not work", keep in mind that the OP is simply asking about the jQuery Validate plugin and his question has nothing to do with how ASP.NET, MVC, or any other Microsoft framework can alter this plugin's normal expected behavior. If you're using a Microsoft framework, the default functioning of the jQuery Validate plugin is over-written by Microsoft's unobtrusive-validation
plugin.
If you're struggling with the unobtrusive-validation
plugin, then please refer to this answer instead: https://stackoverflow.com/a/11053251/594235
Section 6.5.8.6 of the C standard says:
Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.
a version similar to C. Dragon's, but for if you only need a single replacement:
int n = myText.IndexOf(oldValue, System.StringComparison.InvariantCultureIgnoreCase);
if (n >= 0)
{
myText = myText.Substring(0, n)
+ newValue
+ myText.Substring(n + oldValue.Length);
}
grep -nr string my_directory
Additional notes: this satisfies the syntax grep [options] string filename
because in Unix-like systems, a directory is a kind of file (there is a term "regular file" to specifically refer to entities that are called just "files" in Windows).
grep -nr string
reads the content to search from the standard input, that is why it just waits there for input from you, and stops doing so when you press ^C (it would stop on ^D as well, which is the key combination for end-of-file).
There is a easy way to do it.
NSArray *myArray = @[@"5",@"4",@"3",@"2",@"1"];
NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
for(int i=0; i<[myNewArray count]; i++){
[myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
}
//other way to do it
for(NSString *eachValue in myArray){
[myNewArray insertObject:eachValue atIndex:0];
}
//in both cases your new array will look like this
NSLog(@"myNewArray: %@", myNewArray);
//[@"1",@"2",@"3",@"4",@"5"]
I hope this helps.
char variable = 'x'; // the variable is a char whose value is lowercase x
printf("<%c>", variable); // print it with angle brackets around the character
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test
if you choose res.render
method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
Add a temporary Objective-C file to your project. You may give it any name you like.
Select Yes to configure an Objective-C bridging header.
Delete the temporary Objective-C file you just created.
In the projectName-Bridging-Header.h file just created, add this line:
'#import < GoogleMaps/GoogleMaps.h >'
Edit the AppDelegate.swift file:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
GMSServices.provideAPIKey("AIza....") //iOS API key
return true
}
Follow the link for full sample
You need to replace open
with urllib.urlopen or urllib2.urlopen.
e.g.
import csv
import urllib2
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)
for row in cr:
print row
This would output the following
Year,City,Sport,Discipline,NOC,Event,Event gender,Medal
1924,Chamonix,Skating,Figure skating,AUT,individual,M,Silver
1924,Chamonix,Skating,Figure skating,AUT,individual,W,Gold
...
The original question is tagged "python-2.x", but for a Python 3 implementation (which requires only minor changes) see below.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
It's far from pretty, but you could create a script or an alias that does something like this:
for c in $(git for-each-ref refs/tags/ --format='%(refname)'); do echo $c; git show --quiet "$c"; echo; done
Alternatively, you can use jinfo
jinfo -flags <vmid>
jinfo -sysprops <vmid>
Try doing it this way, it worked for me:
$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`
Seems like the rule always has the validation on the first input among the pair...
MiniDLNA uses inotify
, which is a functionality within the Linux kernel, used to discover changes in specific files and directories on the file system. To get it to work, you need inotify support enabled in your kernel.
The notify_interval
(notice the lack of a leading 'i'), as far as I can tell, is only used if you have inotify disabled. To use the notify_interval
(ie. get the server to 'poll' the file system for changes instead of automatically being notified of them), you have to disable the inotify
functionality.
This is how it looks in my /etc/minidlna.conf
:
# set this to no to disable inotify monitoring to automatically discover new files
# note: the default is yes
inotify=yes
Make sure that inotify is enabled in your kernel.
If it's not enabled, and you don't want to enable it, a forced rescan is the way to force MiniDLNA to re-scan the drive.
As far as I can see from the implementation at https://github.com/angular/angular/blob/master/packages/common/http/src/params.ts
You must provide values separately - You are not able to avoid your loop.
There is also a constructor which takes a string as a parameter, but it is in form param=value¶m2=value2
so there is no deal for You (in both cases you will finish with looping your object).
You can always report an issue/feature request to angular, what I strongly advise: https://github.com/angular/angular/issues
PS: Remember about difference between set
and append
methods ;)
t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")
Go to your project folder\app\src\main\res\mipmap-mdpi\ic_launcher.png
You will see 5 mipmap folders. Replace the icon inside of the each mipmap folder, with the icon you want.
You asked why it happens, let's see:
The official language specificaion dictates a call to the internal [[GetValue]]
method. Your .attr
returns undefined and you're trying to access its length.
If Type(V) is not Reference, return V.
This is true, since undefined is not a reference (alongside null, number, string and boolean)
Let base be the result of calling GetBase(V).
This gets the undefined
part of myVar.length
.
If IsUnresolvableReference(V), throw a ReferenceError exception.
This is not true, since it is resolvable and it resolves to undefined.
If IsPropertyReference(V), then
This happens since it's a property reference with the .
syntax.
Now it tries to convert undefined
to a function which results in a TypeError.
I'm looking for a function that checks only if it's one of the Latin letters or a decimal number. Since char c = 255
, which in printable version is + and considered as a letter by Character.isLetter(c)
.
This function I think is what most developers are looking for:
private static boolean isLetterOrDigit(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9');
}
The following signature will do:
List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);
Spring Data JPA supports a large number of keywords to build a query. IN
and AND
are among them.
Extend HttpServletRequestWrapper
, override the header getters to return the parameters as well:
public class AddParamsToHeader extends HttpServletRequestWrapper {
public AddParamsToHeader(HttpServletRequest request) {
super(request);
}
public String getHeader(String name) {
String header = super.getHeader(name);
return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.
}
public Enumeration getHeaderNames() {
List<String> names = Collections.list(super.getHeaderNames());
names.addAll(Collections.list(super.getParameterNames()));
return Collections.enumeration(names);
}
}
..and wrap the original request with it:
chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);
That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.
.md is markdown
. README.md
is used to generate the html
summary you see at the bottom of projects. Github has their own flavor of Markdown.
Order of Preference: If you have two files named README
and README.md
, the file named README.md
is preferred, and it will be used to generate github's html
summary.
FWIW, Stack Overflow uses local Markdown modifications as well (also see Stack Overflow's C# Markdown Processor)
My prefered technique :
body {
display: table;
position: absolute;
height: 100%;
width: 100%;
}
.jumbotron {
display: table-cell;
vertical-align: middle;
}
body {_x000D_
display: table;_x000D_
position: absolute;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.jumbotron {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<div class="jumbotron vertical-center">_x000D_
<div class="container text-center">_x000D_
<h1>The easiest and powerful way</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-7">_x000D_
<div class="top-bg">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>_x000D_
</div>_x000D_
_x000D_
<div class="col-md-5 iPhone-features">_x000D_
<ul class="top-features">_x000D_
<li>_x000D_
<span><i class="fa fa-random simple_bg top-features-bg"></i></span>_x000D_
<p><strong>Redirect</strong><br>Visitors where they converts more.</p>_x000D_
</li>_x000D_
<li>_x000D_
<span><i class="fa fa-cogs simple_bg top-features-bg"></i></span>_x000D_
<p><strong>Track</strong><br>Views, Clicks and Conversions.</p>_x000D_
</li>_x000D_
<li>_x000D_
<span><i class="fa fa-check simple_bg top-features-bg"></i></span>_x000D_
<p><strong>Check</strong><br>Constantly the status of your links.</p>_x000D_
</li>_x000D_
<li>_x000D_
<span><i class="fa fa-users simple_bg top-features-bg"></i></span>_x000D_
<p><strong>Collaborate</strong><br>With Customers, Partners and Co-Workers.</p>_x000D_
</li>_x000D_
<a href="pricing-and-signup.html" class="btn-primary btn h2 lightBlue get-Started-btn">GET STARTED</a>_x000D_
<h6 class="get-Started-sub-btn">FREE VERSION AVAILABLE!</h6>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
See also this Fiddle!
How about calling the .NET Framework methods?
You can do ANYTHING with them... :
[System.IO.File]::Copy($src, $dest, $true);
The $true
argument makes it overwrite.
To allow https wrapper:
php_openssl
extension must exist and be enabled allow_url_fopen
must be set to on
In the php.ini file you should add this lines if not exists:
extension=php_openssl.dll
allow_url_fopen = On
As far as I can tell there is no upper limit in 2008.
In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg
variable with
Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.
the code below fails with
REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.
However it appears these limitations have quietly been lifted. On 2008
DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681);
SET @y = REPLICATE(@y,92681);
SELECT LEN(@y)
Returns
8589767761
I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory
Running
select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid
Returned
internal_objects_alloc_page_co
------------------------------
2144456
so I presume this all just gets stored in LOB
pages in tempdb
with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681);
statement. The initial variable assignment to @y
and the LEN
calculation did not increase this.
The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE
method isn't supported for varchar(max) variables.
Addition
I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max)
and nvarchar(max) + varchar(max)
. Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
again. The script for that is below (may take a long time to run).
DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647);
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1) /*4294967294, 4294967292*/
DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823);
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2) /*2147483646, 4294967292*/
DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3) /*6442450940, 12884901880*/
/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test
Is your browser making calls to the server while it is starting? if yes, you probably should close it e.g. if your browser is currently set to http://localhost, close it before attempting to start the server.
The approach of @AzharShaikh works fine.
android:ellipsize="end"
android:maxLines="1"
But I realize a trouble that TextView will be truncated by word (in default). Show if we have a text like:
test long_line_without_any_space_abcdefgh
the TextView will display:
test...
And I found solution to handle this trouble, replace spaces with the unicode no-break space character, it makes TextView wrap on characters instead of words:
yourString.replace(" ", "\u00A0");
The result:
test long_line_without_any_space_abc...
This sort of is reading better:
if (a) {
return b || c;
}
else {
return b && c;
}
Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:
Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)
Type command git init
Type command git add --all
Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO
)
Type command git commit -m "my first commit"
Type command git push -u origin master
Note: if you get error unable to detect email or name, just type following commands after 5th step:
git config --global user.email "yourEmail" #your email at Bitbucket
git config --global user.name "yourName" #your name at Bitbucket
Alternatively to Link Library Dependencies
in project properties there is another way to link libraries in Visual Studio.
Add Existing Item...
).Item Type
is Library
This will include the other libraries in X as if you ran
lib /out:X.lib X.lib other1.lib other2.lib
According to the source code of codeigniter, the function set
is defined as:
public function set($key, $value = '', $escape = TRUE)
{
$key = $this->_object_to_array($key);
if ( ! is_array($key))
{
$key = array($key => $value);
}
foreach ($key as $k => $v)
{
if ($escape === FALSE)
{
$this->ar_set[$this->_protect_identifiers($k)] = $v;
}
else
{
$this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
}
}
return $this;
}
Apparently, if $key
is an array, codeigniter will simply ignore the second parameter $value
, but the third parameter $escape
will still work throughout the iteration of $key
, so in this situation, the following codes work (using the chain method):
$this->db->set(array(
'name' => $name ,
'email' => $email,
'time' => 'NOW()'), '', FALSE)->insert('mytable');
However, this will unescape all the data, so you can break your data into two parts:
$this->db->set(array(
'name' => $name ,
'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');
I think the best way is:
data: "{'Ids':['2','2']}"
To read this values Ids[0], Ids[1].
Not quite sure what you are asking, have you tried:
time yourscript | tail -n1 >log
Edit: ok, so you know how to get the times out and you just want to change the format. It would help if you described what format you want, but here are some things to try:
time -p script
This changes the output to one time per line in seconds with decimals. You only want the real time, not the other two so to get the number of seconds use:
time -p script | tail -n 3 | head -n 1
YourKit Java Profiler seems to handle them too.
I think you need something like:
var text= data.response.venue.tips.groups[0].items[1].text;
Try these:
adb kill-server
then adb start-server
Hope this helps.
If you're mutating your source object, ES6 can do it in one line.
delete Object.assign(o, {[newKey]: o[oldKey] })[oldKey];
Or two lines if you want to create a new object.
const newObject = {};
delete Object.assign(newObject, o, {[newKey]: o[oldKey] })[oldKey];
If useful, try this:
BufferedImage imgBuffer = ImageIO.read(new File("c:\\image.bmp"));
byte[] pixels = (byte[])imgBuffer.getRaster().getDataElements(0, 0, imgBuffer.getWidth(), imgBuffer.getHeight(), null);
This snippet is dependency injection friendly (I even use it in combination of ngmin and uglify) and it's a more elegant domain driven based solution.
The example below registers a Phone resource and a constant phoneRoutes, which contains all your routing information for that (phone) domain. Something I didn't like in the provided answer was the location of the resolve logic -- the main module should not know anything or be bothered about the way the resource arguments are provided to the controller. This way the logic stays in the same domain.
Note: if you're using ngmin (and if you're not: you should) you only have to write the resolve functions with the DI array convention.
angular.module('myApp').factory('Phone',function ($resource) {
return $resource('/api/phone/:id', {id: '@id'});
}).constant('phoneRoutes', {
'/phone': {
templateUrl: 'app/phone/index.tmpl.html',
controller: 'PhoneIndexController'
},
'/phone/create': {
templateUrl: 'app/phone/edit.tmpl.html',
controller: 'PhoneEditController',
resolve: {
phone: ['$route', 'Phone', function ($route, Phone) {
return new Phone();
}]
}
},
'/phone/edit/:id': {
templateUrl: 'app/phone/edit.tmpl.html',
controller: 'PhoneEditController',
resolve: {
form: ['$route', 'Phone', function ($route, Phone) {
return Phone.get({ id: $route.current.params.id }).$promise;
}]
}
}
});
The next piece is injecting the routing data when the module is in the configure state and applying it to the $routeProvider.
angular.module('myApp').config(function ($routeProvider,
phoneRoutes,
/* ... otherRoutes ... */) {
$routeProvider.when('/', { templateUrl: 'app/main/index.tmpl.html' });
// Loop through all paths provided by the injected route data.
angular.forEach(phoneRoutes, function(routeData, path) {
$routeProvider.when(path, routeData);
});
$routeProvider.otherwise({ redirectTo: '/' });
});
Testing the route configuration with this setup is also pretty easy:
describe('phoneRoutes', function() {
it('should match route configuration', function() {
module('myApp');
// Mock the Phone resource
function PhoneMock() {}
PhoneMock.get = function() { return {}; };
module(function($provide) {
$provide.value('Phone', FormMock);
});
inject(function($route, $location, $rootScope, phoneRoutes) {
angular.forEach(phoneRoutes, function (routeData, path) {
$location.path(path);
$rootScope.$digest();
expect($route.current.templateUrl).toBe(routeData.templateUrl);
expect($route.current.controller).toBe(routeData.controller);
});
});
});
});
You can see it in full glory in my latest (upcoming) experiment. Although this method works fine for me, I really wonder why the $injector isn't delaying construction of anything when it detects injection of anything that is a promise object; it would make things soooOOOOOooOOOOO much easier.
Edit: used Angular v1.2(rc2)
<hr>
is not from struts. It is just an HTML tag.
So, take a look here: http://www.microbion.co.uk/web/vertline.htm This link will give you a couple of tips.
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
In this case you need to go up to the <tr>
then use .next()
, like this:
$(obj).closest('tr').next().find('.class');
Or if there may be rows in-between without the .class
inside, you can use .nextAll()
, like this:
$(obj).closest('tr').nextAll(':has(.class):first').find('.class');
By assuming that predicate is a Boolean property of an element, that if it is true, then the element should be removed:
int i = 0;
while (i < list.Count())
{
if (list[i].predicate == true)
{
list.RemoveAt(i);
continue;
}
i++;
}
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
For an incoming request like /v1/location/1234
, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid
and not to deviceid
.
I think you should change your route template to be like
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
and then parse the deiveOrAppid
to figure out the type of id.
Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ?
character in this case.
For example:
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
if ( 0 < i && i < 100)
if ( 'a' <= c && c <= 'z' )
If you are using Ruby on Rails there is a squish
> @title = " abc "
=> " abc "
> @title.squish
=> "abc"
> @title
=> " abc "
> @title.squish!
=> "abc"
> @title
=> "abc"
If you are using just Ruby you want to use strip
Herein lies the gotcha.. in your case you want to use strip without the bang !
while strip! certainly does return nil if there was no action it still updates the variable so strip! cannot be used inline. If you want to use strip inline you can use the version without the bang !
strip! using multi line approach
> tokens["Title"] = " abc "
=> " abc "
> tokens["Title"].strip!
=> "abc"
> @title = tokens["Title"]
=> "abc"
strip single line approach... YOUR ANSWER
> tokens["Title"] = " abc "
=> " abc "
> @title = tokens["Title"].strip if tokens["Title"].present?
=> "abc"
I think it will be perfect solution:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Other views -->
<Space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<!-- Target view below -->
<View
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.
input_string = eval('b"' + sys.argv[1] + '"')
It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?
Looks like you want split
I'd float #content
too, that way both columns contain floats. Also because it will allow you to clear elements inside #content
without clearing the side bar.
Same thing with the wrapper, you'd need to make it a block formatting context to wrap the two columns.
This article mentions a few triggers you can use: block formatting contexts.
I just made a simple test to see how instanceOf performance is comparing to a simple s.equals() call to a string object with only one letter.
in a 10.000.000 loop the instanceOf gave me 63-96ms, and the string equals gave me 106-230ms
I used java jvm 6.
So in my simple test is faster to do a instanceOf instead of a one character string comparison.
using Integer's .equals() instead of string's gave me the same result, only when I used the == i was faster than instanceOf by 20ms (in a 10.000.000 loop)
You can do like this:
rename %CURR_DIR%\ftp\mywish1.txt text.txt
for /f %%a in (%CURR_DIR%\ftp\text.txt) do (
if "%%a" EQU "ex3" (
echo ex5 >> %CURR_DIR%\ftp\mywish1.txt
) else (
echo %%a >> %CURR_DIR%\ftp\mywish1.txt
)
)
del %CURR_DIR%\ftp\text.txt
just a convenient way of getting last n=5 containers (no matter running or not):
$ docker container ls -a -n5
NSNumber may be good for you in this case.
NSString *inStr = [NSString stringWithFormat:@"%d",
[NSNumber numberWithInteger:[month intValue]]];
var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();
From Programming Ruby 1.9
We’ll make a couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.
IPv4 uses 32 bits, in the form of:
255.255.255.255
I suppose it depends on your datatype, whether you're just storing as a string with a CHAR type or if you're using a numerical type.
IPv6 uses 128 bits. You won't have IPs longer than that unless you're including other information with them.
IPv6 is grouped into sets of 4 hex digits seperated by colons, like (from wikipedia):
2001:0db8:85a3:0000:0000:8a2e:0370:7334
You're safe storing it as a 39-character long string, should you wish to do that. There are other shorthand ways to write addresses as well though. Sets of zeros can be truncated to a single 0, or sets of zeroes can be hidden completely by a double colon.
I think you should go to:
File ->Project Structure->SDK Location->
there select your sdk location.
I am running a similar setup: Selenium 3.40, Chrome 61, chromedriver 2.33 running with xvfb on ubuntu 16.04.
I was getting the same Chrome error intermittently. It seems that sometimes, the chromedriver fails to cleanup the temp files associated with the Chrome profile.
A workaround for me is to cleanup the temp files before running tests:
rm -rf /tmp/.org.chromium.Chromium*
I expect this will be resolved in future versions of chromedriver, but for now this solves the problem in my case.
Here is an example
#!/bin/bash
default='default_value'
value=${1:-$default}
echo "value: [$value]"
save this as script.sh and make it executable. run it without params
./script.sh
> value: [default_value]
run it with param
./script.sh my_value
> value: [my_value]
In Ubuntu the file path is ./opt/lampp/var/mysql
This code can be used to execute an array of promises synchronously & sequentially after which you can execute your final code in the .then()
call.
const allTasks = [() => promise1, () => promise2, () => promise3];
function executePromisesSync(tasks) {
return tasks.reduce((task, nextTask) => task.then(nextTask), Promise.resolve());
}
executePromisesSync(allTasks).then(
result => console.log(result),
error => console.error(error)
);
You are using Python 2 for which the input()
function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError
exception.
To fix the problem, in Python 2, you can use raw_input()
. This returns the string entered by the user and does not attempt to evaluate it.
Note that if you were using Python 3, input()
behaves the same as raw_input()
does in Python 2.
This would run the 2 commands one after another:
alias lock='gnome-screensaver ; gnome-screensaver-command --lock'
On windows, I use a start.bat file like this:
java -Dhttp.port=9001 -DapplyEvolutions.default=true -cp "./lib/*;" play.core.server.NettyServer "."
The -DapplyEvolutions.default=true tells evolution to automatically apply evolutions without asking for confirmation. Use with caution on production environment, of course...
I got it resolved by doing Repir on .NET framework Extended, in Add/Remove program ;
Using win2008R2, .NET framework 4.0
I solved it by:
if(!response.isSuccessful()){
Gson gson = new Gson();
MyErrorMessage message=gson.fromJson(response.errorBody().charStream(),MyErrorMessage.class);
if(message.getCode()==ErrorCode.DUPLICATE_EMAIL_ID_CODE){
//DO Error Code specific handling
}else{
//DO GENERAL Error Code Specific handling
}
}
MyErrorMessage Class:
public class MyErrorMessage {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
You could use dplyr::mutate_if()
to convert all character columns or dplyr::mutate_at()
for select named character columns to factors:
library(dplyr)
# all character columns to factor:
df <- mutate_if(df, is.character, as.factor)
# select character columns 'char1', 'char2', etc. to factor:
df <- mutate_at(df, vars(char1, char2), as.factor)
the problem with datagridview is that it select the first row automatically so you want to clear the selection by
grvPackingList.ClearSelection();
dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;
other wise it will not work
An example of using logging.basicConfig
rather than logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
self.logger = logging.getLogger('urbanGUI')
In order, the five parts do the following:
filename=logname
)filemode='a'
)format=...
)datefmt='%H:%M:%S'
)level=logging.DEBUG
).CREATE PROCEDURE pr_emp(dept_id IN NUMBER,vv_ename out varchar2 )
AS
v_ename emp%rowtype;
CURSOR c_emp IS
SELECT ename
FROM emp where deptno=dept_id;
BEGIN
OPEN c;
loop
FETCH c_emp INTO v_ename;
return v_ename;
vv_ename := v_ename
exit when c_emp%notfound;
end loop;
CLOSE c_emp;
END pr_emp;
I would take those directions to mean:
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = { //note you don't use = in an object definition
"name": name,
"totalScore": totalScore,
"gamesPlayed": gamesPlayed
}
return obj;
}
You can use position:absolute;
to absolutely position an element within a parent div.
When using position:absolute;
the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.
To make the content div positioned, all position
values that aren't static will work, but relative
is the easiest since it doesn't change the divs positioning by itself.
So add position:relative;
to the content div, remove the float from the button and add the following css to the button:
position: absolute;
right: 0;
bottom: 0;
SELECT * FROM sys.dm_exec_sessions es
INNER JOIN sys.dm_exec_connections ec
ON es.session_id = ec.session_id
CROSS APPLY sys.dm_exec_sql_text(ec.most_recent_sql_handle) where es.session_id=65 under see text contain...
UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];
///// called event
-(IBAction)Back_btn:(id)sender
{
//Your code here
}
SWIFT:
var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)
var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true
var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton
func back_btn(_ sender: Any) {
//Your code here
}