lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]
msg = filter(lambda x : x != "8", lst)
print msg
EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.
Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.
To make this (kinda work?) with how the intent of the question was we could perform something similar to this
msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].
This would result in a data type that looks like this
msg = [["a", "a", "a", "a"], ["b", "b"]...]
So finally to wrap that up we would have to map it to bring them all back into the same type roughly
msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))
I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.
- mvn install
You can write code below in command line or if you're using eclipse builtin maven right click on project -> Run As -> run configurations... -> in left panel right click on Maven Build -> new configuration -> write the code in Goals & in base directory :${project_loc:NameOfYourProject} -> Run
mvn install:install-file
-Dfile=<path-to-file>
-DgroupId=<group-id>
-DartifactId=<artifact-id>
-Dversion=<version>
-Dpackaging=<packaging>
-DgeneratePom=true
Where each refers to:
< path-to-file >: the path to the file to load e.g -> c:\kaptcha-2.3.jar
< group-id >: the group that the file should be registered under e.g -> com.google.code
< artifact-id >: the artifact name for the file e.g -> kaptcha
< version >: the version of the file e.g -> 2.3
< packaging >: the packaging of the file e.g. -> jar
2.After installed, just declares jar in pom.xml.
<dependency>
<groupId>com.google.code</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3</version>
</dependency>
Example:
redis 127.0.0.1:6379> AUTH PASSWORD
(error) ERR Client sent AUTH, but no password is set
redis 127.0.0.1:6379> CONFIG SET requirepass "mypass"
OK
redis 127.0.0.1:6379> AUTH mypass
Ok
In 2018:
<input type="number" pattern="\d*">
is working for both Android and iOS.
I tested on Android (^4.2) and iOS (11.3)
"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"
There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.
In addition to the accepted answer, if you have multiple instances of the activity, you can use a counter instead:
class MyActivity extends Activity {
static int activeInstances = 0;
static boolean isActive() {
return (activeInstance > 0)
}
@Override
public void onStart() {
super.onStart();
activeInstances++;
}
@Override
public void onStop() {
super.onStop();
activeInstances--;
}
}
It seems, fileinput.FileInput is a generator. As such, you can only iterate over it once, then all items have been consumed and calling it's next method raises StopIteration. If you want to iterate over the lines more than once, you can put them in a list:
list(fileinput.FileInput('test.txt'))
Then call rstrip on them.
For Empty row how we can insert values on where clause
Try this
UPDATE table_name SET username="",password="" WHERE id =""
Let me show approch without JQuery. Simple JS function:
function isVisible(elem) {
var coords = elem.getBoundingClientRect();
var topVisible = coords.top > 0 && coords.top < 0;
var bottomVisible = coords.bottom < shift && coords.bottom > 0;
return topVisible || bottomVisible;
}
Short example how to use it:
var img = document.getElementById("pic1");
if (isVisible(img)) { img.style.opacity = "1.00"; }
I would prefer:
try
{
...
}
catch (FooException fe){
throw fe;
}
catch (Exception e)
{
// Note: don't catch all exceptions like this unless you know what you
// are doing.
...
}
have you tried line-height:1em;? I recall that that's the way to get it to center vertically.
In general it is safer to work on copies than on original data frames, except when you know that you won't be needing the original anymore and want to proceed with the manipulated version. Normally, you would still have some use for the original data frame to compare with the manipulated version, etc. Therefore, most people work on copies and merge at the end.
Some days I faced the same problem. Reason was different sizes arrays.
I needed to replace the \r\n
with an actual carriage return and line feed and replace \t
with an actual tab. So I came up with the following:
public string Transform(string data)
{
string result = data;
char cr = (char)13;
char lf = (char)10;
char tab = (char)9;
result = result.Replace("\\r", cr.ToString());
result = result.Replace("\\n", lf.ToString());
result = result.Replace("\\t", tab.ToString());
return result;
}
Note that -p
is an argument to the mkdir
command specifically, not the whole of Unix. Every command can have whatever arguments it needs.
In this case it means "parents", meaning mkdir
will create a directory and any parents that don't already exist.
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
As I learned, no one of those several solutions are perfects. Using a favicon generator is indeed a good solution but their number is overwhelming and it's hard to choose. I d'like to add that if you want your website to be PWA enabled, you need to provide also a 512x512 icon as stated by Google Devs :
icons including a 192px and a 512px version
I didn't met a lot of favicon generators enforcing that criteria (firebase does, but there is a lot of things it doesn't do). So the solution must be a mix of many other solutions.
I don't know, today at the begining of 2020 if providing a 16x16, 32x32 still relevant. I guess it still matters in certain context like, for example, if your users still use IE for some reason (this stills happen in some privates companies which doesn't migrate to a newer browser for some reasons)
You can have a pair of extension methods to make this task easier:
public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
return lst.ToDelimitedString(p => p, separator);
}
public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector,
string separator = ", ")
{
return string.Join(separator, lst.Select(selector));
}
So now just:
new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
This is how you make Android Google Maps API v2 work on your emulator.
Create a new emulator
these are the settings that are working for me. I don't know for different ones.
Start the emulator
install com.android.vending-1.apk and com.google.android.gms-1.apk via ADB install command
The longer answer is on my blog post about this issue https://medium.com/nemanja-kovacevic/how-to-make-android-google-maps-v2-work-in-android-emulator-e384f5423723
Solve problem with two method parse common
public <T> T jsonToObject(String json, Class<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (Jsenter code hereonProcessingException e) {
e.printStackTrace();
}
return target;
}
public <T> T jsonToObject(String json, TypeReference<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return target;
}
Examples using curl
Send messages to specific devices
To send messages to specific devices, set the to the registration token for the specific app instance
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send
Send messages to topics
here the topic is : /topics/foo-bar
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send
Send messages to device groups
Sending messages to a device group is very similar to sending messages to an individual device. Set the to parameter to the unique notification key for the device group
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send
Examples using Service API
API URL : https://fcm.googleapis.com/fcm/send
Headers
Content-type: application/json
Authorization:key=<Your Api key>
Request Method : POST
Request Body
Messages to specific devices
{
"data": {
"score": "5x1",
"time": "15:10"
},
"to": "<registration token>"
}
Messages to topics
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!"
}
}
Messages to device groups
{
"to": "<aUniqueKey>",
"data": {
"hello": "This is a Firebase Cloud Messaging Device Group Message!"
}
}
Adding /
after /preference
solved the problem for me:
@Test
public void circularViewPathIssue() throws Exception {
mockMvc.perform(get("/preference/"))
.andDo(print());
}
Strictly speaking; With no Java EE features your app hardly need an appserver at all ;-)
Like others have pointed out JBoss has a (more or less) full Java EE stack while Tomcat is a webcontainer only. JBoss can be configured to only serve as a webcontainer as well, it'd then just be a thin wrapper around the included tomcat webcontainer. That way you could have an almost as lightweight JBoss, which would actually just be a thin "wrapper" around Tomcat. That would be almost as lightweigth.
If you won't need any of the extras JBoss has to offer, go for the one you're most comfortable with. Which is easiest to configure and maintain for you?
Some times semiColon makes matter please ensure
JAVA_HOME=c:\Program Files\Java\jdk1.6.0_32
but not
JAVA_HOME=c:\Program Files\Java\jdk1.6.0_32;
Same problem i got but not solved
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
One thing I've used with good results is the following (I don't know if its mentioned already because I can't remember its name).
You precompute a table T with a random number for each character in your key's alphabet [0,255]. You hash your key 'k0 k1 k2 ... kN' by taking T[k0] xor T[k1] xor ... xor T[kN]. You can easily show that this is as random as your random number generator and its computationally very feasible and if you really run into a very bad instance with lots of collisions you can just repeat the whole thing using a fresh batch of random numbers.
NameValueCollection n = Request.QueryString;
if (n.HasKeys())
{
//something
}
Return Value Type: System.Boolean true if the NameValueCollection contains keys that are not null; otherwise, false. LINK
I too faced the same problem in Angular 6. I solved the issue by using below code. Add the code in component.ts file.
import { HttpHeaders } from '@angular/common/http';
headers;
constructor() {
this.headers = new HttpHeaders();
this.headers.append('Access-Control-Allow-Headers', 'Authorization');
}
getData() {
this.http.get(url,this.headers). subscribe (res => {
// your code here...
})}
For me / had to be in a new line.
For example
create type emp_t;/
didn't work
but
create type emp_t;
/
worked.
I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:
* commit I want to cherry-pick (x)
|\
| * branch I want to cherry-pick to (y)
* |
|/
* common parent (x)
I understand now that I want to do
git cherry-pick -m 2 mycommitsha
This is because -m 1
would merge based on the common parent where as -m 2
merges based on branch y, that is the one I want to cherry-pick to.
You can use in this manner also
var rowId =$("#list").jqGrid('getGridParam','selrow');
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId']; // perticuler Column name of jqgrid that you want to access
The following function shows why and is capable for working out the difference:
function test() {
var myObj = {};
console.log(myObj.myProperty);
myObj.myProperty = null;
console.log(myObj.myProperty);
}
If you call
test();
You're getting
undefined
null
The first console.log(...)
tries to get myProperty
from myObj
while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...)
returns obviously "null" because myProperty
exists, but it has the value null
assigned to it.
In order to be able to query this difference, JavaScript has null
and undefined
: While null
is - just like in other languages an object, undefined
cannot be an object because there is no instance (even not a null
instance) available.
It's a "precompiled header file" -- any headers you include in stdafx.h are pre-processed to save time during subsequent compilations. You can read more about it here on MSDN.
If you're building a cross-platform application, check "Empty project" when creating your project and Visual Studio won't put any files at all in your project.
Adding the actual quote characters is only a tiny fraction of the problem; once you have done that, you are likely to face the real problem: what happens if the string already contains quotes, or line feeds, or other unprintable characters?
The following method will take care of everything:
public static String escapeForJava( String value, boolean quote )
{
StringBuilder builder = new StringBuilder();
if( quote )
builder.append( "\"" );
for( char c : value.toCharArray() )
{
if( c == '\'' )
builder.append( "\\'" );
else if ( c == '\"' )
builder.append( "\\\"" );
else if( c == '\r' )
builder.append( "\\r" );
else if( c == '\n' )
builder.append( "\\n" );
else if( c == '\t' )
builder.append( "\\t" );
else if( c < 32 || c >= 127 )
builder.append( String.format( "\\u%04x", (int)c ) );
else
builder.append( c );
}
if( quote )
builder.append( "\"" );
return builder.toString();
}
The correct syntax is mysql> SET @@global.group_concat_max_len = integer;
If you do not have the privileges to do this on the server where your database resides then use a query like:
mySQL="SET @@session.group_concat_max_len = 10000;"
or a different value.
Next line:
SET objRS = objConn.Execute(mySQL)
your variables may be different.
then
mySQL="SELECT GROUP_CONCAT(......);"
etc
I use the last version since I do not have the privileges to change the default value of 1024 globally (using cPanel).
Hope this helps.
In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":
find / -name index.html -print
Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:
/var/www/*
Or type:
find /var/www -name index.html -print
For future visitors - use this for range: ($A$1:$A$10)
Example
=COUNTIF($G$6:$G$9;J6)>0
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
Sort of. Using phpMyAdmin I just deleted one row too many. But I caught it before I proceeded and had most of the data from the delete confirmation message. I was able to rebuild the record. But the confirmation message truncated some of a text comment.
Someone more knowledgeable than I regarding phpMyAdmin may know of a setting so that you can get a more complete echo of the delete confirmation message. With a complete delete message available, if you slow down and catch your error, you can restore the whole record.
(PS This app also sends an email of the submission that creates the record. If the client has a copy, I will be able to restore the record completely)
You can do a P/Invoke to MoveFileEx()
- pass 11 for flags
(MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH
)
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern bool MoveFileEx(string existingFileName, string newFileName, int flags);
Or, you can just call
Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(existingFileName, newFileName, true);
after adding Microsoft.VisualBasic as a reference.
On Windows I kept facing different errors messages when trying to use pg_upgrade
.
Saved a lot of time for me to just:
if you have array that looks like this -
data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]
and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -
data_hash = Hash[data.map { |key| [key.shift, key] }]
#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}
I tried most of the answers and unfortunately, none of them worked in completion.
Here is what worked for me. There are 3 things to do to the site you want PUT for (select the site) :
Open WebDav Authoring Rules
and then select Disable WebDAV
option present on the right bar.
Select Modules
, find the WebDAV Module
and remove it.
Select HandlerMapping
, find the WebDAVHandler
and remove it.
Restart IIS.
You should put the parameter gravity to bottom not in the textview but in the Linear Layout. Like this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Something"/>
</LinearLayout>
Since PHP/5.4.0, there is an option called JSON_UNESCAPED_UNICODE
. Check it out:
https://php.net/function.json-encode
Therefore you should try:
json_encode( $text, JSON_UNESCAPED_UNICODE );
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Or, for Python 2 only:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as
.
From laravel 5.2
and onward. you can use DB::listen
to get executed queries.
DB::listen(function ($query) {
// $query->sql
// $query->bindings
// $query->time
});
Or if you want to debug a single Builder
instance then you can use toSql
method.
DB::table('posts')->toSql();
Just using a class to only hide some...based on https://stackoverflow.com/a/17541916/1815624
/* HIDE RADIO */_x000D_
.hiddenradio [type=radio] { _x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
width: 0;_x000D_
height: 0;_x000D_
}_x000D_
_x000D_
/* IMAGE STYLES */_x000D_
.hiddenradio [type=radio] + img {_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
/* CHECKED STYLES */_x000D_
.hiddenradio [type=radio]:checked + img {_x000D_
outline: 2px solid #f00;_x000D_
}
_x000D_
<div class="hiddenradio">_x000D_
<label>_x000D_
<input type="radio" name="test" value="small" checked>_x000D_
<img src="http://placehold.it/40x60/0bf/fff&text=A">_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
<input type="radio" name="test" value="big">_x000D_
<img src="http://placehold.it/40x60/b0f/fff&text=B">_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<div class="">_x000D_
<label>_x000D_
<input type="radio" name="test" value="small" checked>_x000D_
<img src="http://placehold.it/40x60/0bf/fff&text=A">_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
<input type="radio" name="test" value="big">_x000D_
<img src="http://placehold.it/40x60/b0f/fff&text=B">_x000D_
</label>_x000D_
</div>
_x000D_
Verify that you have the latest version of Node installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:
Option 1
In the nearest parent package.json
file, add the top-level "type"
field with a value of "module"
. This will ensure that all .js
and .mjs
files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs
extension.
// package.json
{
"type": "module"
}
Option 2
Explicitly name files with the .mjs
extension. All other files, such as .js
will be interpreted as CommonJS, which is the default if type
is not defined in package.json
.
A grep-less solution, works for me:
MY_LIST=$( cat /path/to/my_list.txt )
if [[ "${MY_LIST}" == *"${NEW_DIRECTORY_NAME}"* ]]; then
echo "It's there!"
else
echo "its not there"
fi
I use CTRL-SHIFT-DELETE which activates the privacy feature, allowing you to clear your cache, reset cookies, etc, all at once. You can even configure it so that it just DOES it, instead of popping up a dialog box asking you to confirm.
After way too much research, trial and error I found a way that seems to works fine and doesn't require to manually re-set the font size manually on the children elements, allowing me to have a standardized em font size across the whole doc.
In Firefox this is fairly simple, just set word-spacing: -1em
on the parent element. For some reason, Chrome ignore this (and as far as I tested, it ignores the word spacing regardless of the value). So besides this I add letter-spacing: -.31em
to the parent and letter-spacing: normal
to the children. This fraction of an em is the size of the space ONLY IF your em size is standardized. Firefox, in turn, ignores negative values for letter-spacing, so it won't add it to the word spacing.
I tested this on Firefox 13 (win/ubuntu, 14 on android), Google Chrome 20 (win/ubuntu), Android Browser on ICS 4.0.4 and IE 9. And I'm tempted to say this may also work on Safari, but I don't really know...
Here's a demo http://jsbin.com/acucam
In my case it was just caused because there was not enough space on the disk for cvtres.exe
to write the files it had to.
The error was preceded by this line
CVTRES : fatal error CVT1106: cannot write to file
Remember that a single =
is always an assignment in C or C++.
Your test should be if ( match == 0 && k == M )
you made a typo on the k == M
test.
If you really mean k=M
(i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0)
but most coding rules advise not writing that.
BTW, your mistake suggests to ask for all warnings (e.g. -Wall
option to g++
), and to upgrade to recent compilers. The next GCC 4.8 will give you:
% g++-trunk -Wall -c ederman.cc
ederman.cc: In function ‘void foo()’:
ederman.cc:9:30: error: lvalue required as left operand of assignment
if ( match == 0 && k = M )
^
and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable
So use recent versions of free compilers and enable all the warnings when using them.
Strings, though they are not set
types, have a valuable in
property during validation in scripts:
yn = input("Are you sure you want to do this? ")
if yn in "yes":
#accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
return True
return False
I hope this helps you better understand the use of in
with this example.
Also it might be useful for those who are doing this by coding. You need to add WebHttpBehavior() to your added service endpoint. Something like:
restHost.AddServiceEndpoint(typeof(IRestInterface), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
Take a look at : https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/calling-a-rest-style-service-from-a-wcf-service
Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.
Javascript code embedded aswell:
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
});
You'll want to use either JavaScript or a server-side language like PHP, ASP...etc
(supposedly can be done with HTML <embed>
tag, which makes sense, but I haven't used, since PHP...etc is so simple/common)
Javascript can work: Here's a link to someone doing something similar via javascript on stackoverflow: How do I load the contents of a text file into a javascript variable?
PHP (as example of server-side language) is the easiest way to go though:
<div><p><?php include('myFile.txt'); ?></p></div>
To use this (if you're unfamiliar with PHP), you can:
1) check if you have php on your server
2) change the file extension of your .html file to .php
3) paste the code from my PHP example somewhere in the body of your newly-renamed PHP file
I'd consider also Apache Thrift http://thrift.apache.org/
It can bridge between several programming languages, is highly efficient and has support for async or sync calls. See full features here http://thrift.apache.org/docs/features/
The multi language can be useful for future plans, for example if you later want to do part of the computational task in C++ it's very easy to do add it to the mix using Thrift.
I have noticed that if utilised progrmmatically it renders incomplete (entire form simply doesn't "paint" anything) if used before panel1.Controls.Add(dataGridView);
then dataGridView.Columns["ID"].Visible = false;
will break the entire form and make it blank, so to get round that set this AFTER EG:
panel1.Controls.Add(dataGridView);
dataGridView.Columns["ID"].Visible = false;
//works
dataGridView.Columns["ID"].Visible = false;
panel1.Controls.Add(dataGridView);
//fails miserably
private void txt3_KeyPress(object sender, KeyPressEventArgs e)
{
for (int h = 58; h <= 127; h++)
{
if (e.KeyChar == h) //58 to 127 is alphabets tat will be blocked
{
e.Handled = true;
}
}
for(int k=32;k<=47;k++)
{
if (e.KeyChar == k) //32 to 47 are special characters tat will
{ be blocked
e.Handled = true;
}
}
}
try this is very simple
A lot of answers have been given, but id like to add to them.
If you need the week to display as a year/week style (ex. 1953 - week 53 of 2019, 2001 - week 1 of 2020 etc.), you can do this:
import datetime
year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)
It will take the current year and week, and long_week_num in the day of writing this will be:
>>> 2006
I think you can try to load that csv into a RDD and then create a dataframe from that RDD, here is the document of creating dataframe from rdd:http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds
Just in case it helps someone:
If the method GetDataThatLooksVerySimilarButNotTheSame()
returns an ExpandoObject
you can also cast to a IDictionary
before checking.
dynamic test = new System.Dynamic.ExpandoObject();
test.foo = "bar";
if (((IDictionary<string, object>)test).ContainsKey("foo"))
{
Console.WriteLine(test.foo);
}
Use this:
\d{10}
I hope it helps.
defaults write org.R-project.R force.LANG en_US.UTF-8
For someone runs R in a docker environment (under root), try to run R with below command,
LC_ALL=C.UTF-8 R
# instead of just `R`
A pertinent quote from PEP 465 - A dedicated infix operator for matrix multiplication , as mentioned by @petr-viktorin, clarifies the problem the OP was getting at:
[...] numpy provides two different types with different
__mul__
methods. Fornumpy.ndarray
objects,*
performs elementwise multiplication, and matrix multiplication must use a function call (numpy.dot
). Fornumpy.matrix
objects,*
performs matrix multiplication, and elementwise multiplication requires function syntax. Writing code usingnumpy.ndarray
works fine. Writing code usingnumpy.matrix
also works fine. But trouble begins as soon as we try to integrate these two pieces of code together. Code that expects anndarray
and gets amatrix
, or vice-versa, may crash or return incorrect results
The introduction of the @
infix operator should help to unify and simplify python matrix code.
For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window.
I have not used Selenium 2. Selenium 1.x has selenium.getTable("tablename".columnNumber.rowNumber)
to reach the required cell. May be you can use webdriverbackedselenium
and do this.
And you can get the total rows and columns by using
int numOfRows = selenium.getXpathCount("//table[@id='tableid']//tr")
int numOfCols=selenium.getXpathCount("//table[@id='tableid']//tr//td")
$("a.save, #country")
will select both "a.save" class and "country" id.
Assuming you are dealing with a JSON-string in the input, you can parse it using the json
package, see the documentation.
In the specific example you posted you would need
x = json.loads("""{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
For anyone using the Node.js driver instead of Mongoose, you'll want to use {returnOriginal:false}
instead of {new:true}
.
You sure can do this!
//make a regular expression out of your needle
var needle = 'le'
var re = new RegExp(needle,'gi');
var haystack = 'I learned to play the Ukulele';
var results = new Array();//this is the results you want
while (re.exec(haystack)){
results.push(re.lastIndex);
}
Edit: learn to spell RegExp
Also, I realized this isn't exactly what you want, as lastIndex
tells us the end of the needle not the beginning, but it's close - you could push re.lastIndex-needle.length
into the results array...
Edit: adding link
@Tim Down's answer uses the results object from RegExp.exec(), and all my Javascript resources gloss over its use (apart from giving you the matched string). So when he uses result.index
, that's some sort of unnamed Match Object. In the MDC description of exec, they actually describe this object in decent detail.
For Eclipse: menu bar-> window -> show view then find "debug" option if not in list then select other ...
new window will open and then search using keyword "debug" -> select debug from list
it will added near console tab. use debug tab to terminate and remove previous executions. ( right clicking on executing process will show you many option including terminate)
One of #a
or #b
needs to be not position:absolute
, so that #box
will grow to accommodate it.
So you can stop #a
from being position:absolute
, and still position #b
over the top of it, like this:
#box {_x000D_
background-color: #000;_x000D_
position: relative; _x000D_
padding: 10px;_x000D_
width: 220px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
width: 210px;_x000D_
background-color: #fff;_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
width: 100px; /* So you can see the other one */_x000D_
position: absolute;_x000D_
top: 10px; left: 10px;_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
#after {_x000D_
background-color: yellow;_x000D_
padding: 10px;_x000D_
width: 220px;_x000D_
}
_x000D_
<div id="box">_x000D_
<div class="a">Lorem</div>_x000D_
<div class="b">Lorem</div>_x000D_
</div>_x000D_
<div id="after">Hello world</div>
_x000D_
(Note that I've made the widths different, so you can see one behind the other.)
Edit after Justine's comment: Then your only option is to specify the height of #box. This:
#box {
/* ... */
height: 30px;
}
works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
before that works properly.
You can use the .complete property of the Javascript image class.
I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:
var gAllImages = [];
function makeThumbDivs(thumbnailsBegin, thumbnailsEnd)
{
gAllImages = [];
for (var i = thumbnailsBegin; i < thumbnailsEnd; i++)
{
var theImage = new Image();
theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]);
gAllImages.push(theImage);
setTimeout('checkForAllImagesLoaded()', 5);
window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd;
// make a new div containing that image
makeASingleThumbDiv(globals.gAllPageGUIDs[i]);
}
}
function checkForAllImagesLoaded()
{
for (var i = 0; i < gAllImages.length; i++) {
if (!gAllImages[i].complete) {
var percentage = i * 100.0 / (gAllImages.length);
percentage = percentage.toFixed(0).toString() + ' %';
userMessagesController.setMessage("loading... " + percentage);
setTimeout('checkForAllImagesLoaded()', 20);
return;
}
}
userMessagesController.setMessage(globals.defaultTitle);
}
You should use jwt.verify it will check if the token is expired. jwt.decode should not be used if the source is not trusted as it doesn't check if the token is valid.
You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)
$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
//Process your response
$("#ajaxLoader").hide();
});
If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-
$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
Using blockUI is similar for example with mark up like:-
<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
<p id="result"></p>
</div>
<div id="ajaxLoader" style="display:none">
<h2>Please wait</h2>
<p>I'm getting my AJAX on!</p>
</div>
And using jQuery:-
$(function() {
$("#jsonLink").click(function(e) {
$.post(this.href, function(result) {
$("#resultContainer").fadeIn();
$("#result").text(result.Answer);
}, "json");
return false;
});
$("#ajaxLoader").ajaxStart(function() {
$.blockUI({ message: $("#ajaxLoader") });
})
.ajaxStop(function() {
$.unblockUI();
});
});
In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.
You can always use an alias:
alias next='printf "blah_%02d" $count;count=$((count+1))'
It looks like you forgot to include the ngRoute module in your dependency for myApp.
In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
To check file exists or not you can use
System.IO.File.Exists(path)
The lazy way: simply uninstall from the Windows installation menu (if you're using Windows), or from the rpm command, provided you first re-install it after creating a distribution package.
For example,
python setup.py bdist_wininst
dist/foo-1.0.win32.exe
("foo" being an example of course).
Run ./mnistCUDNN
in /usr/src/cudnn_samples_v7/mnistCUDNN
Here is an example:
cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30 Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0, boardGroupID=0
Using device 0
In this case i would use the ECMAscript 5 Array.filter. The following solution requires array.filter() that doesn't exist in all versions of IE.
Shims can be found here: MDN Array.filter or ES5-shim
var result = restaurants.filter(function (chain) {
return chain.restaurant.food === "chicken";
})[0].restaurant.name;
So I have been lurking on stack for so many years. This is actually my first time posting on here.
Anyhow, this might seem insane but I came across this post while struggling with the same issue and came up with a dirty solution. I know there are more elegant ways to perhaps set this as a property value but:
if you look at lines 12880-12883 in tcpdf.php :
$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`110`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`110`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`111`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
and lines 13135-13138 :
$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`108`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`108`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`109`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
Those widgets are rendered from the zapfdingbats font set... just swap the character codes and voila... checks are radios and/or vice versa. This also opens up ideas to make a custom font set to use here and add some nice styling to your form elements.
Anyhow, just figured I would offer my two cents ... it worked awesome for me.
public class ConsecutiveNumberPrint {
private static class NumberGenerator {
public int MAX = 100;
private volatile boolean evenNumberPrinted = true;
public NumberGenerator(int max) {
this.MAX = max;
}
public void printEvenNumber(int i) throws InterruptedException {
synchronized (this) {
if (evenNumberPrinted) {
wait();
}
System.out.println("e = \t" + i);
evenNumberPrinted = !evenNumberPrinted;
notify();
}
}
public void printOddNumber(int i) throws InterruptedException {
synchronized (this) {
if (!evenNumberPrinted) {
wait();
}
System.out.println("o = \t" + i);
evenNumberPrinted = !evenNumberPrinted;
notify();
}
}
}
private static class EvenNumberGenerator implements Runnable {
private NumberGenerator numberGenerator;
public EvenNumberGenerator(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}
@Override
public void run() {
for(int i = 2; i <= numberGenerator.MAX; i+=2)
try {
numberGenerator.printEvenNumber(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class OddNumberGenerator implements Runnable {
private NumberGenerator numberGenerator;
public OddNumberGenerator(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}
@Override
public void run() {
for(int i = 1; i <= numberGenerator.MAX; i+=2) {
try {
numberGenerator.printOddNumber(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
NumberGenerator numberGenerator = new NumberGenerator(100);
EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(numberGenerator);
OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(numberGenerator);
new Thread(oddNumberGenerator).start();
new Thread(evenNumberGenerator).start();
}
}
See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.
The config portion looks like this:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {controller:'ListCtrl', templateUrl:'list.html'})
.otherwise({redirectTo:'/'});
}])
The point of entry for injecting the partial view into your main template is:
<div class="container" ng-view=""></div>
If none of the above work, I also have a different approach, as it happened to me in a real scenario.
More specifically using auto-generated Ruby files from Thrift.
In my situation, I had a Module
with several classes, so the order is important in this case:
Class A
makes use of Class B
in the same module. However, Class B
was declared after Class A
.
Simply making Class B
to be declared before Class A
solved the issue to me.
Found a way with two (2) easy codes here. First do a mysqldump:
mysqldump -uUSERNAME -p DATABASE_NAME > database-dump.sql
then grep the sqldump file:
grep -i "Search string" database-dump.sql
It possible also to find/replace and re-import back to the database.
You can, the question in my mind is more should you. Right from the beginning, I'll say that there is no hard and fast answer. Do the right thing for your current situation.
To me inheritance implies an 'is-a' relationship. Imagine a dog class, which can be extended by more specialized sub types (Alsatian, Poodle, etc). In this case making the dog class abstract may be the right thing to do since sub-types are dogs. Now let's imagine that dogs need a collar. In this case inheritance doesn't make sense: it's nonsense to have a 'is-a' relationship between dogs and collars. This is definitely a 'has-a' relationship, collar is a collaborating object. Making collar abstract just so that dogs can have one doesn't make sense.
I often find that abstract classes with no abstract methods are really expressing a 'has-a' relationship. In these cases I usually find that the code can be better factored without using inheritance. I also find that abstract classes with no abstract method are often a code smell and at the very least should lead to questions being raised in a code review.
Again, this is entirely subjective. There may well be situations when an abstract class with no abstract methods makes sense, it's entirely up to interpretation and justification. Make the best decision for whatever you're working on.
In windows server 2012 or 2016 you can search for Windows PowerShell and then "Pin to Start". After this you will see "Run as different user" option on a right click on the start page tiles.
ALT+SHIFT+F10, Right, E, Enter, Tab, enter your command line parameters, Enter. ;-)
CTRL+ALT+R, Right, E, Enter, Tab, enter your command line parameters, Enter.
<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
<input id="fileupload" name="myfile" type="file" />
<input type="submit" value="submit" id="submit" />
</form>
To upload a file, it is essential to set enctype="multipart/form-data"
on your form
You need that form type and then some php to process the file :)
You should probably check out Uploadify if you want something very customisable out of the box.
I like the answer given here:
http://stupidpythonideas.blogspot.com/2013/08/defaultdict-vs-setdefault.html
In short, the decision (in non-performance-critical apps) should be made on the basis of how you want to handle lookup of empty keys downstream (viz. KeyError
versus default value).
I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)
There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):
The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.
API is really nice and easy to learn. Example how to capture single image and save it to PNG file:
Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
Here's another option that seems to work for me. In the viewForFooter delegate method check if it's the final section and add your code there. This approach came to mind after realizing that willDisplayCell doesn't account for footers if you have them.
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
// Perform some final layout updates
if (section == ([tableView numberOfSections] - 1)) {
[self tableViewWillFinishLoading:tableView];
}
// Return nil, or whatever view you were going to return for the footer
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
// Return 0, or the height for your footer view
return 0.0;
}
- (void)tableViewWillFinishLoading:(UITableView *)tableView
{
NSLog(@"finished loading");
}
I find this approach works best if you are looking to find the end loading for the entire UITableView
, and not simply the visible cells. Depending on your needs you may only want the visible cells, in which case folex's answer is a good route.
var model = JSON.stringify({
'ID': 0,
'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
'VendorID': $('#Vendors').val()
})
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PartSourceAPI/",
data: model,
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
var model = JSON.stringify({ 'ID': 0, ...': 5, 'PartNumber': 6, 'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"
your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model
Having is only used with aggregation but where with non aggregation statements If you have where word put it before aggregation (group by)
This worked for me. It also prints the output returned by the child process
child = subprocess.Popen(serial_script_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
retValRunJobsSerialScript = 0
for line in child.stdout.readlines():
child.wait()
print line
retValRunJobsSerialScript= child.returncode
I think using the matrix.at<type>(x,y)
is not the best way to iterate trough a Mat object!
If I recall correctly matrix.at<type>(x,y)
will iterate from the beginning of the matrix each time you call it(I might be wrong though).
I would suggest using cv::MatIterator_
cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
std::cout << *_it << std::endl;
}
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break
. That will do it.
The accepted answer of this question has some issue with chrome when the window is zoomed in to a value >100%. Here is the code recommended by chrome developers as part of a bug i had raised on the same.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()){
//Your code here
}
});
For reference:
I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery
jQuery('a[target^="_new"]').click(function() {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
it will open all the <a target="_new">
in a new window
EDIT:
1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)
but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):
jQuery('a[target^="_new"]').click(function() {
return openWindow(this.href);
}
function openWindow(url) {
if (window.innerWidth <= 640) {
// if width is smaller then 640px, create a temporary a elm that will open the link in new tab
var a = document.createElement('a');
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}
else {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
return false;
}
This didnt work for me:
pip install mysqlclient
so i found this after a while on stackoverflow:
pip install --only-binary :all: mysqlclient
and it went all through, no need for MS Visual C++ 14 Build tools and stuff
Note: for now this doesnt work with Python3.7, i also had to downgrade to Python 3.6.5
Maybe adding the commands to executable file, setting +x permission and then executing?
ps aux | grep -ie amarok | awk '{print "kill -9 " $2}' > pk;chmod +x pk;./pk;rm pk
using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("[email protected]");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("[email protected]");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
You may use the above code.
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
Yes, there is a threading pool similar to the multiprocessing Pool, however, it is hidden somewhat and not properly documented. You can import it by following way:-
from multiprocessing.pool import ThreadPool
Just I show you simple example
def test_multithread_stringio_read_csv(self):
# see gh-11786
max_row_range = 10000
num_files = 100
bytes_to_df = [
'\n'.join(
['%d,%d,%d' % (i, i, i) for i in range(max_row_range)]
).encode() for j in range(num_files)]
files = [BytesIO(b) for b in bytes_to_df]
# read all files in many threads
pool = ThreadPool(8)
results = pool.map(self.read_csv, files)
first_result = results[0]
for result in results:
tm.assert_frame_equal(first_result, result)
#if defined(__OBJC__)
#define __bool BOOL
#include <stdbool.h>
#define __bool bool
#endif
static inline __bool xor(__bool a, __bool b)
{
return (!a && b) || (a && !b);
}
It works as defined. The conditionals are to detect if you are using Objective-C, which is asking for BOOL instead of bool (the length is different!)
I don't have an Ubuntu box, but on Red Hat Linux you can see all running services by running the following command:
service --status-all
On the list the +
indicates the service is running, -
indicates service is not running, ?
indicates the service state cannot be determined.
If you just for in
a object without if statement hasOwnProperty
then you will get error from linter like:
for (const key in myobj) {
console.log(key);
}
WARNING in component.ts
for (... in ...) statements must be filtered with an if statement
So the solutions is use Object.keys
and of
instead.
for (const key of Object.keys(myobj)) {
console.log(key);
}
Hope this helper some one using a linter.
All of the answers above may work for the time being but whenever you run maven on the command line or Maven → Update project… the JDK will be reset, this was also the question as I understand it.
To fix this for good add the following code to your pom file. Remember to do a Maven → Update project… afterwards or mvn clean compile
at the command line.
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
Something like this will do the trick. Don't know about performance, so do make some tests.
select
id, name, city
from
[stuff] s
where
1 < (select count(*) from [stuff] i where i.city = s.city and i.name = s.name)
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
You can get current href value by this code:
$(this).attr("href");
To get href value by ID
$("#mylink").attr("href");
c
can be used on lists (and not only on vectors):
# you have
l1 = list(2, 3)
l2 = list(4)
# you want
list(2, 3, 4)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
# you can do
c(l1, l2)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
If you have a list of lists, you can do it (perhaps) more comfortably with do.call
, eg:
do.call(c, list(l1, l2))
I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.
I tried changing year
to a different term, and it worked.
public_methods : {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue > this.originYear) {
this._year = newValue;
this.edition += newValue - this.originYear;
}
}
}
It's better, if you use two div containers in HTML .
As Shown Below:
HTML:
<div id="container1">
<div id="container2">
// Content here
</div>
</div>
CSS:
#container1{
height: 100%;
width: 100%;
overflow: hidden;
}
#container2{
height: 100%;
width: 100%;
overflow: auto;
padding-right: 20px;
}
It was my own stupidity:
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
Putting this inside onCreate()
method fixed my problem.
public class Test {
private static final Map<Integer, String> myMap;
static {
Map<Integer, String> aMap = ....;
aMap.put(1, "one");
aMap.put(2, "two");
myMap = Collections.unmodifiableMap(aMap);
}
}
If we declare more than one constant then that code will be written in static block and that is hard to maintain in future. So it is better to use anonymous class.
public class Test {
public static final Map numbers = Collections.unmodifiableMap(new HashMap(2, 1.0f){
{
put(1, "one");
put(2, "two");
}
});
}
And it is suggested to used unmodifiableMap for constants other wise it can't be treated as constant.
If you're referring to the shell command line, either of the following will work:
node -v
node --version
Just typing node version
will cause node.js to attempt loading a module named version, which doesn't exist unless you like working with confusing module names.
use:
#ifdef __linux__
//linux code goes here
#elif _WIN32
// windows code goes here
#else
#endif
Angular Cli 8 support Node Js 10.9+. After update Node.js to 10.16 works fine.
With Kotlin you can do,
// to disable clicks
myButton.isClickable = false
// to disable button
myButton.isEnabled = false
// to enable clicks
myButton.isClickable = true
// to enable button
myButton.isEnabled = true
Bravo for @user80168's solution (I'm still counting \
's !) but to avoid all the escaping involved with aliases and shells:
%~/ cat ~/bin/perlmod
perl -le'eval qq{require $ARGV[0]; }
? print ( "Found $ARGV[0] Version: ", eval "$ARGV[0]->VERSION" )
: print "Not installed" ' $1
works reasonably well.
Here might be the simplest and most "modern" approach, using Module::Runtime
:
perl -MModule::Runtime=use_module -E '
say "$ARGV[0] ", use_module($ARGV[0])->VERSION' DBI
This will give a useful error if the module is not installed.
Using -MModule::Runtime
requires it to be installed (it is not a core module).
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
You can also get the value by the following way
$(document).ready(function(){
$("#start").click(function(){
alert($(this).find("input[class='myClass']").val());
});
});
Some of the more obscure operators in C exist solely because they allow implementation of various function-like macros as a single expression that returns a result. I would say that this is the main purpose why the ?:
and ,
operators are allowed to exist, even though their functionality is otherwise redundant.
Lets say we wish to implement a function-like macro that returns the largest of two parameters. It would then be called as for example:
int x = LARGEST(1,2);
The only way to implement this as a function-like macro would be
#define LARGEST(x,y) ((x) > (y) ? (x) : (y))
It wouldn't be possible with an if ... else
statement, since it does not return a result value. Note)
The other purpose of ?:
is that it in some cases actually increases readability. Most often if...else
is more readable, but not always. Take for example long, repetitive switch statements:
switch(something)
{
case A:
if(x == A)
{
array[i] = x;
}
else
{
array[i] = y;
}
break;
case B:
if(x == B)
{
array[i] = x;
}
else
{
array[i] = y;
}
break;
...
}
This can be replaced with the far more readable
switch(something)
{
case A: array[i] = (x == A) ? x : y; break;
case B: array[i] = (x == B) ? x : y; break;
...
}
Please note that ?:
does never result in faster code than if-else
. That's some strange myth created by confused beginners. In case of optimized code, ?:
gives identical performance as if-else
in the vast majority of the cases.
If anything, ?:
can be slower than if-else
, because it comes with mandatory implicit type promotions, even of the operand which is not going to be used. But ?:
can never be faster than if-else
.
Note) Now of course someone will argue and wonder why not use a function. Indeed if you can use a function, it is always preferable over a function-like macro. But sometimes you can't use functions. Suppose for example that x
in the example above is declared at file scope. The initializer must then be a constant expression, so it cannot contain a function call. Other practical examples of where you have to use function-like macros involve type safe programming with _Generic
or "X macros".
Use Commons Net's Util class:
import org.apache.commons.net.io.Util;
...
Util.copyStream(in, out);
$('.tag1, .tag2').on('click', function() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
});
or
function dothing() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
}
$('.tag1, .tag2').on('click', dothing);
or
$('[class^=tag]').on('click', dothing);
I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.
****Note that you probably have to run cmd.exe as an administrator for this to work**
So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run
C:\Windows\System32>cd ras
Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.
So to create our temp file run:
C:\Windows\System32\ras>copy con temp.txt
Now it will let you type the contents of the file, which should look like this:
[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com
So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.
Make a new line and press Ctrl+Z to finish and save.
Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:
C:\Windows\System32\ras>del temp.txt
Now we can connect to our newly configured VPN server with the following command:
C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword
When we want to disconnect we can run:
C:\Windows\System32\ras>rasdial /DISCONNECT
That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd ras
C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
1 file(s) copied.
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
C:\Windows\System32\ras>del temp.txt
C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.
C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.
C:\Windows\System32\ras>
Hope this helps.
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
$ yum install -y yum-utils
$ repoquery -l packagename
If i understand your question right, one way to do is break down the string in chars and then check each char in that string using a loop whether it's a string or a number and then if string save it in a variable and then once the loop is finished, display that to the user
You can take the sets of the columns and just subtract the smaller set from the larger set:
distinct_values = set(df['a'])-set(df['b'])
$keyword = "Batman"; //Term you want to search
$url = 'http://en.wikipedia.org/w/api.php?action=parse&page='.$keyword.'&format=json&prop=text§ion=0';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Infeeds Sniper');
$c = curl_exec($ch);
$json = json_decode($c);
if($json !='' && isset($json->{'parse'})){
$title = $json->{'parse'}->{'title'};
$content = $json->{'parse'}->{'text'}->{'*'};
$pattern = '#<p>(.*)</p>#Us';
if(preg_match($pattern, $content, $matches)){
if($matches[1]!=''){
$con = preg_replace_callback("/\[[^)]+\]/", function($m){return '';}, $matches[1]);
echo '<h2>'.$title.'</h2>'.strip_tags($con).'</p><src>Source: <a href="https://en.wikipedia.org/wiki/'.$keyword.'" target="_blank">Wikipedia</a></src>';
}
}
}
Wiki scrapper gist to get summary from either Wikipedia or DB Pedia API with PHP. Hope it helps.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
Base URL in JavaScript
Here is simple function for your project to get base URL in JavaScript.
// base url
function base_url() {
var pathparts = location.pathname.split('/');
if (location.host == 'localhost') {
var url = location.origin+'/'+pathparts[1].trim('/')+'/'; // http://localhost/myproject/
}else{
var url = location.origin; // http://stackoverflow.com
}
return url;
}
A succinct solution:
public static double round(double value, int precision) {
int scale = (int) Math.pow(10, precision);
return (double) Math.round(value * scale) / scale;
}
See also, https://stackoverflow.com/a/22186845/212950 Thanks to jpdymond for offering this.
instead of receiving the json string a model binding is better. For example:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
The amazing ubiquity of Vim, and the even more amazing ubiquity of Vi-clones in general, on Unix systems alone is enough to make it worth learning.
Besides that, the whole Vi-style thinking is something that I really think has made me a bit more productive. For a person not used to modes such as the command mode and insert mode, it seems a bit excessive to have to enter a mode just to insert text. But, when one has been using Vim for a few months, and has learned quite a few tips and tricks, Vim seems to be an asset that seems to be worth it.
Of course, the Emacs crowd says the same thing regarding Emacs-style thinking, but I gave up on learning Emacs because Vim was simpler and did the job for me.
To view the differences going from the remote file to the local file:
git diff remotename/branchname:remote/path/file1.txt local/path/file1.txt
To view the differences in the other direction:
git diff HEAD:local/path/file1.txt remotename/branchname:remote/path/file1.txt
Basically you can diff any two files anywhere using this notation:
git diff ref1:path/to/file1 ref2:path/to/file2
As usual, ref1
and ref2
could be branch names, remotename/branchname, commit SHAs, etc.
Let me clarify what you're talking about: you want to test Foo
in a testcase, which calls external method uses_some_other_method
. Instead of calling the actual method, you want to mock the return value.
class Foo:
def method_1():
results = uses_some_other_method()
def method_n():
results = uses_some_other_method()
Suppose the above code is in foo.py
and uses_some_other_method
is defined in module bar.py
. Here is the unittest:
import unittest
import mock
from foo import Foo
class TestFoo(unittest.TestCase):
def setup(self):
self.foo = Foo()
@mock.patch('foo.uses_some_other_method')
def test_method_1(self, mock_method):
mock_method.return_value = 3
self.foo.method_1(*args, **kwargs)
mock_method.assert_called_with(*args, **kwargs)
If you want to change the return value every time you passed in different arguments, mock
provides side_effect
.
So, you may use
Yii::app()->getBaseUrl(true)
to get an Absolute webroot url, and strip the http[s]://
Here is how I made monthly page in similar manner as Fernando:
I made five weeks on every page and on fifth week I made function
=IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
that empties fifth week if this month has only four weeks. C12 holds the number of weeks.
Insert following function on the first day field starting sheet #2:
=INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.
Try this:
rows = tabDelimitedTable.split("[\\r\\n]+");
This should work regardless of what line delimiters are in the input, and will ignore blank lines.
You only use the M
for a numeric literal, when you cast it's just:
decimal dtot = (decimal)doubleTotal;
Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal
you may get rounding errors. You may want to convert the numbers to Decimal
before adding them together, or make sure that the numbers aren't floating point numbers in the first place.
I am not sure about be the best way, but works fine and all code stays in your ArrayAdapter.
package br.com.fontolan.pessoas.arrayadapter;
import java.util.List;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import br.com.fontolan.pessoas.R;
import br.com.fontolan.pessoas.model.Telefone;
public class TelefoneArrayAdapter extends ArrayAdapter<Telefone> {
private TelefoneArrayAdapter telefoneArrayAdapter = null;
private Context context;
private EditText tipoEditText = null;
private EditText telefoneEditText = null;
private ImageView deleteImageView = null;
public TelefoneArrayAdapter(Context context, List<Telefone> values) {
super(context, R.layout.telefone_form, values);
this.telefoneArrayAdapter = this;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.telefone_form, parent, false);
tipoEditText = (EditText) view.findViewById(R.id.telefone_form_tipo);
telefoneEditText = (EditText) view.findViewById(R.id.telefone_form_telefone);
deleteImageView = (ImageView) view.findViewById(R.id.telefone_form_delete_image);
final int i = position;
final Telefone telefone = this.getItem(position);
tipoEditText.setText(telefone.getTipo());
telefoneEditText.setText(telefone.getTelefone());
TextWatcher tipoTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
telefoneArrayAdapter.getItem(i).setTipo(s.toString());
telefoneArrayAdapter.getItem(i).setIsDirty(true);
}
};
TextWatcher telefoneTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
telefoneArrayAdapter.getItem(i).setTelefone(s.toString());
telefoneArrayAdapter.getItem(i).setIsDirty(true);
}
};
tipoEditText.addTextChangedListener(tipoTextWatcher);
telefoneEditText.addTextChangedListener(telefoneTextWatcher);
deleteImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
telefoneArrayAdapter.remove(telefone);
}
});
return view;
}
}
The problem you'll face is that there's two types of PEM formatted keys: PKCS8 and SSLeay. It doesn't help that OpenSSL seems to use both depending on the command:
The usual openssl genrsa
command will generate a SSLeay format PEM. An export from an PKCS12 file with openssl pkcs12 -in file.p12
will create a PKCS8 file.
The latter PKCS8 format can be opened natively in Java using PKCS8EncodedKeySpec
. SSLeay formatted keys, on the other hand, can not be opened natively.
To open SSLeay private keys, you can either use BouncyCastle provider as many have done before or Not-Yet-Commons-SSL have borrowed a minimal amount of necessary code from BouncyCastle to support parsing PKCS8 and SSLeay keys in PEM and DER format: http://juliusdavies.ca/commons-ssl/pkcs8.html. (I'm not sure if Not-Yet-Commons-SSL will be FIPS compliant)
By inference from the OpenSSL man pages, key headers for two formats are as follows:
PKCS8 Format
Non-encrypted: -----BEGIN PRIVATE KEY-----
Encrypted: -----BEGIN ENCRYPTED PRIVATE KEY-----
SSLeay Format
-----BEGIN RSA PRIVATE KEY-----
(These seem to be in contradiction to other answers but I've tested OpenSSL's output using PKCS8EncodedKeySpec
. Only PKCS8 keys, showing ----BEGIN PRIVATE KEY-----
work natively)
I tried this code, to retrieve shared preferences from an activity, and could not get it to work:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getAll();
Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());
Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.
getPreferenceManager().setSharedPreferencesName("defaultPreferences");
After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.
I want to more fully address the issue of scroll duration, which, should you choose any earlier answer, will in fact will vary dramatically (and unacceptably) according to the amount of scrolling necessary to reach the target position from the current position .
To obtain a uniform scroll duration the velocity (pixels per millisecond) must account for the size of each individual item - and when the items are of non-standard dimension then a whole new level of complexity is added.
This may be why the RecyclerView developers deployed the too-hard basket for this vital aspect of smooth scrolling.
Assuming that you want a semi-uniform scroll duration, and that your list contains semi-uniform items then you will need something like this.
/** Smoothly scroll to specified position allowing for interval specification. <br>
* Note crude deceleration towards end of scroll
* @param rv Your RecyclerView
* @param toPos Position to scroll to
* @param duration Approximate desired duration of scroll (ms)
* @throws IllegalArgumentException */
private static void smoothScroll(RecyclerView rv, int toPos, int duration) throws IllegalArgumentException {
int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000; // See androidx.recyclerview.widget.LinearSmoothScroller
int itemHeight = rv.getChildAt(0).getHeight(); // Height of first visible view! NB: ViewGroup method!
itemHeight = itemHeight + 33; // Example pixel Adjustment for decoration?
int fvPos = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
int i = Math.abs((fvPos - toPos) * itemHeight);
if (i == 0) { i = (int) Math.abs(rv.getChildAt(0).getY()); }
final int totalPix = i; // Best guess: Total number of pixels to scroll
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(rv.getContext()) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
@Override protected int calculateTimeForScrolling(int dx) {
int ms = (int) ( duration * dx / (float)totalPix );
// Now double the interval for the last fling.
if (dx < TARGET_SEEK_SCROLL_DISTANCE_PX ) { ms = ms*2; } // Crude deceleration!
//lg(format("For dx=%d we allot %dms", dx, ms));
return ms;
}
};
//lg(format("Total pixels from = %d to %d = %d [ itemHeight=%dpix ]", fvPos, toPos, totalPix, itemHeight));
smoothScroller.setTargetPosition(toPos);
rv.getLayoutManager().startSmoothScroll(smoothScroller);
}
PS: I curse the day I began indiscriminately converting ListView to RecyclerView.
this code will work ,
.navbar .navbar-nav > li .navbar-item ,
.navbar .navbar-brand{
color: red;
}
paste in your css and run if you have a element below
eg .
<li>@Html.ActionLink("Login", "Login", "Home", new { area = "" },
new { @class = "navbar-item" })</li>
OR
<li> <button class="navbar-item">hi</button></li>
Fuzzy Wuzzy
is a package that implements Levenshtein distance in python, with some helper functions to help in certain situations where you may want two distinct strings to be considered identical. For example:
>>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
91
>>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
100
or hide any br that follows the p tag, which are obviously not wanted
p + br {
display: none;
}
UPDATE:
You'll also want to goto Security -> Server Roles
, and for public
check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipes
and remove the connect
permission
you can also create your own interface as well.
export interface UserEvent {
target: HTMLInputElement;
}
...
onUpdatingServerName(event: UserEvent) {
.....
}
I've found this other possibility, maybe it could be useful also...
awk 'BEGIN {OFS=ORS="\t" }; {for(i=1; i<14; i++) print $i " "; print $NF "\n" }' your_file
Note: 1. For tabular data and from column $1 to $14
AngularJS — Superheroic JavaScript MVW Framework
Check this simple code
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class FirstFrame extends JFrame{
static JComboBox<ArrayList> mycombo;
FirstFrame()
{
this.setSize(600,500);
this.setTitle("My combo");
this.setLayout(null);
ArrayList<String> names=new ArrayList<String>();
names.add("jessy");
names.add("albert");
names.add("grace");
mycombo=new JComboBox(names.toArray());
mycombo.setBounds(60,32,200,50);
this.add(mycombo);
this.setVisible(true); // window visible
}
public static void main(String[] args) {
FirstFrame frame=new FirstFrame();
}
}
If you want to concatenate the input, then replace printf("%s\n", buffer);
with strcat(big_buffer, buffer);
. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
. The modified program would look like this:
#include <stdio.h>
#include <string.h>
#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024
int main (int argc, char *argv[])
{
char buffer[BUFFERSIZE];
char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
printf("Enter a message: \n");
while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
{
if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
{
strcat(big_buffer, buffer);
}
}
return 0;
}
You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.
#include <iostream>
#include <vector>
#include <string.h>
int main ()
{
std::vector<std::string> myvector ;
std::vector<std::string>::iterator it;
it = myvector.begin();
std::string myarray [] = { "Hi","hello","wassup" };
myvector.insert (myvector.begin(), myarray, myarray+3);
std::cout << "myvector contains:";
for (it=myvector.begin(); it<myvector.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
From "iPhone Tutorial: Better way to check capabilities of iOS devices":
There are two seemingly similar functions that take a parameter kSystemSoundID_Vibrate
:
1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Both of the functions vibrate the iPhone. But, when you use the first function on devices that don’t support vibration, it plays a beep sound. The second function, on the other hand, does nothing on unsupported devices. So if you are going to vibrate the device continuously, as an alert, common sense says, use function 2.
First, add the AudioToolbox framework AudioToolbox.framework
to your target in Build Phases.
Then, import this header file:
#import <AudioToolbox/AudioServices.h>
Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.
span.bold(This name can be anything do not include parenthesis) { font-weight: bold; }
If you don't have an existing local branch, it is truly as simple as:
git fetch
git checkout <remote-branch-name>
For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page
, just do this:
git checkout feature/Main_Page
This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:
git checkout -t <remote>/<remote-branch-name>
If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.
It's quite unclear how you are computing the size ("the size in debug mode"?").
Use printf()
:
printf("the size of c is %u\n", (unsigned int) sizeof c);
Normally you'd print a size_t
value (which is the type sizeof
returns) with %zu
, but if you're using a pre-C99 compiler like Visual Studio that won't work.
You need to find the typedef
statements in your code that define the custom names like uint8
and so on; those are not standard so nobody here can know how they're defined in your code.
New C code should use <stdint.h>
which gives you uint8_t
and so on.
Make sure that the "Distributed Transaction Coordinator" Service is running on both database and client. Also make sure you check "Network DTC Access", "Allow Remote Client", "Allow Inbound/Outbound" and "Enable TIP".
To enable Network DTC Access for MS DTC transactions
Open the Component Services snap-in.
To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.
Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.
On the Action menu, click Properties.
Click the Security tab and make the following changes: In Security Settings, select the Network DTC Access check box.
In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.
The best solution for you would depend on what you require from your fake enum
.
Simple enum:
If you need the enum
as only a list of names identifying different items, the solution by Mark Harrison (above) is great:
Pen, Pencil, Eraser = range(0, 3)
Using a range
also allows you to set any starting value:
Pen, Pencil, Eraser = range(9, 12)
In addition to the above, if you also require that the items belong to a container of some sort, then embed them in a class:
class Stationery:
Pen, Pencil, Eraser = range(0, 3)
To use the enum item, you would now need to use the container name and the item name:
stype = Stationery.Pen
Complex enum:
For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for Simulating Enumerations in Python published in the Python Cookbook. An online version of that is available here.
More info:
PEP 354: Enumerations in Python has the interesting details of a proposal for enum in Python and why it was rejected.
Here is the only CSS solution to fix this. Use the below css.
.row-fluid {
display: table;
}
.row-fluid .span6 {
display: table-cell;
vertical-align: top;
}
.vc_single_image-wrapper {
position: relative;
}
.vc_single_image-wrapper .image-wrapper {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
}
HTML from the OP:
<div class="vc_single_image-wrapper vc_box_border_grey">
<div class="image-wrapper" style="background-image: url(http://i0.wp.com/www.homedecor.nl/wp-content/uploads/2016/03/Gordijnen-Home-Decor-2.jpg?fit=952%2C480;"></div>
</div>
try this, it should work. also remove float from .row-fluid .span6
If you care about order, then just use the equals method:
list1.equals(list2)
If you don't care order then use this
Collections.sort(list1);
Collections.sort(list2);
list1.equals(list2)
There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).
Obviously you can get the key from a KeyValuePair
just by using the Key
property, so that will let you use the indexer of the dictionary:
var pair = ...;
var value = dictionary[pair.Key];
Assert.AreEqual(value, pair.Value);
You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:
var key = dictionary.Where(pair => pair.Value == desiredValue)
.Select(pair => pair.Key)
.FirstOrDefault();
key
will be null if the entry doesn't exist.
This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.
Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.
Here's a class I wrote do multiple inserts with purge option:
<?php
/**
* $pdo->beginTransaction();
* $pmi = new PDOMultiLineInserter($pdo, "foo", array("a","b","c","e"), 10);
* $pmi->insertRow($data);
* ....
* $pmi->insertRow($data);
* $pmi->purgeRemainingInserts();
* $pdo->commit();
*
*/
class PDOMultiLineInserter {
private $_purgeAtCount;
private $_bigInsertQuery, $_singleInsertQuery;
private $_currentlyInsertingRows = array();
private $_currentlyInsertingCount = 0;
private $_numberOfFields;
private $_error;
private $_insertCount = 0;
function __construct(\PDO $pdo, $tableName, $fieldsAsArray, $bigInsertCount = 100) {
$this->_numberOfFields = count($fieldsAsArray);
$insertIntoPortion = "INSERT INTO `$tableName` (`".implode("`,`", $fieldsAsArray)."`) VALUES";
$questionMarks = " (?".str_repeat(",?", $this->_numberOfFields - 1).")";
$this->_purgeAtCount = $bigInsertCount;
$this->_bigInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks.str_repeat(", ".$questionMarks, $bigInsertCount - 1));
$this->_singleInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks);
}
function insertRow($rowData) {
// @todo Compare speed
// $this->_currentlyInsertingRows = array_merge($this->_currentlyInsertingRows, $rowData);
foreach($rowData as $v) array_push($this->_currentlyInsertingRows, $v);
//
if (++$this->_currentlyInsertingCount == $this->_purgeAtCount) {
if ($this->_bigInsertQuery->execute($this->_currentlyInsertingRows) === FALSE) {
$this->_error = "Failed to perform a multi-insert (after {$this->_insertCount} inserts), the following errors occurred:".implode('<br/>', $this->_bigInsertQuery->errorInfo());
return false;
}
$this->_insertCount++;
$this->_currentlyInsertingCount = 0;
$this->_currentlyInsertingRows = array();
}
return true;
}
function purgeRemainingInserts() {
while ($this->_currentlyInsertingCount > 0) {
$singleInsertData = array();
// @todo Compare speed - http://www.evardsson.com/blog/2010/02/05/comparing-php-array_shift-to-array_pop/
// for ($i = 0; $i < $this->_numberOfFields; $i++) $singleInsertData[] = array_pop($this->_currentlyInsertingRows); array_reverse($singleInsertData);
for ($i = 0; $i < $this->_numberOfFields; $i++) array_unshift($singleInsertData, array_pop($this->_currentlyInsertingRows));
if ($this->_singleInsertQuery->execute($singleInsertData) === FALSE) {
$this->_error = "Failed to perform a small-insert (whilst purging the remaining rows; the following errors occurred:".implode('<br/>', $this->_singleInsertQuery->errorInfo());
return false;
}
$this->_currentlyInsertingCount--;
}
}
public function getError() {
return $this->_error;
}
}
How about changing
<input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model="todo.done">
to
<input type='checkbox' ng-change='onCompleteTodo(todo)' ng-model="todo.done">
From docs:
Evaluate given expression when user changes the input. The expression is not evaluated when the value change is coming from the model.
Note, this directive requires
ngModel
to be present.
Actually there is no way to do this through JavaScript, unless you use some external source. Even then, it might not be 100% correct.
Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts("mailto", "[email protected]", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, text);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE
.
Reference: https://www.postgresql.org/docs/current/functions-matching.html
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
if one of the column is number i have experienced the oracle will think '+' as sum operator instead concatenation.
eg:
select (id + name) as one from table 1; (id is numeric)
throws invalid number exception
in such case you can || operator which is concatenation.
select (id || name) as one from table 1;
I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.
It turned out I needed to remove the min-height property too!
height: unset;
min-height: none
Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".
You can make your own animations. For example create xml file in res/anim like this
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<translate
android:fromXDelta="100%p"
android:toXDelta="0"
android:startOffset="0"
android:duration="500"
/> </set>
Then override animations in selected activity:
overridePendingTransition(R.anim.animationIN, R.anim.animationOUT);
If you are only interested in the packages installed globally without the full TREE then:
npm -g ls --depth=0
or locally (omit -g) :
npm ls --depth=0
Drew Sherman's solution is very good, but the list must be contiguous (he suggests manually sorting, and that is not acceptable for me). Guitarthrower's solution is kinda slow if the number of items is large and don't respects the order of the original list: it outputs a sorted list regardless.
I wanted the original order of the items (that were sorted by the date in another column), and additionally I wanted to exclude an item from the final list not only if it was duplicated, but also for a variety of other reasons.
My solution is an improvement on Drew Sherman's solution. Likewise, this solution uses 2 columns for intermediate calculations:
Column A:
The list with duplicates and maybe blanks that you want to filter. I will position it in the A11:A1100 interval as an example, because I had trouble moving the Drew Sherman's solution to situations where it didn't start in the first line.
Column B:
This formula will output 0 if the value in this line is valid (contains a non-duplicated value). Note that you can add any other exclusion conditions that you want in the first IF, or as yet another outer IF.
=IF(ISBLANK(A11);1;IF(COUNTIF($A$11:A11;A11)=1;0;COUNTIF($A11:A$1100;A11)))
Use smart copy to populate the column.
Column C:
In the first line we will find the first valid line:
=MATCH(0;B11:B1100;0)
From that position, we search for the next valid value with the following formula:
=C11+MATCH(0;OFFSET($B$11:$B$1100;C11;0);0)
Put it in the second line and use smart copy to fill the rest of the column. This formula will output #N/D error when there is no more unique itens to point. We will take advantage of this in the next column.
Column D:
Now we just have to get the values pointed by column C:
=IFERROR(INDEX($A$11:$A$1100; C11); "")
Use smart copy to populate the column. This is the output unique list.
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
http://maven.apache.org/guides/mini/guide-using-one-source-directory.html
<build>
<sourceDirectory>../src/main/java</sourceDirectory>
also see
In my case Malwarebytes was holding a handle on my program's executable:
Using Process Explorer to close the handle, or just disabling antivirus for a bit work just fine.
Mark the directory as a source directory. Opened via Ctrl+Shift+Alt+S
Chiming in here a few years after the original question, using laravel 5.1, I had the same error as my migrations were computer generated with all the same date code. I went through all the proposed solutions, then refactored to find the error source.
In following laracasts, and in reading these posts, I believe the correct answer is similar to Vickies answer, with the exception that you don't need to add a separate schema call. You don't need to set the table to Innodb, I am assuming laravel is now doing that.
The migrations simply need to be timed correctly, which means you will modify the date code up (later) in the filename for tables that you need foreign keys on. Alternatively or in addition, Lower the datecode for tables that don't need foreign keys.
The advantage in modifying the datecode is your migration code will be easier to read and maintain.
So far my code is working by adjusting the time code up to push back migrations that need foreign keys.
However I do have hundreds of tables, so at the very end I have one last table for just foreign keys. Just to get things flowing. I am assuming I will pull those into the correct file and modify the datecode as i test them.
So an example: file 2016_01_18_999999_create_product_options_table. This one needs the products table to be created. Look at the file names.
public function up()
{
Schema::create('product_options', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_attribute_id')->unsigned()->index();
$table->integer('product_id')->unsigned()->index();
$table->string('value', 40)->default('');
$table->timestamps();
//$table->foreign('product_id')->references('id')->on('products');
$table->foreign('product_attribute_id')->references('id')->on('product_attributes');
$table->foreign('product_id')->references('id')->on('products');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('product_options');
}
the products table: this needs to migrate first. 2015_01_18_000000_create_products_table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('style_number', 64)->default('');
$table->string('title')->default('');
$table->text('overview')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('products');
}
And finally at the very end the file that I am temporarily using to resolve issues, which I will refactor as I write tests for the models which I named 9999_99_99_999999_create_foreign_keys.php. These keys are commented as I pulled them out, but you get the point.
public function up()
{
// Schema::table('product_skus', function ($table) {
// $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
// });
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Schema::table('product_skus', function ($table)
// {
// $table->dropForeign('product_skus_product_id_foreign');
// });
Yes;
git commit FILE
will commit just FILE. Then you can use
git reset --hard
to undo local changes in other files.
There may be other ways too that I don't know about...
edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)
I tried to rebuilt, restart, clean, update Gradle, etc. However, none of them worked for me.
Sometimes, it can be caused by a wrong naming for an XML or resource file.
At least, for me, that problem was solved by changing the name.
something like below
var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
friends.ForEach(a=>a.msgSentBy='1234');
db.SaveChanges();
}
you can update multiple fields as below
friends.ForEach(a =>
{
a.property1 = value1;
a.property2 = value2;
});
Use Data.List.Split
, which uses split
:
[me@localhost]$ ghci
Prelude> import Data.List.Split
Prelude Data.List.Split> let l = splitOn "," "1,2,3,4"
Prelude Data.List.Split> :t l
l :: [[Char]]
Prelude Data.List.Split> l
["1","2","3","4"]
Prelude Data.List.Split> let { convert :: [String] -> [Integer]; convert = map read }
Prelude Data.List.Split> let l2 = convert l
Prelude Data.List.Split> :t l2
l2 :: [Integer]
Prelude Data.List.Split> l2
[1,2,3,4]
You never give any value to your strings in main
so they are empty, and thus obviously the function returns an empty string.
Replace:
string str1, str2, str3;
with:
string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";
Also, you have several problems in your replaceSubstring
function:
int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
std::string::find
returns a std::string::size_type
(aka. size_t
) not an int
. Two differences: size_t
is unsigned, and it's not necessarily the same size as an int
depending on your platform (eg. on 64 bits Linux or Windows size_t
is unsigned 64 bits while int
is signed 32 bits).s2
is not part of s1
? I'll leave it up to you to find how to fix that. Hint: std::string::npos
;)Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:
if (j % 4 == 0) {
// j is an exact multiple of 4
}
Try doing this, using firefox as fake user agent (moreover, it's a good startup script for web scraping with the use of cookies):
#!/usr/bin/env python2
# -*- coding: utf8 -*-
# vim:ts=4:sw=4
import cookielib, urllib2, sys
def doIt(uri):
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
page = opener.open(uri)
page.addheaders = [('User-agent', 'Mozilla/5.0')]
print page.read()
for i in sys.argv[1:]:
doIt(i)
python script.py "http://www.ichangtou.com/#company:data_000008.html"
var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null
|| screen.width <= 480;