I got the same error in Chrome console.
My problem was, I was trying to go to the site using http://
instead of https://
. So there was nothing to fix, just had to go to the same site using https
.
Similar answer to Gunnar, with more complete example: You can even transparently return the whole thing:
function dumpArguments(...args) {
for (var i = 0; i < args.length; i++)
console.log(args[i]);
return args;
}
dumpArguments("foo", "bar", true, 42, ["yes", "no"], { 'banana': true });
Output:
foo
bar
true
42
["yes","no"]
{"banana":true}
Depends on what you run in that thread. If that's your code, then you can implement a stop condition (see other answers).
However, if what you want is to run someone else's code, then you should fork and start a process. Like this:
import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()
now, whenever you want to stop that process, send it a SIGTERM like this:
proc.terminate()
proc.join()
And it's not slow: fractions of a second. Enjoy :)
check this out: http://hayageek.com/docs/jquery-upload-file.php I've found it accidentally on the net.
git rev-list HEAD --count
git rev-list <commit>
:
List commits that are reachable by following the parent links from the given commit (in this case, HEAD).
--count
: Print a number stating how many commits would have been listed, and suppress all other output.
Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.
First check if the element exists by looking for it's index. If it does exist, remove it by its index using the splice method
elementPosition = array.indexOf(value);
if(elementPosition != -1) {
array.splice(elementPosition, 1);
}
It matches p
elements with class some_class
that are directly under a div
.
The fastest running code would be carefully hand crafted machine code. Assembler will be almost as good. Both are very low level and it takes a lot of writing code to do things. C is a little above assembler. You still have the ability to control things at a very low level in the actual machine, but there is enough abstraction make writing it faster and easier then assembler. Other languages such as C# and JAVA are even more abstract. While Assembler and machine code are called low level languages, C# and JAVA (and many others) are called high level languages. C is sometimes called a middle level language.
Probably a bit late but this is worth a mention:
Environment.GetCommandLineArgs()[0];
Or more correctly to get just the directory path:
System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
Edit:
Quite a few people have pointed out that GetCommandLineArgs
is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof' GetCommandLineArgs
, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.
You can use
<input name="Upload Saved Replay" type="file"
accept="application/pdf,application/msword,
application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>
whearat
application/pdf
means .pdf
application/msword
means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document
means .docx
instead.
[EDIT] Be warned, .dot
might match too.
ButterKnife is probably the best solution for the clutter problem. It uses annotation processors to generate the so called "old method" boilerplate code.
But the onClick method can still be used, with a custom inflator.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup cnt, Bundle state) {
inflater = FragmentInflatorFactory.inflatorFor(inflater, this);
return inflater.inflate(R.layout.fragment_main, cnt, false);
}
public class FragmentInflatorFactory implements LayoutInflater.Factory {
private static final int[] sWantedAttrs = { android.R.attr.onClick };
private static final Method sOnCreateViewMethod;
static {
// We could duplicate its functionallity.. or just ignore its a protected method.
try {
Method method = LayoutInflater.class.getDeclaredMethod(
"onCreateView", String.class, AttributeSet.class);
method.setAccessible(true);
sOnCreateViewMethod = method;
} catch (NoSuchMethodException e) {
// Public API: Should not happen.
throw new RuntimeException(e);
}
}
private final LayoutInflater mInflator;
private final Object mFragment;
public FragmentInflatorFactory(LayoutInflater delegate, Object fragment) {
if (delegate == null || fragment == null) {
throw new NullPointerException();
}
mInflator = delegate;
mFragment = fragment;
}
public static LayoutInflater inflatorFor(LayoutInflater original, Object fragment) {
LayoutInflater inflator = original.cloneInContext(original.getContext());
FragmentInflatorFactory factory = new FragmentInflatorFactory(inflator, fragment);
inflator.setFactory(factory);
return inflator;
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if ("fragment".equals(name)) {
// Let the Activity ("private factory") handle it
return null;
}
View view = null;
if (name.indexOf('.') == -1) {
try {
view = (View) sOnCreateViewMethod.invoke(mInflator, name, attrs);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof ClassNotFoundException) {
return null;
}
throw new RuntimeException(e);
}
} else {
try {
view = mInflator.createView(name, null, attrs);
} catch (ClassNotFoundException e) {
return null;
}
}
TypedArray a = context.obtainStyledAttributes(attrs, sWantedAttrs);
String methodName = a.getString(0);
a.recycle();
if (methodName != null) {
view.setOnClickListener(new FragmentClickListener(mFragment, methodName));
}
return view;
}
private static class FragmentClickListener implements OnClickListener {
private final Object mFragment;
private final String mMethodName;
private Method mMethod;
public FragmentClickListener(Object fragment, String methodName) {
mFragment = fragment;
mMethodName = methodName;
}
@Override
public void onClick(View v) {
if (mMethod == null) {
Class<?> clazz = mFragment.getClass();
try {
mMethod = clazz.getMethod(mMethodName, View.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"Cannot find public method " + mMethodName + "(View) on "
+ clazz + " for onClick");
}
}
try {
mMethod.invoke(mFragment, v);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
}
Another option to resolve issue described in OP which I encountered on recent bootcamp training is using window.setTimeout to wrap around the code which is bothersome. My understanding is that it delays the execution of the function for the specified time period (500ms in this case), allowing enough time for the page to load. So, for example:
<script type = "text/javascript">
window.setTimeout(function(){
alert("Hello World!");
}, 500);
</script>
Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.
import UIKit
// MARK: Local Constants
private let changeSegueId = "MasterToChange"
private let bookSegueId = "MasterToBook"
I have stumbled upon this problem for one hour. After an hour, I tried debugging and this helped:
$('.list').on('click', 'span', (e) => {
$(e.target).parent().remove();
});
HTML:
<ul class="list">
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
</ul>
/usr/local/tomcat6/bin/catalina.sh version
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
You should use strcat
, or better, strncat
. Google it (the keyword is "concatenating").
You can see if object has shape or not
def check_array(x):
try:
x.shape
return True
except:
return False
None of the answers actually work. I've managed to find the solution myself. This is a bit hackish, but it solve the problem for me:
echo off
setlocal enableextensions
setlocal enabledelayedexpansion
set MAX_TRIES=100
set P=%PATH%
for /L %%a in (1, 1, %MAX_TRIES%) do (
for /F "delims=;" %%g in ("!P!") do (
echo %%g
set P=!P:%%g;=!
if "!P!" == "%%g" goto :eof
)
)
Oh ! I hate batch file programming !!
Updated
Mark's solution is simpler but it won't work with path containing whitespace. This is a little-modified version of Mark's solution
echo off
setlocal enabledelayedexpansion
set NonBlankPath=%PATH: =#%
set TabbedPath=%NonBlankPath:;= %
for %%g in (%TabbedPath%) do (
set GG=%%g
echo !GG:#= !
)
I found this:
osascript -e 'tell application "iOS Simulator" to quit'
xcrun simctl list devices | grep -v '^[-=]' | cut -d "(" -f2 | cut -d ")" -f1 | xargs -I {} xcrun simctl erase "{}"
Source: https://gist.github.com/ZevEisenberg/5a172662cb576872d1ab
Here's the intended way to convert a String to a Date:
String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);
Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.
To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100
in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application.
If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.
If you set CURLINFO_HEADER_OUT
to true
, outgoing headers are available in the array returned by curl_getinfo()
, under request_header
key:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
This will print:
GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*
Note the auth details are base64-encoded:
echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword
Also note that username and password need to be percent-encoded to escape any URL reserved characters (/
, ?
, &
, :
and so on) they might contain:
curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));
EDIT (8/3/2013): Use http://sourceforge.net/projects/shelled/files/shelled/update/ for latest version
EDIT (2/25/2013): Non need to install linux tool for shelled 2.0.2 on Eclipse 4.2.1. Also, no need to download zip file. Here's the update site of shelled 2.0.2: http://sourceforge.net/projects/shelled/files/shelled/ShellEd%202.0.2/update/
OLD POST:
I like Shelled as well. If you install it now, you need to download the zip file and point to it in the install new software wizard in Eclipse. You'll also need to install the man plugin from
http://download.eclipse.org/technology/linuxtools/update
first of all,
be sure that there is a post
if(isset($_POST['username'])) {
// check if the username has been set
}
second, and most importantly, sanitize the data, meaning that
$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";
is deadly dangerous, instead use
$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";
and please research the subject sql injection
index[hash(input)%2]
would result in a collision for half of all possible hashes and a range of values. index[hash(input)%prime]
results in a collision of <2 of all possible hashes. Fixing the divisor to the table size also ensures that the number cannot be greater than the table.
This worked for me
cp /usr/local/lib/python3.5/configparser.py /usr/local/lib/python3.5/ConfigParser.py
This is just example using reflect.DeepEqual() that is given in @VictorDeryagin's answer.
package main
import (
"fmt"
"reflect"
)
func main() {
a := []int {4,5,6}
b := []int {4,5,6}
c := []int {4,5,6,7}
fmt.Println(reflect.DeepEqual(a, b))
fmt.Println(reflect.DeepEqual(a, c))
}
Result:
true
false
Try it in Go Playground
You can use
adb shell ps | grep apps | awk '{print $9}'
to produce an output like:
com.google.process.gapps
com.google.android.apps.uploader
com.google.android.apps.plus
com.google.android.apps.maps
com.google.android.apps.maps:GoogleLocationService
com.google.android.apps.maps:FriendService
com.google.android.apps.maps:LocationFriendService
adb shell ps returns a list of all running processes on the android device, grep apps searches for any row with contains "apps", as you can see above they are all com.google.android.APPS. or GAPPS, awk extracts the 9th column which in this case is the package name.
To search for a particular package use
adb shell ps | grep PACKAGE.NAME.HERE | awk '{print $9}'
i.e adb shell ps | grep com.we7.player | awk '{print $9}'
If it is running the name will appear, if not there will be no result returned.
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
As a LinearSegmentedColormaps
is based on a dictionary of red, green and blue, it's necessary to reverse each item:
import matplotlib.pyplot as plt
import matplotlib as mpl
def reverse_colourmap(cmap, name = 'my_cmap_r'):
"""
In:
cmap, name
Out:
my_cmap_r
Explanation:
t[0] goes from 0 to 1
row i: x y0 y1 -> t[0] t[1] t[2]
/
/
row i+1: x y0 y1 -> t[n] t[1] t[2]
so the inverse should do the same:
row i+1: x y1 y0 -> 1-t[0] t[2] t[1]
/
/
row i: x y1 y0 -> 1-t[n] t[2] t[1]
"""
reverse = []
k = []
for key in cmap._segmentdata:
k.append(key)
channel = cmap._segmentdata[key]
data = []
for t in channel:
data.append((1-t[0],t[2],t[1]))
reverse.append(sorted(data))
LinearL = dict(zip(k,reverse))
my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
return my_cmap_r
See that it works:
my_cmap
<matplotlib.colors.LinearSegmentedColormap at 0xd5a0518>
my_cmap_r = reverse_colourmap(my_cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = my_cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = my_cmap_r, norm=norm, orientation='horizontal')
EDIT
I don't get the comment of user3445587. It works fine on the rainbow colormap:
cmap = mpl.cm.jet
cmap_r = reverse_colourmap(cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = cmap_r, norm=norm, orientation='horizontal')
But it especially works nice for custom declared colormaps, as there is not a default _r
for custom declared colormaps. Following example taken from http://matplotlib.org/examples/pylab_examples/custom_cmap.html:
cdict1 = {'red': ((0.0, 0.0, 0.0),
(0.5, 0.0, 0.1),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0))
}
blue_red1 = mpl.colors.LinearSegmentedColormap('BlueRed1', cdict1)
blue_red1_r = reverse_colourmap(blue_red1)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = blue_red1, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = blue_red1_r, norm=norm, orientation='horizontal')
As mentioned by others here, that you could have two adb's running ... And to add to these answers from a Linux box perspective ( for the next newbie who is working from Linux );
Uninstall your distro's android-tools ( use zypper or yum etc )
# zypper -v rm android-tools
Find where your other adb is
# find /home -iname "*adb"|grep -i android
Say it was at ;
/home/developer/Android/Sdk/platform-tools/adb
Then Make a softlink to it in the /usr/bin folder
ln -s /home/developer/Android/Sdk/platform-tools/adb /usr/bin/adb
Then;
# adb start-server
CTE has its uses - when data in the CTE is small and there is strong readability improvement as with the case in recursive tables. However, its performance is certainly no better than table variables and when one is dealing with very large tables, temporary tables significantly outperform CTE. This is because you cannot define indices on a CTE and when you have large amount of data that requires joining with another table (CTE is simply like a macro). If you are joining multiple tables with millions of rows of records in each, CTE will perform significantly worse than temporary tables.
Use the radix parameter of parseInt
:
var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
1.Go to your manifest.xml
file.
2.Find
the activity tag
for which you want to hide your ActionBar and then add
,
android:theme="@style/Theme.AppCompat.NoActionBar"
<activity
android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.NoActionBar"
>
Ubuntu 16.04 comes with PHP7 as the standard, so there are no PHP5 packages
However if you like you can add a PPA to get those packages anyways:
Remove all the stock php packages
List installed php packages with dpkg -l | grep php| awk '{print $2}' |tr "\n" " "
then remove unneeded packages with sudo aptitude purge your_packages_here or if you want to directly remove them all use :
sudo aptitude purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`
Add the PPA
sudo add-apt-repository ppa:ondrej/php
Install your PHP Version
sudo apt-get update
sudo apt-get install php5.6
You can install php5.6 modules too ..
Verify your version
sudo php -v
Based on https://askubuntu.com/a/756186/532957 (thanks @AhmedJerbi)
For adding some more information, your example will work without the @
symbol (it prevents escaping with \), this way:
string foo = "this \"word\" is escaped!";
It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).
Edit: Unfortunately, as of PHP 8.0, the answer is not "No, not anymore". This RFC was not accepted as I hoped, proposing to change T_PAAMAYIM_NEKUDOTAYIM
to T_DOUBLE_COLON
; but it was declined.
Note: I keep this answer for historical purposes. Actually, because of the creation of the RFC and the votes ratio at some point, I created this answer. Also, I keep this for hoping it to be accepted in the near future.
In large part, pointers are arrays (in C/C++) - they are addresses in memory, and can be accessed like an array if desired (in "normal" cases).
Since they're the address of an item, they're small: they take up only the space of an address. Since they're small, sending them to a function is cheap. And then they allow that function to work on the actual item rather than a copy.
If you want to do dynamic storage allocation (such as for a linked-list), you must use pointers, because they're the only way to grab memory from the heap.
The report might want to access a DataSource or DataView where the AD user (or AD group) has insuficcient access rights.
Make sure you check out the following URLs:
http://REPORTSERVERNAME/Reports/Pages/Folder.aspx?ItemPath=%2fDataSources
http://REPORTSERVERNAME/Reports/Pages/Folder.aspx?ItemPath=%2fDataSets
Then choose Folder Settings
(or the appropriate individual DataSource
or DataSet
) and select Security
. The user group needs to have the Browser
permission.
I just found this question while on a quest to do the same thing.
After some experimenting I came across an answer that works the way the OQ would want and is simple as heck, but not very general purpose.
Create a shortcut on your desktop or elsewhere (you can use the create-shortcut helper from the right-click menu), set it to run the program "cmd.exe" and run it. When the window opens, position it where you want your window to be. To save that position, bring up the properties menu and hit "Save".
Now if you want you can also set other properties like colors and I highly recommend changing the buffer to be a width of 120-240 and the height to 9999 and enable quick edit mode (why aren't these the defaults!?!)
Now you have a shortcut that will work. Make one of these for each CMD window you want opened at a different location.
Now for the trick, the windows CMD START command can run shortcuts. You can't programmatically reposition the windows before launch, but at least it comes up where you want and you can launch it (and others) from a batch file or another program.
Using a shortcut with cmd /c you can create one shortcut that can launch ALL your links at once by using a command that looks like this:
cmd /c "start cmd_link1 && start cmd_link2 && start cmd_link3"
This will open up all your command windows to your favorite positions and individually set properties like foreground color, background color, font, administrator mode, quick-edit mode, etc... with a single click. Now move that one "link" into your startup folder and you've got an auto-state restore with no external programs at all.
This is a pretty straight-forward solution. It's not general purpose, but I believe it will solve the problem that most people reading this question are trying to solve.
I did this recently so I'll post my cmd file here:
cd /d C:\shortucts
for %%f in (*.lnk *.rdp *.url) do start %%f
exit
Late EDIT: I didn't mention that if the original cmd /c command is run elevated then every one of your windows can (if elevation was selected) start elevated without individually re-prompting you. This has been really handy as I start 3 cmd windows and 3 other apps all elevated every time I start my computer.
There are quite a few ways to check if a device is an iPad. This is my favorite way to check whether the device is in fact an iPad:
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
return YES; /* Device is iPad */
}
#define IDIOM UI_USER_INTERFACE_IDIOM()
#define IPAD UIUserInterfaceIdiomPad
if ( IDIOM == IPAD ) {
/* do something specifically for iPad. */
} else {
/* do something specifically for iPhone or iPod touch. */
}
if ( [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPad"] ) {
return YES; /* Device is iPad */
}
#define IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
if ( IPAD )
return YES;
For a Swift solution, see this answer: https://stackoverflow.com/a/27517536/2057171
I'm on Windows 10 and I saved my key with Windows1252 encoding and it worked for me. On another StackOverflow question some people were fixing this with UTF-8 with BOM.
In other words, it may be the file encoding.
Both support the same functions. jquery.min.js
is a compressed version of jquery.js
(whitespaces and comments stripped out, shorter variable names, ...) in order to preserve bandwidth. In terms of functionality they are absolutely the same. It is recommended to use this compressed version in production environment.
Please try the following:
import re
name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
m = re.match("(^[A-Z]\d[A-Z]\d)", element)
if m:
print(m.groups())
Try utilizing .one()
var button = $("#button"),_x000D_
result = $("#result"),_x000D_
buttonHandler = function buttonHandler(e) {_x000D_
result.html("processing...");_x000D_
$(this).fadeOut(1000, function() {_x000D_
// do stuff_x000D_
setTimeout(function() {_x000D_
// reset `click` event at `button`_x000D_
button.fadeIn({_x000D_
duration: 500,_x000D_
start: function() {_x000D_
result.html("done at " + $.now());_x000D_
}_x000D_
}).one("click", buttonHandler);_x000D_
_x000D_
}, 5000)_x000D_
})_x000D_
};_x000D_
_x000D_
button.one("click", buttonHandler);
_x000D_
#button {_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background: olive;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">_x000D_
</script>_x000D_
<div id="result"></div>_x000D_
<div id="button">click</div>
_x000D_
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void displayBinary(int n)
{
char bistr[1000];
itoa(n,bistr,2); //2 means binary u can convert n upto base 36
printf("%s",bistr);
}
int main()
{
int n;
cin>>n;
displayBinary(n);
getch();
return 0;
}
Your code has two problems. One was identified and answered, but the other wasn't. The first was that your selector was missing the name of its parameter. However, even when you fix that, the line will still raise an exception, assuming your revised method signature still includes more than one argument. Let's say your revised method is declared as:
-(void)myTestWithString:(NSString *)sourceString comparedTo:(NSString *)testString ;
Creating selectors for methods that take multiple arguments is perfectly valid (e.g. @selector(myTestWithString:comparedTo:) ). However, the performSelector method only allows you to pass one value to myTest, which unfortunately has more than one parameter. It will error out and tell you that you didn't supply enough values.
You could always redefine your method to take a collection as it's only parameter:
-(void)myTestWithObjects:(NSDictionary *)testObjects ;
However, there is a more elegant solution (that doesn't require refactoring). The answer is to use NSInvocation, along with its setArgument:atIndex:
and invoke
methods.
I've written up an article, including a code example, if you want more details. The focus is on threading, but the basics still apply.
Good luck!
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
You can create a new model to Deserialize your Json CustomerJson
:
public class CustomerJson
{
[JsonProperty("customer")]
public Customer Customer { get; set; }
}
public class Customer
{
[JsonProperty("first_name")]
public string Firstname { get; set; }
[JsonProperty("last_name")]
public string Lastname { get; set; }
...
}
And you can deserialize your json easily :
JsonConvert.DeserializeObject<List<CustomerJson>>(json);
Hope it helps !
Documentation: Serializing and Deserializing JSON
It is simple! You create new timer.
Timer timer = new Timer();
Then you extend the timer task
class UpdateBallTask extends TimerTask {
Ball myBall;
public void run() {
//calculate the new position of myBall
}
}
And then add the new task to the Timer with some update interval
final int FPS = 40;
TimerTask updateBall = new UpdateBallTask();
timer.scheduleAtFixedRate(updateBall, 0, 1000/FPS);
Disclaimer: This is not the ideal solution. This is solution using the Timer class (as asked by OP). In Android SDK, it is recommended to use the Handler class (there is example in the accepted answer).
If you are getting an error like the one below:
OperationalError: FATAL: no pg_hba.conf entry for host "your ipv6",
user "username", database "postgres", SSL off
then add an entry like the following, with your mac address.
host all all [your ipv6]/128 md5
I'm also having the same issue with a very latest Tomcat server (7.0.40). It goes non-responsive once for a couple of days.
To see open connections, you may use:
sudo netstat -tonp | grep jsvc | grep --regexp="127.0.0.1:443" --regexp="127.0.0.1:80" | grep CLOSE_WAIT
As mentioned in this post, you may use /proc/sys/net/ipv4/tcp_keepalive_time
to view the values. The value seems to be in seconds and defaults to 7200 (i.e. 2 hours).
To change them, you need to edit /etc/sysctl.conf
.
Open/create `/etc/sysctl.conf`
Add `net.ipv4.tcp_keepalive_time = 120` and save the file
Invoke `sysctl -p /etc/sysctl.conf`
Verify using `cat /proc/sys/net/ipv4/tcp_keepalive_time`
The following is a group of versatile C functions for timer management based on the gettimeofday() system call. All the timer properties are contained in a single ticktimer struct - the interval you want, the total running time since the timer initialization, a pointer to the desired callback you want to call, the number of times the callback was called. A callback function would look like this:
void your_timer_cb (struct ticktimer *t) {
/* do your stuff here */
}
To initialize and start a timer, call ticktimer_init(your_timer, interval, TICKTIMER_RUN, your_timer_cb, 0).
In the main loop of your program call ticktimer_tick(your_timer) and it will decide whether the appropriate amount of time has passed to invoke the callback.
To stop a timer, just call ticktimer_ctl(your_timer, TICKTIMER_STOP).
ticktimer.h:
#ifndef __TICKTIMER_H
#define __TICKTIMER_H
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#define TICKTIMER_STOP 0x00
#define TICKTIMER_UNCOMPENSATE 0x00
#define TICKTIMER_RUN 0x01
#define TICKTIMER_COMPENSATE 0x02
struct ticktimer {
u_int64_t tm_tick_interval;
u_int64_t tm_last_ticked;
u_int64_t tm_total;
unsigned ticks_total;
void (*tick)(struct ticktimer *);
unsigned char flags;
int id;
};
void ticktimer_init (struct ticktimer *, u_int64_t, unsigned char, void (*)(struct ticktimer *), int);
unsigned ticktimer_tick (struct ticktimer *);
void ticktimer_ctl (struct ticktimer *, unsigned char);
struct ticktimer *ticktimer_alloc (void);
void ticktimer_free (struct ticktimer *);
void ticktimer_tick_all (void);
#endif
ticktimer.c:
#include "ticktimer.h"
#define TIMER_COUNT 100
static struct ticktimer timers[TIMER_COUNT];
static struct timeval tm;
/*!
@brief
Initializes/sets the ticktimer struct.
@param timer
Pointer to ticktimer struct.
@param interval
Ticking interval in microseconds.
@param flags
Flag bitmask. Use TICKTIMER_RUN | TICKTIMER_COMPENSATE
to start a compensating timer; TICKTIMER_RUN to start
a normal uncompensating timer.
@param tick
Ticking callback function.
@param id
Timer ID. Useful if you want to distinguish different
timers within the same callback function.
*/
void ticktimer_init (struct ticktimer *timer, u_int64_t interval, unsigned char flags, void (*tick)(struct ticktimer *), int id) {
gettimeofday(&tm, NULL);
timer->tm_tick_interval = interval;
timer->tm_last_ticked = tm.tv_sec * 1000000 + tm.tv_usec;
timer->tm_total = 0;
timer->ticks_total = 0;
timer->tick = tick;
timer->flags = flags;
timer->id = id;
}
/*!
@brief
Checks the status of a ticktimer and performs a tick(s) if
necessary.
@param timer
Pointer to ticktimer struct.
@return
The number of times the timer was ticked.
*/
unsigned ticktimer_tick (struct ticktimer *timer) {
register typeof(timer->tm_tick_interval) now;
register typeof(timer->ticks_total) nticks, i;
if (timer->flags & TICKTIMER_RUN) {
gettimeofday(&tm, NULL);
now = tm.tv_sec * 1000000 + tm.tv_usec;
if (now >= timer->tm_last_ticked + timer->tm_tick_interval) {
timer->tm_total += now - timer->tm_last_ticked;
if (timer->flags & TICKTIMER_COMPENSATE) {
nticks = (now - timer->tm_last_ticked) / timer->tm_tick_interval;
timer->tm_last_ticked = now - ((now - timer->tm_last_ticked) % timer->tm_tick_interval);
for (i = 0; i < nticks; i++) {
timer->tick(timer);
timer->ticks_total++;
if (timer->tick == NULL) {
break;
}
}
return nticks;
} else {
timer->tm_last_ticked = now;
timer->tick(timer);
timer->ticks_total++;
return 1;
}
}
}
return 0;
}
/*!
@brief
Controls the behaviour of a ticktimer.
@param timer
Pointer to ticktimer struct.
@param flags
Flag bitmask.
*/
inline void ticktimer_ctl (struct ticktimer *timer, unsigned char flags) {
timer->flags = flags;
}
/*!
@brief
Allocates a ticktimer struct from an internal
statically allocated list.
@return
Pointer to the newly allocated ticktimer struct
or NULL when no more space is available.
*/
struct ticktimer *ticktimer_alloc (void) {
register int i;
for (i = 0; i < TIMER_COUNT; i++) {
if (timers[i].tick == NULL) {
return timers + i;
}
}
return NULL;
}
/*!
@brief
Marks a previously allocated ticktimer struct as free.
@param timer
Pointer to ticktimer struct, usually returned by
ticktimer_alloc().
*/
inline void ticktimer_free (struct ticktimer *timer) {
timer->tick = NULL;
}
/*!
@brief
Checks the status of all allocated timers from the
internal list and performs ticks where necessary.
@note
Should be called in the main loop.
*/
inline void ticktimer_tick_all (void) {
register int i;
for (i = 0; i < TIMER_COUNT; i++) {
if (timers[i].tick != NULL) {
ticktimer_tick(timers + i);
}
}
}
Well, according to me to it is O(2^n)
as in this function only recursion is taking the considerable time (divide and conquer). We see that, the above function will continue in a tree until the leaves are approaches when we reach to the level F(n-(n-1))
i.e. F(1)
. So, here when we jot down the time complexity encountered at each depth of tree, the summation series is:
1+2+4+.......(n-1)
= 1((2^n)-1)/(2-1)
=2^n -1
that is order of 2^n [ O(2^n) ]
.
Well, I figured it out myself, right after posting, which is the most embarassing way. :)
It seems every member of a StackPanel will simply fill its minimum requested size.
In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.
I would love to see a more elegant method of handling this, but it will do.
Integer objects are immutable. You can't change the value of the integer held by the object itself, but you can just create a new Integer object to hold the result:
Integer start = new Integer(5);
Integer end = start + 5; // end == 10;
I was struggling for a while with this as my work computer (with Windows 10) created the default user library on a network drive, which would slow down R and RStudio to an unusable state.
In case this helps someone, this is the easiest way I found, without requiring admin rights:
C:\Users\username\R\win-library\rversion
(for example, something like: C:\Users\janebloggs\R\win-library\3.6
).Renviron
file in your home directory (which might be on the network drive?), and in it, write one single line that defines the R_LIBS_USER
variable to be your custom path:R_LIBS_USER=C:\Users\janebloggs\R\win-library\3.6
(feel free to add comments too, with lines starting with #
)
If a .Renviron
file exists, R will read it at startup and use the variables as they are defined in there, before running the code in the .Rprofile
. You can read about it in help(Startup)
.
Now it should be persistent between sessions!
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
In my case (im using Firebase Cloud Functions) i opened .eslintrc.json
and changed:
"parserOptions": {
// Required for certain syntax usages
"ecmaVersion": 2017
},
to:
"parserOptions": {
// Required for certain syntax usages
"ecmaVersion": 2020
},
"You can store as many objects as you want within a bucket, and write, read, and delete objects in your bucket. Objects can be up to 5 terabytes in size."
from http://aws.amazon.com/s3/details/ (as of Mar 4th 2015)
Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.
Public Function SendEmail2()
Dim varName As Variant
Dim varCC As Variant
Dim varSubject As Variant
Dim varBody As Variant
varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','
varSubject = "Hello"
'Email subject
varBody = "Let's get ice cream this week"
'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File
End Function
I had the same question for macOS.
But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew
.
I fixed my issue with: $ brew uninstall python@2
Some context on here: https://bugs.swift.org/browse/SR-1061
If you are using this query to generate an input file for your Data Warehouse, then you need to format the data appropriately. Essentially in that case you are converting the date (which does have a time component) to a string. You need to explicitly format your string or change your nls_date_format to set the default. In your query you could simply do:
select to_char(some_date, 'yyyy-mm-dd hh24:mi:ss') my_date
from some_table;
I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
'update to the cell that contains HTML you want converted
.ExecWB 17, 0
'Select all contents in browser
.ExecWB 12, 2
'Copy them
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
'update to cell you want converted HTML pasted in
.Quit
End With
End Sub
Yes, just add multiple FileAppenders to your logger. For example:
<log4net>
<appender name="File1Appender" type="log4net.Appender.FileAppender">
<file value="log-file-1.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>
<appender name="File2Appender" type="log4net.Appender.FileAppender">
<file value="log-file-2.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="File1Appender" />
<appender-ref ref="File2Appender" />
</root>
</log4net>
you may try this way also, it will provide you material style dialogs
private void showDialog()
{
String text2 = "<font color=#212121>Medi Notification</font>";//for custom title color
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle(Html.fromHtml(text2));
String text3 = "<font color=#A4A4A4>You can complete your profile now or start using the app and come back later</font>";//for custom message
builder.setMessage(Html.fromHtml(text3));
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
toast = Toast.makeText(getApplicationContext(), "DELETE", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
toast = Toast.makeText(getApplicationContext(), "CANCEL", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
builder.show();
}
If the variable is same, then
: "${VARIABLE:=DEFAULT_VALUE}"
assigns DEFAULT_VALUE
to VARIABLE
if not defined. The double quotes prevent globbing and word splitting.
Also see Section 3.5.3, Shell Parameter Expansion, in the Bash manual.
YearMonth // Represent the year and month, without a date and without a time zone.
.from( // Extract the year and month from a `LocalDate` (a year-month-day).
LocalDate // Represent a date without a time-of-day and without a time zone.
.parse( // Get a date from an input string.
"1/13/2012" , // Poor choice of format for a date. Educate the source of your data about the standard ISO 8601 formats to be used when exchanging date-time values as text.
DateTimeFormatter.ofPattern( "M/d/uuuu" ) // Specify a formatting pattern by which to parse the input string.
) // Returns a `LocalDate` object.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determines the last day of the month for that particular year-month, and returns a `LocalDate` object.
.toString() // Generate text representing the value of that `LocalDate` object using standard ISO 8601 format.
See this code run live at IdeOne.com.
2012-01-31
YearMonth
The YearMonth
class makes this easy. The atEndOfMonth
method returns a LocalDate
. Leap year in February is accounted for.
First define a formatting pattern to match your string input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu" ) ;
Use that formatter to get a LocalDate
from the string input.
String s = "1/13/2012" ;
LocalDate ld = LocalDate.parse( "1/13/2012" , f ) ;
Then extract a YearMonth
object.
YearMonth ym = YearMonth.from( ld ) ;
Ask that YearMonth
to determine the last day of its month in that year, accounting for Leap Year in February.
LocalDate endOfMonth = ym.atEndOfMonth() ;
Generate text representing that date, in standard ISO 8601 format.
String output = endOfMonth.toString() ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
timedisplayLabel= [[UILabel alloc]initWithFrame:CGRectMake(70, 194, 180, 60)];
[timedisplayLabel setTextAlignment:NSTextAlignmentLeft];
[timedisplayLabel setBackgroundColor:[UIColor clearColor]];
[timedisplayLabel setAdjustsFontSizeToFitWidth:YES];
[timedisplayLabel setTextColor:[UIColor blackColor]];
[timedisplayLabel setUserInteractionEnabled:NO];
[timedisplayLabel setFont:[UIFont fontWithName:@"digital-7" size:60]];
timedisplayLabel.layer.shadowColor =[[UIColor whiteColor ]CGColor ];
timedisplayLabel.layer.shadowOffset=(CGSizeMake(0, 0));
timedisplayLabel.layer.shadowOpacity=1;
timedisplayLabel.layer.shadowRadius=3.0;
timedisplayLabel.layer.masksToBounds=NO;
timedisplayLabel.shadowColor=[UIColor darkGrayColor];
timedisplayLabel.shadowOffset=CGSizeMake(0, 2);
Here's one I've run into, in real life.
Assume you have a table of external/3rd party logins for users, and you're going to merge two users and want to dedupe on the provider/provider key values.
;WITH Logins AS
(
SELECT [LoginId],[UserId],[Provider],[ProviderKey]
FROM [dbo].[UserLogin]
WHERE [UserId]=@FromUserID -- is the user we're deleting
OR [UserId]=@ToUserID -- is the user we're moving data to
), Ranked AS
(
SELECT Logins.*
, [Picker]=ROW_NUMBER() OVER (
PARTITION BY [Provider],[ProviderKey]
ORDER BY CASE WHEN [UserId]=@FromUserID THEN 1 ELSE 0 END)
FROM Logins
)
MERGE Logins AS T
USING Ranked AS S
ON S.[LoginId]=T.[LoginID]
WHEN MATCHED AND S.[Picker]>1 -- duplicate Provider/ProviderKey
AND T.[UserID]=@FromUserID -- safety check
THEN DELETE
WHEN MATCHED AND S.[Picker]=1 -- the only or best one
AND T.[UserID]=@FromUserID
THEN UPDATE SET T.[UserID]=@ToUserID
OUTPUT $action, DELETED.*, INSERTED.*;
Another way, if you want to create a new commit instead of performing a merge:
git checkout cleanchanges
git reset --hard master
git reset cleanchanges
git status
git add .
git commit
The first (hard) reset will set your working tree to the same as the last commit in master
.
The second reset will put your HEAD back where it was, pointing to the tip of the cleanchanges
branch, but without changing any files. So now you can add and commit them.
Afterwards, if you want to remove the dirty commits you made from master
(and assuming you have not already pushed them), you could:
git checkout master
git reset --hard origin/master
This will discard all your new commits, returning your local master
branch to the same commit as the one in the repository.
SELECT t1.credit,
t2.debit
FROM (SELECT Sum(c.total_amount) AS credit
FROM credit c
WHERE c.status = "a") AS t1,
(SELECT Sum(d.total_amount) AS debit
FROM debit d
WHERE d.status = "a") AS t2
Press Ctrl+C
When you start the server it mentions this in the startup text.
A combination of line styles, markers, and qualitative colors from matplotlib
:
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);
UPDATE: Supporting not only ListedColormap
, but also LinearSegmentedColormap
import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})
^ BRANCH Selector
git checkout HEAD^2
Selects the 2nd branch of a (merge) commit by moving onto the selected branch (one step backwards on the commit-tree)
~ COMMIT Selector
git checkout HEAD~2
Moves 2 commits backwards on the default/selected branch
Defining both ~ and ^ relative refs as PARENT selectors is far the dominant definition published everywhere on the internet I have come across so far - including the official Git Book. Yes they are PARENT selectors, but the problem with this "explanation" is that it is completely against our goal: which is how to distinguish the two... :)
The other problem is when we are encouraged to use the ^ BRANCH selector for COMMIT selection (aka HEAD^ === HEAD~).
Again, yes, you can use it this way, but this is not its designed purpose. The ^ BRANCH selector's backwards move behaviour is a side effect not its purpose.
At merged commits only, can a number be assigned to the ^ BRANCH selector. Thus its full capacity can only be utilised where there is a need for selecting among branches. And the most straightforward way to express a selection in a fork is by stepping onto the selected path / branch - that's for the one step backwards on the commit-tree. It is a side effect only, not its main purpose.
In the near future you may be able to use the ::marker
psuedo-element to achieve the same result as other solutions in just one line of code.
Remember to check the Browser Compatibility Table as this is still an experimental technology. At the moment of writing only Firefox and Firefox for Android, starting from version 68, support this.
Here is a snippet that will render correctly if tried in a compatible browser:
::marker { content: counters(list-item,'.') ':' }_x000D_
li { padding-left: 0.5em }
_x000D_
<ol>_x000D_
<li>li element_x000D_
<ol>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
</ol>_x000D_
</li>_x000D_
<li>li element</li>_x000D_
<li>li element_x000D_
<ol>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ol>
_x000D_
You may also want to check out this great article by smashingmagazine on the topic.
list comprehension formula:
[<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name]
thus you can do it like this:
[y for y in a if y not in b]
Only for demonstration purpose : [y if y not in b else False for y in a ]
For future readers:
To select manually the buttons with the trackball use:
myListView.setItemsCanFocus(true);
And to disable the focus on the whole list items:
myListView.setFocusable(false);
myListView.setFocusableInTouchMode(false);
myListView.setClickable(false);
It works fine for me, I can click on buttons with touchscreen and also alows focus an click using keypad
This may not be the answer you're looking for, but I'd recommend using the now community maintained repository Laravel Collective Forms & HTML as the main repositories have been deprecated.
Laravel Collective is in the process of updating their website. You may view the documentation on GitHub if needed.
I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like
I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context
kubectl config get-contexts
Sure, that is why python implements the following methods where the first parameter is a function:
Move your branch pointer to the HEAD:
git branch -f master
Your branch master
already exists, so git will not allow you to overwrite it, unless you use... -f
(this argument stands for --force
)
Or you can use rebase:
git rebase HEAD master
Do it on your own risk ;)
If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.
In C++, You are much better off using std::string and then you can use std::string::append()
1.Right click on your java project.
2.Select "RUN AS".
3.Select "RUN CONFIGURATIOS...".
4.Here select your server at left side of the page and then u would see "CLASS PATH" tab at riht side,just click on it.
5.Here clilck on "USER ENTRIES" and select "ADD EXTERNAL JARS".
6.Select "ojdbc14.jar" file.
7.Click on Apply.
8.Click on Run.
9.Finally Restart your server then it would be execute.
Not using Mutex though, simple answer:
System.Diagnostics;
...
string thisprocessname = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
Put it inside the Program.Main()
.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Sample
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//simple add Diagnostics namespace, and these 3 lines below
string thisprocessname = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Sample());
}
}
}
You can add MessageBox.Show
to the if
-statement and put "Application already running".
This might be helpful to someone.
Unfortunately, none of the solution listed here helped me to resolve this issue. I fixed this issue by using http://127.0.0.1 (ip address) instead of http://localhost. A quick little hack to work with angular development with chrome browser.
Functional Approach for ES6+
If you want to take a more functional approach to iterating over the Map
object, you can do something like this
const myMap = new Map()
myMap.forEach((value, key) => {
console.log(value, key)
})
This is what I came op for a thread safe bounded blocking queue.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
public class BlockingBuffer<T>
{
private Object t_lock;
private Semaphore sema_NotEmpty;
private Semaphore sema_NotFull;
private T[] buf;
private int getFromIndex;
private int putToIndex;
private int size;
private int numItems;
public BlockingBuffer(int Capacity)
{
if (Capacity <= 0)
throw new ArgumentOutOfRangeException("Capacity must be larger than 0");
t_lock = new Object();
buf = new T[Capacity];
sema_NotEmpty = new Semaphore(0, Capacity);
sema_NotFull = new Semaphore(Capacity, Capacity);
getFromIndex = 0;
putToIndex = 0;
size = Capacity;
numItems = 0;
}
public void put(T item)
{
sema_NotFull.WaitOne();
lock (t_lock)
{
while (numItems == size)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
buf[putToIndex++] = item;
if (putToIndex == size)
putToIndex = 0;
numItems++;
Monitor.Pulse(t_lock);
}
sema_NotEmpty.Release();
}
public T take()
{
T item;
sema_NotEmpty.WaitOne();
lock (t_lock)
{
while (numItems == 0)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
item = buf[getFromIndex++];
if (getFromIndex == size)
getFromIndex = 0;
numItems--;
Monitor.Pulse(t_lock);
}
sema_NotFull.Release();
return item;
}
}
This should be enough to force an IE
user to drop compatibility mode in any IE
version:
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
However, there are a couple of caveats one should be aware of:
<head>
. Only the <title>
tag may be placed above it.If you don't do that, you'll get an error on IE9
Dev Tools: X-UA-Compatible META tag ignored because document mode is already finalized.
If you want this markup to validate, make sure you remember to close the meta
tag with a />
instead of just >
.
Starting with IE11
, edge mode is the preferred document mode. To support/enable that, use the HTML5 document type declaration <!doctype html>
.
If you need to support webfonts on IE7
, make sure you use <!DOCTYPE html>
. I've tested it and found that rendering webfonts on IE7
got pretty unreliable when using <!doctype html>
.
The use of Google Chrome Frame is popular, but unfortunately it's going to be dropped sometime this month, Jan. 2014.
<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1">
Extensive related info here. The tip on using it as the first meta tag is on a previously mentioned source here, which has been updated.
if ( $("#txt").val().length > 0 )
{
// do something
}
Your method fails when there is more than 1 space character inside the textbox.
Ubuntu 17.10 default doesn't have the ~/.vimrc
file, we need create it and put the setting colorscheme color_scheme_name
in it.
By the way, colorscheme desert
is good scheme to choose.
Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method
setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'
import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))
Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499
So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.
I had trouble with changing the JFrame background as well and the above responses did not solve it entirely. I am using Eclipse. Adding a layout fixed the issue.
public class SampleProgram extends JFrame {
public SampleProgram() {
setSize(400,400);
setTitle("Sample");
getContentPane().setLayout(new FlowLayout());//specify a layout manager
getContentPane().setBackground(Color.red);
setVisible(true);
}
You can use a list comprehension:
[x for x in j if x >= 5]
Need to install jar files as well so that build can save memory in getting local jars.
Below command work for me after trying all those "MAVEN_OPTS" environment variable.
run "mvn clean install -U" on terminal from the root folder of the project.
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
Looks like YouTube has updated their JS API so this is available by default! You can use an existing YouTube iframe's ID...
<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>
...in your JS...
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange() {
//...
}
...and the constructor will use your existing iframe instead of replacing it with a new one. This also means you don't have to specify the videoId to the constructor.
Have you tried Hammerjs? It supports swipe gestures by using the velocity of the touch. http://eightmedia.github.com/hammer.js/
For my web application i corrected my mistake by writing
instead of : http://localhost:11472/authorize/
type : http://localhost/authorize/
Here is an example that shows the differences, which will help with the explanation.
var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;
String
is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2
in the example above creates a new string without the use of the new
keyword and without explicitly using the String
object.
string
is the TypeScript string type, which you can use to type variables, parameters and return values.
Additional notes...
Currently (Feb 2013) Both s1
and s2
are valid JavaScript. s3
is valid TypeScript.
Use of String
. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:
var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();
If you really had a penchant for the string, you could use it in TypeScript in one of two ways...
var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type
Not sure if this helps anyone, but I had the same issue and could not find the process that was holding me up. I closed SSMS and stopped all the services hitting the local instance. Then once I went back in and ran the exec sp_who2, it showed me the culprit. I killed the process and was able to get the Multi_User to work, then restart the services. We had IIS hitting it every few minutes/seconds looking for certain packages.
For those who are wondering why this works in Java but not C#, consider what happens if some doof wrote this class:
public class Trololol : ISignatur<bool>, ISignatur<int>{
Type ISignatur<bool>.Type => typeof(bool);
Type ISignatur<int>.Type => typeof(int);
}
How is the compiler supposed to resolve var access = service.Get(new Trololol())
? Both int
and bool
are valid.
The reason this implicit resolution works in Java likely has to do with Erasure and how Java will throw a fit if you try to implement an interface with two or more different type arguments. Such a class is simply not allowed in Java, but is just fine in C#.
Think of a jar file as the root of a directory structure. Yes, you need to add them all separately.
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
This is working for me It's very simple
return $.ajax({
type: 'POST',
url: urlBaseUrl
data: {someData:someData},
dataType: "json",
success: function(resultData) {
}
});
check https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutbyExample/AutoLayoutbyExample.html having nice description about solving your problem.
By using the :last-child selector?
Do you have a specific scenario in mind you need assistance with?
This tutorial gives a simple, yet elegant, solution, which i transcribe:
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
...
std::string my_val = stringify(val);
Depends what you mean by local:
If by local you mean the address of the server/system executing the PHP code, then there are still two avenues to discuss. If PHP is being run through a web server, then you can get the server address by reading $_SERVER['SERVER_ADDR']
. If PHP is being run through a command line interface, then you would likely have to shell-execute ipconfig
(Windows) / ifconfig
(*nix) and grep out the address.
If by local you mean the remote address of the website visitor, but not their external IP address (since you specifically said 192.*), then you are out of luck. The whole point of NAT routing is to hide that address. You cannot identify the local addresses of individual computers behind an IP address, but there are some tricks (user agent, possibly mac address) that can help differentiate if there are multiple computers accessing from the same IP.
Because System.exit()
is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit()
method. It is standard for 0
to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.
return
on the other hand is a reserved key word that the compiler knows well.
return
returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void
as you have not supplied anything to return.
Obfuscate the code! There is an example in Obfuscating C# Code.
You don't pass n
itself, but rather range(n)
[the list of integers from 0 to n-1 included], from your view to your template, and in the latter you do {% for i in therange %}
(if you absolutely insist on 1-based rather than the normal 0-based index you can use forloop.counter
in the loop's body;-).
This relatively recent article provides a simple example with a limited Google Maps set of colored icons.
for getting Hash map first element you can use bellow code in kotlin:
val data : Float = hashMap?.get(hashMap?.keys?.first())
<p id="text" onclick="func()">
Click on text to change
</p>
<script>
function func()
{
document.getElementById("text").style.color="red";
document.getElementById("text").style.font="calibri";
}
</script>
My guess is that the folder you are trying to add already exists in SVN. You can confirm by checking out the files to a different folder and see if trunk already has the required folder.
Working with atom (1.21.1 ia32)... i got the same error, even though i added a reference to my pipe in the app.module.ts and in the declarations within app.module.ts
solution was to restart my node instance... stopping the website and then doing ng serve again... going to localhost:4200 worked like a charm after this restart
If you want to use plain javascript, but avoid promises, you can use Rami Sarieddine's solution, but substitute the promise with a callback function like this:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
And you would call it like this:
getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert('Your Json result is: ' + data.result);
result.innerText = data.result;
}
});
Easy way to achieve this in angular 2 or 4 (Assuming that you are using bootstrap 4)
Component.html
<button type="button" (click)="openModel()">Open Modal</button>_x000D_
_x000D_
<div #myModel class="modal fade">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<h5 class="modal-title ">Title</h5>_x000D_
<button type="button" class="close" (click)="closeModel()">_x000D_
<span aria-hidden="true">×</span>_x000D_
</button>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Component.ts
import {Component, OnInit, ViewChild} from '@angular/core';
@ViewChild('myModal') myModal;
openModel() {
this.myModal.nativeElement.className = 'modal fade show';
}
closeModel() {
this.myModal.nativeElement.className = 'modal hide';
}
I recommend using the emulator by Genymotion instead of Google's emulators. It launches way faster and responds almost in real-time. It also supports Google Play Services and therefore Google Maps.
Give it a try! Here is a blog post which helps you setting up the emulator.
As easy as
SELECT lpad(42::text, 4, '0')
References:
sqlfiddle: http://sqlfiddle.com/#!15/d41d8/3665
Just divide the number of td to 100%. Example, you have 4 td's:
<html>
<table>
<tr>
<td style="width:25%">This is a text</td>
<td style="width:25%">This is some text, this is some text</td>
<td style="width:25%">This is another text, this is another text</td>
<td style="width:25%">This is the last text, this is the last text</td>
</tr>
</table>
</html>
We use 25% in each td to maximize the 100% space of the entire table
As suggested in "PostgreSQL database default location on Linux", under Linux you can find out using the following command:
ps aux | grep postgres | grep -- -D
I have also encountered this error . Just i opened the new window ie Window -> New Window in eclipse .Then , I closed my old window. This solved my problem.
I think you can leverage the [Zip File System Provider][1] to achieve this. When using FileSystems.newFileSystem
it looks like you can treat the objects in that ZIP as a "regular" file.
In the linked documentation above:
Specify the configuration options for the zip file system in the java.util.Map object passed to the
FileSystems.newFileSystem
method. See the [Zip File System Properties][2] topic for information about the provider-specific configuration properties for the zip file system.Once you have an instance of a zip file system, you can invoke the methods of the [
java.nio.file.FileSystem
][3] and [java.nio.file.Path
][4] classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.
The documentation for the jdk.zipfs
module in [Java 11 states][5]:
The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider can be created by [
FileSystems.newFileSystem
][6] if installed.
Here is a contrived example I did using your example resources. Note that a .zip
is a .jar
, but you could adapt your code to instead use classpath resources:
Setup
cd /tmp
mkdir -p x/y/z
touch x/y/z/{a,b,c}.html
echo 'hello world' > x/y/z/d
zip -r example.zip x
Java
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Collections;
import java.util.stream.Collectors;
public class MkobitZipRead {
public static void main(String[] args) throws IOException {
final URI uri = URI.create("jar:file:/tmp/example.zip");
try (
final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
) {
Files.walk(zipfs.getPath("/")).forEach(path -> System.out.println("Files in zip:" + path));
System.out.println("-----");
final String manifest = Files.readAllLines(
zipfs.getPath("x", "y", "z").resolve("d")
).stream().collect(Collectors.joining(System.lineSeparator()));
System.out.println(manifest);
}
}
}
Output
Files in zip:/
Files in zip:/x/
Files in zip:/x/y/
Files in zip:/x/y/z/
Files in zip:/x/y/z/c.html
Files in zip:/x/y/z/b.html
Files in zip:/x/y/z/a.html
Files in zip:/x/y/z/d
-----
hello world
Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer
And another solution (the quick way) for those who can afford running 'file' command within python, run:
import os
info = os.popen("file foo.jpg").read()
print info
Output:
foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3
All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.
In my project with netcore 2.2 I use this code:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
OkObjectResult result = Ok( payload );
// currently result.Formatters is empty but we'd like to ensure it will be so in the future
result.Formatters.Clear();
// force response as xml
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
It forces only one action within a controller to return a xml without effect to other actions. Also this code doesn't contain neither HttpResponseMessage or StringContent or ObjectContent which are disposable objects and hence should be handled appropriately (it is especially a problem if you use any of code analyzers that reminds you about it).
Going further you could use a handy extension like this:
public static class ObjectResultExtensions
{
public static T ForceResultAsXml<T>( this T result )
where T : ObjectResult
{
result.Formatters.Clear();
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
}
And your code will become like this:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
return Ok( payload ).ForceResultAsXml();
}
In addition, this solution looks like an explicit and clean way to force return as xml and it is easy to add to your existent code.
P.S. I used fully-qualified name Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter just to avoid ambiguity.
i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');
I noticed that leowebdev's post did seem to work on my end, however, it did knock out two elements of the site that I am trying to make: the scrolling and the footer.
The scrolling I got back by adding a
scrolling="yes"
To the iframe embed code.
I am not sure if the footer is automatically knocked out because of the responsiveness or not, but hopefully someone else knows that answer.
This worked for me:
#include <iostream>
#include <pthread.h>
using namespace std;
void* print_message(void*) {
cout << "Threading\n";
}
int main() {
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
// Optional.
void* result;
pthread_join(t1,&result);
// :~
return 0;
}
You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:
public class ProgramViwer : Form{
public ProgramViwer()
{
InitializeComponent();
Load += new EventHandler(ProgramViwer_Load);
}
private void ProgramViwer_Load(object sender, System.EventArgs e)
{
formPanel.Controls.Clear();
formPanel.Controls.Add(wel);
}
}
I'm using Alibaba fastjson, easy and simple:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>VERSION_CODE</version>
</dependency>
and import:
import com.alibaba.fastjson.JSON;
Then:
String text = JSON.toJSONString(obj); // serialize
VO vo = JSON.parseObject("{...}", VO.class); //unserialize
Everything is ok.
The equals()
of arrays is inherited from Object
, so it does not look at the contents of the arrrays, it only considers each array equal to itself.
The Arrays.equals()
methods do compare the arrays' contents. There's overloads for all primitive types, and the one for objects uses the objects' own equals()
methods.
json_encode($response, JSON_UNESCAPED_SLASHES);
l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.
los.Aggregate((current, next) => current + "," + next);
You cannot just put in a function to pause Javascript unfortunately.
You have to use setTimeout()
Example:
function startTimer () {
timer.start();
setTimeout(stopTimer,5000);
}
function stopTimer () {
timer.stop();
}
EDIT:
For your user generated countdown, it is just as simple.
HTML:
<input type="number" id="delay" min="1" max="5">
JS:
var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;
function startTimer () {
timer.start();
setTimeout(stopTimer,delayInMilliseconds);
}
function stopTimer () {
timer.stop;
}
Now you simply need to add a trigger for startTimer()
, such as onchange
.
Your @Entity
class has a String
type for its @Id
field, so it can't generate ids for you.
If you change it to an auto increment in the DB and a Long
in java, and add the @GeneratedValue
annotation:
@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;
it will handle incrementing id generation for you.
You need to be running a mail server locally. If this is Unix, enable sendmail If this is Windows install the Simple Mail Transfer Server (not sure if the name is correct) component of IIs. E.g. for windows 2003 follow this: http://msdn.microsoft.com/en-us/library/8b83ac7t.aspx
Solution:
echo
parse_url
($_SERVER["REQUEST_URI"], PHP_URL_PATH);
One way is to use ANSI escape sequences:
import sys
import time
for i in range(10):
print("Loading" + "." * i)
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(1)
Also sometimes useful (for example if you print something shorter than before):
sys.stdout.write("\033[K") # Clear to the end of line
The accepted answer is not ideal, so I decided to add my 2 cents
timeStamp.toLocalDateTime().toLocalDate();
is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.
The good solution is
timestamp.toInstant().atZone(zoneId).toLocalDate()
Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC
The general approach should be
However, if you want to do it anyway, search for regex pattern
<primaryAddress>[\s\S]*?<\/primaryAddress>
and replace it with empty string...
This page explains it pretty well.
As a numeric
the allowable range that can be stored in that field is -10^38 +1
to 10^38 - 1
.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1)
to (10^18 - 1)
Or -999999999999999999
to 999999999999999999
Integers only
I suspect you are having a problem with factors. For example,
> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8
Some comments:
as.numeric
to do with these values?read.csv
, try using the argument stringsAsFactors=FALSE
sep="/t
and not sep="\t"
head(pitchman)
to check the first fews rows of your datapichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
since I don't have access to the data set.EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
Javascript using the onLoad()
event, will wait for the page to be loaded before executing.
<body onload="somecode();" >
If you're using the jQuery framework's document ready function the code will load as soon as the DOM is loaded and before the page contents are loaded:
$(document).ready(function() {
// jQuery code goes here
});
This warning is issued due the security features, do not disable this feature.
It's just displayed once.
If it still appears after second connection, the problem is probably in writing to the known_hosts
file.
In this case you'll also get the following message:
Failed to add the host to the list of known hosts
You may fix it by changing owner of changing the permissions of the file to be writable by your user.
sudo chown -v $USER ~/.ssh/known_hosts
Horizontal ProgressBar
uses rectangle shape
drawable for background, ClipDrawable
constructed from rectangle shape
for progresses (primary & secondary). Tinting changes colors to some tint. If you want targeted colors for all three separately then you can use ProgressBar.setProgressDrawable()
as following:
LayerDrawable progressBarDrawable = new LayerDrawable(
new Drawable[]{
new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
new int[]{Color.parseColor("#ff0000ff"),Color.parseColor("#ff0000ff")}),
new ClipDrawable(
new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
new int[]{Color.parseColor("#ff00ff00"),Color.parseColor("#ff00ff00")}),
Gravity.START,
ClipDrawable.HORIZONTAL),
new ClipDrawable(
new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
new int[]{Color.parseColor("#ffff0000"),Color.parseColor("#ffff0000")}),
Gravity.START,
ClipDrawable.HORIZONTAL)
});
progressBarDrawable.setId(0,android.R.id.background);
progressBarDrawable.setId(1,android.R.id.secondaryProgress);
progressBarDrawable.setId(2,android.R.id.progress);
((ProgressBar)findViewById(R.id.progressBar)).setProgressDrawable(progressBarDrawable);
Note that order of drawable layers is important while initializing LayerDrawable
. First drawable should be for background. As per my experiment switching ids does not work. If you set padding to progressbar
then this approach will not work. If you need padding then you can use a container for the progressbar such as a LinearLayout
.
Some might find my function useful if you just want to print out all of the tables and columns in your db.
In the loop, I query each TABLE with LIMIT 0 so it just returns the header info without all the data. You make an empty df out of it, and use the iterable df.columns to print each column name out.
conn = sqlite3.connect('example.db')
c = conn.cursor()
def table_info(c, conn):
'''
prints out all of the columns of every table in db
c : cursor object
conn : database connection object
'''
tables = c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
for table_name in tables:
table_name = table_name[0] # tables is a list of single item tuples
table = pd.read_sql_query("SELECT * from {} LIMIT 0".format(table_name), conn)
print(table_name)
for col in table.columns:
print('\t-' + col)
print()
table_info(c, conn)
Results will be:
table1
-column1
-column2
table2
-column1
-column2
-column3
etc.
Tools --> Options --> Designers node --> Uncheck " Prevent saving changes that require table recreation ".
I really needed to do this dirty thing... Here is how
I redefined those dependencies with scope test
. Scope provided
did not work for me.
We use spring Boot plugin to build fat jar. We have module common which defines common libraries, for example Springfox swagger-2. My super-service needs to have parent common (it does not want to do so, but company rules force!)
So my parent or commons has pom.
<dependencyManagement>
<!- I do not need Springfox in one child but in others ->
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>${swagger.version}</version>
</dependency>
<!- All services need them ->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${apache.poi.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
And my super-service pom.
<name>super-service</name>
<parent>
<groupId>com.company</groupId>
<artifactId>common</artifactId>
<version>1</version>
</parent>
<dependencies>
<!- I don't need them ->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>2.8.0</version>
<scope>test</scope>
</dependency>
<!- Required dependencies ->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
</dependencies>
This is size of the final fat artifact
82.3 MB (86,351,753 bytes) - redefined dependency with scope test
86.1 MB (90,335,466 bytes) - redefined dependency with scope provided
86.1 MB (90,335,489 bytes) - without exclusion
Also this answer is worth mentioning - I wanted to do so, but I am lazy... https://stackoverflow.com/a/48103554/4587961
Can you get round this by calling System.load() programmatically to load your native library? This method (unlike System.loadLibrary()) allows you to specify an absolute path.
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
Have you thought about using the TAG "dt" instead of "ul" for nesting lists? It's inherit style and structure allow you to have a title per section and it automatically tabulates the content that goes inside.
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
VS
<ul>
<li>Choice A</li>
<li>Choice B
<ul>
<li>Sub 1</li>
<li>Sub 2</li>
</ul>
</li>
</ul>
Try this:
final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
public void onLongPress(MotionEvent e) {
Log.e("", "Longpress detected");
}
});
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
};
Live Demo : http://jsfiddle.net/abdennour/ba54W/
$(document).ready(function() {
$("#textA").bind({
copy : function(){
$('span').text('copy behaviour detected!');
},
paste : function(){
$('span').text('paste behaviour detected!');
},
cut : function(){
$('span').text('cut behaviour detected!');
}
});
});
if you have Firebug installed on Firefox, just open the url. In the network panel, right-click and select Copy as cURL. You can see all curl parameters for this web call.
Yes, the value returned is the value after and before the incrementation, respectively.
class Foo {
public static void main(String args[]) {
int x = 1;
int a = x++;
System.out.println("a is now " + a);
x = 1;
a = ++x;
System.out.println("a is now " + a);
}
}
$ java Foo
a is now 1
a is now 2
As I understand it, loadData()
simply generates a data:
URL with the data provide it.
Read the javadocs for loadData()
:
If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.
Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):
String data = ...; // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");
While using Google reCaptcha with reCaptcha DLL file, we can validate it in C# as follows :
RecaptchaControl1.Validate();
bool _Varify = RecaptchaControl1.IsValid;
if (_Varify)
{
// Pice of code after validation.
}
Its works for me.
The Array index only accepts a long value.
You declared iCounter as an integer. You should declare it as a long.
The safest way to do this is to prompt for the password beforehand and then pipe it into the command. Prompting for the password will avoid having the password saved anywhere in your code and it also won't show up in your bash history. Here's an example:
from getpass import getpass
from subprocess import Popen, PIPE
password = getpass("Please enter your password: ")
# sudo requires the flag '-S' in order to take input from stdin
proc = Popen("sudo -S apach2ctl restart".split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())
Yup, often called a 'cookie jar' Google should provide many examples:
http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/
http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO
Copying that last one here so it does not go away...
Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell
<?php
/*
This script is an example of using curl in php to log into on one page and
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into
thinking its netscape and even pass a fake referer, yo look like it surfed
from a local page.
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");
ob_start(); // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean(); // stop preventing output
curl_close ($ch);
unset($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");
$buf2 = curl_exec ($ch);
curl_close ($ch);
echo "<PRE>".htmlentities($buf2);
?>
Try doing something like this:
Pattern p = Pattern.compile("^.+(\\d+).+");
Matcher m = p.matcher("Testing123Testing");
if (m.find()) {
System.out.println(m.group(1));
}
Couldn't get the accepted answer to work. Then found out that actually the solution is much simpler anyway as Ghostscript not just natively supports PNG but even multiple different "encodings":
png256
png16
pnggray
pngmono
The shell command that works for me is:
gs -dNOPAUSE -q -sDEVICE=pnggray -r500 -dBATCH -dFirstPage=2 -dLastPage=2 -sOutputFile=test.png test.pdf
It will save page 2 of test.pdf to test.png using the pnggray
encoding and 500 DPI.
You may also permanently (after reboots) add to the Path variable this way:
Right click My Computer -> Click Properties -> Click Advanced system settings -> Click Environment Variables
Reference: Change System/User Variables
If you don't use the STL, then the code looks a lot bit like C.
#include <cstdlib>
#include <new>
template< class T >
void append_to_array( T *&arr, size_t &n, T const &obj ) {
T *tmp = static_cast<T*>( std::realloc( arr, sizeof(T) * (n+1) ) );
if ( tmp == NULL ) throw std::bad_alloc( __FUNCTION__ );
// assign things now that there is no exception
arr = tmp;
new( &arr[ n ] ) T( obj ); // placement new
++ n;
}
T
can be any POD type, including pointers.
Note that arr
must be allocated by malloc
, not new[]
.
Have you take a look Google Maps Geolocation Api? Google Map Geolocation
This is simple RestApi, you just need POST a request, the the service will return a location with accuracy in meters.
The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):
Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.
For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.
These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '
), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "
), or (iv) unquoted — with the following restrictions:
... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.
<> means not equal. however, in some versions of SQL, you can write !=
set nocount on
the quotes are there, use -w2000 to keep each row on one line.
Here's some code. This assumes you are doing this on a form, or a UserControl.
Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");
int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));
From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.
@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;
public void clickOnSubmitButton() {
submitButton.click();
}
Maybe this can help you
Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i] = c.getInt(c.getColumnIndex("field_name"));
i++;
} while (c.moveToNext());
c.close();
}
If you have a path with spaces you must surround it with quotation marks (").
Not sure if that's exactly what you're asking though?
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class HeightAnimation extends Animation {
protected final int originalHeight;
protected final View view;
protected float perValue;
public HeightAnimation(View view, int fromHeight, int toHeight) {
this.view = view;
this.originalHeight = fromHeight;
this.perValue = (toHeight - fromHeight);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
view.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
}
uss to:
HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);
It's worth noting some other things:
As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.
In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.
AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.
Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.
I don't know the impact upon an installer of using something other than numeric file version numbers, though.
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.
Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.
For any OS
This helped me so I'll put it here, just in case.
Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh
directory for both the accounts (.ssh/config
)
# First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_user1
# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_user2
Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from
git config user.email
Suppose this returns the first user email and you want to push from the second user. Change the local user.name
and user.email
:
git config user.name "SECOND_USER"
git config user.email "[email protected]"
(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email
and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add
, git commit
and git push
.
To push from the first user, change the local user.name
again and follow the same steps.
Hope it helps :)
If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:
Then, clear your ssh cached keys Reference
ssh-add -D
Then add you 2 ssh keys
ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2
Then type in your terminal:
ssh -T [email protected]<SECOND_ACCOUNT_USERNAME_HERE>
You should see the following output:
Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.
Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config
file next to Host
. In the following case [email protected]<SECOND_ACCOUNT_USERNAME_HERE>
.
git remote rm origin
git remote add origin [email protected]<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git
If You are using eclipse then the following steps will solve your problem:
Go to Run -> Run Configurations -> Main Class Search -> Locate your class manually -> Apply -> Run
It worked to me only using a specific service.
For example instead of use:
compile 'com.google.android.gms:play-services:10.0.1'
I used:
com.google.android.gms:play-services-places:10.0.1
$(':checkbox').change(function(){
$('#delete').removeAttr('hidden');
});
Note, thanks to tip by A.Wolff
, you should use removeAttr
instead of setting to false. When set to false, the element will still be hidden. Therefore, removing is more effective.
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
http://www.bsourcecode.com/codeigniter/codeigniter-select-query/
$query = $this->db->query("select * from tbl_user");
OR
$query = $this->db->select("*");
$this->db->from('table_name');
$query=$this->db->get();
Are you sure you're using the correct proxy as system properties?
Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:
//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
Python doesn't have such types as you describe. There are two types used to represent integral values: int
, which corresponds to platform's int type in C, and long
, which is an arbitrary precision integer (i.e. it grows as needed and doesn't have an upper limit). int
s are silently converted to long
if an expression produces result which cannot be stored in int
.
The problem you're having is that the output you get into the variable 's' is not a csv, but a html file. In order to get the raw csv, you have to modify the url to:
'https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv'
Your second problem is that read_csv expects a file name, we can solve this by using StringIO from io module. Third problem is that request.get(url).content delivers a byte stream, we can solve this using the request.get(url).text instead.
End result is this code:
from io import StringIO
import pandas as pd
import requests
url='https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv'
s=requests.get(url).text
c=pd.read_csv(StringIO(s))
output:
>>> c.head()
Country Region
0 Algeria AFRICA
1 Angola AFRICA
2 Benin AFRICA
3 Botswana AFRICA
4 Burkina AFRICA
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
This simple solution posted here Force page refresh on back button worked ...
I've tried to force a page to be downloaded again by browser when user clicks back button, but nothing worked. I appears that modern browsers have separate cache for pages, which stores complete state of a page (including JavaScript generated DOM elements), so when users presses back button, previous page is shown instantly in state the user has left it. If you want to force browser to reload page on back button, add onunload="" to your (X)HTML body element:
<body onunload="">
This disables special cache and forces page reload when user presses back button. Think twice before you use it. Fact of needing such solution is a hint your site navigation concept is flawed.
Most of the answers here are wrong for one of two reasons:
Percona has a blog post about how to do this well: https://www.percona.com/blog/2013/12/24/renaming-database-schema-mysql/
and script posted (made?) by Simon R Jones that does what is suggested in that post. I fixed a bug I found in the script. You can see it here:
https://gist.github.com/ryantm/76944318b0473ff25993ef2a7186213d
Here is a copy of it:
#!/bin/bash
# Copyright 2013 Percona LLC and/or its affiliates
# @see https://www.percona.com/blog/2013/12/24/renaming-database-schema-mysql/
set -e
if [ -z "$3" ]; then
echo "rename_db <server> <database> <new_database>"
exit 1
fi
db_exists=`mysql -h $1 -e "show databases like '$3'" -sss`
if [ -n "$db_exists" ]; then
echo "ERROR: New database already exists $3"
exit 1
fi
TIMESTAMP=`date +%s`
character_set=`mysql -h $1 -e "SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '$2'" -sss`
TABLES=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'" -sss`
STATUS=$?
if [ "$STATUS" != 0 ] || [ -z "$TABLES" ]; then
echo "Error retrieving tables from $2"
exit 1
fi
echo "create database $3 DEFAULT CHARACTER SET $character_set"
mysql -h $1 -e "create database $3 DEFAULT CHARACTER SET $character_set"
TRIGGERS=`mysql -h $1 $2 -e "show triggers\G" | grep Trigger: | awk '{print $2}'`
VIEWS=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='VIEW'" -sss`
if [ -n "$VIEWS" ]; then
mysqldump -h $1 $2 $VIEWS > /tmp/${2}_views${TIMESTAMP}.dump
fi
mysqldump -h $1 $2 -d -t -R -E > /tmp/${2}_triggers${TIMESTAMP}.dump
for TRIGGER in $TRIGGERS; do
echo "drop trigger $TRIGGER"
mysql -h $1 $2 -e "drop trigger $TRIGGER"
done
for TABLE in $TABLES; do
echo "rename table $2.$TABLE to $3.$TABLE"
mysql -h $1 $2 -e "SET FOREIGN_KEY_CHECKS=0; rename table $2.$TABLE to $3.$TABLE"
done
if [ -n "$VIEWS" ]; then
echo "loading views"
mysql -h $1 $3 < /tmp/${2}_views${TIMESTAMP}.dump
fi
echo "loading triggers, routines and events"
mysql -h $1 $3 < /tmp/${2}_triggers${TIMESTAMP}.dump
TABLES=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'" -sss`
if [ -z "$TABLES" ]; then
echo "Dropping database $2"
mysql -h $1 $2 -e "drop database $2"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.columns_priv where db='$2'" -sss` -gt 0 ]; then
COLUMNS_PRIV=" UPDATE mysql.columns_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.procs_priv where db='$2'" -sss` -gt 0 ]; then
PROCS_PRIV=" UPDATE mysql.procs_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.tables_priv where db='$2'" -sss` -gt 0 ]; then
TABLES_PRIV=" UPDATE mysql.tables_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.db where db='$2'" -sss` -gt 0 ]; then
DB_PRIV=" UPDATE mysql.db set db='$3' WHERE db='$2';"
fi
if [ -n "$COLUMNS_PRIV" ] || [ -n "$PROCS_PRIV" ] || [ -n "$TABLES_PRIV" ] || [ -n "$DB_PRIV" ]; then
echo "IF YOU WANT TO RENAME the GRANTS YOU NEED TO RUN ALL OUTPUT BELOW:"
if [ -n "$COLUMNS_PRIV" ]; then echo "$COLUMNS_PRIV"; fi
if [ -n "$PROCS_PRIV" ]; then echo "$PROCS_PRIV"; fi
if [ -n "$TABLES_PRIV" ]; then echo "$TABLES_PRIV"; fi
if [ -n "$DB_PRIV" ]; then echo "$DB_PRIV"; fi
echo " flush privileges;"
fi
Save it to a file called rename_db
and make the script executable with chmod +x rename_db
then use it like ./rename_db localhost old_db new_db
var defaultSettings = {
ajaxsettings: {},
uisettings: {}
};
Take a look at this site: http://www.json.org/
Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.
You can use the:
setBackgroundDrawable(null);
method.And following is the doc:
/**
* Set the background to a given Drawable, or remove the background. If the
* background has padding, this View's padding is set to the background's
* padding. However, when a background is removed, this View's padding isn't
* touched. If setting the padding is desired, please use
* {@link #setPadding(int, int, int, int)}.
*
* @param d The Drawable to use as the background, or null to remove the
* background
*/
You can probably start a Service
here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.
UDPATE
You can use START_STICKY
to make your Service running continuously.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
2015-05-27-191152.jpg << Looking back at your image format, I occasionally confused between .png and .jpg and encountered the same error.
Visual Event is a nice little bookmarklet that you can use to view an element's event handlers. On online demo can be viewed here.
<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" />
</form>
change the request method to' POST' instead of 'GET'.