At first you should check your test logic. Usually there are 3 cases. First, you are mocking wrong method (you made a typo or someone changed tested code so that mocked method is no longer used). Second, your test is failing before this method is called. Third, you logic falls in wrong if/switch branch somewhere in the code so that mocked method is no called.
If this is first case you always want to change mocked method for the one used in the code. With second and the third it depends. Usually you should just delete this mock if it has no use. But sometimes there are certain cases in parametrized tests, which should take this different path or fail earlier. Then you can split this test into two or more separate ones but that's not always good looking. 3 test methods with possibly 3 arguments providers can make you test look unreadable. In that case for JUnit 4 you silent this exception with either
@RunWith(MockitoJUnitRunner.Silent.class)
annotation or if you are using rule approach
@Rule
public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.LENIENT);
or (the same behaviour)
@Rule
public MockitoRule rule = MockitoJUnit.rule().silent();
For JUnit 5 tests you can silent this exception using annotation provided in mockito-junit-jupiter
package.
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class JUnit5MockitoTest {
}
It work's using rules
instead of loaders
module : {
rules : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel-loader'
}
]
}
MongoDB needs a folder to store the database. Create a C:\data\db\
directory:
mkdir C:\data\db
and then start MongoDB:
C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe
Sometimes C:\data\db
folder already exists due to previous installation. So if for this reason mongod.exe
does not work, you may delete all the contents from C:\data\db
folder and execute mongod.exe
again.
Nobody has mention this in. above answers so i am mentioning it.
This error can also come if you're in the wrong folder or path of your pem file is not correct. I was having similar issue and found that my pem file was not there from where i am executing the ssh command
cd KeyPair
ssh -i Keypair.pem [email protected]
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied
.
One thing you can try is doing a user install of the package with pip install lxml --user
. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)
You can also run pip install
as a superuser with sudo pip install lxml
but it is not generally a good idea because it can cause issues with your system-level packages.
Remove all the texts in android/settings.gradle and paste the below code
rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned
Removing few react-native dependencies solved the problem
Deleting these lines the problem is resolved. This line is created by rnpm link but is a bug.
compile project(':react-native-gps')
compile project(':react-native-maps')
I would like to read the versionCode from an external file
I am sure that there are any number of possible solutions; here is one:
android {
compileSdkVersion 18
buildToolsVersion "18.1.0"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def code = versionProps['VERSION_CODE'].toInteger() + 1
versionProps['VERSION_CODE']=code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
versionCode code
versionName "1.1"
minSdkVersion 14
targetSdkVersion 18
}
}
else {
throw new GradleException("Could not read version.properties!")
}
// rest of android block goes here
}
This code expects an existing version.properties
file, which you would create by hand before the first build to have VERSION_CODE=8
.
This code simply bumps the version code on each build -- you would need to extend the technique to handle your per-flavor version code.
You can see the Versioning sample project that demonstrates this code.
You have to add repositories
to your build file. For maven repositories you have to prefix repository name with maven{}
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
Instruct Gradle to download Android plugin from Maven Central repository.
You do it by pasting the following code at the beginning of the Gradle build file:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.1'
}
}
Replace version string 1.0.+
with the latest version. Released versions of Gradle plugin can be found in official Maven Repository or on MVNRepository artifact search.
You must check if the same JAR is being imported again. In my case there was a class inside a jar which was getting imported in another jar. So just check if the any lib / class file is being included twice in the whole project!
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
I believe that phrase should have been worded as follows:
bcrypt has salts built into the generated hashes to prevent rainbow table attacks.
The bcrypt
utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt
). Put another way, the "hash" generated by bcrypt
is not just the hash. Rather, it is the hash and the salt concatenated.
With Java 9, Java 8u161, Java 7u171 and Java 6u181 the limitation is now disabled by default. See issue in Java Bug Database.
Beginning with Java 8u151 you can disable the limitation programmatically.
In older releases, JCE jurisdiction files had to be downloaded and installed separately to allow unlimited cryptography to be used by the JDK. The download and install steps are no longer necessary.
Instead you can now invoke the following line before first use of JCE classes (i.e. preferably right after application start):
Security.setProperty("crypto.policy", "unlimited");
Make sure that you're using the latest version of JSch. I had this exact same problem when using JSch 0.1.31 and trying to connect to a RedHat 5 server. Updating to the latest version solved the problem.
You can't depend on the file having a BOM. UTF-8 doesn't require it. And non-Unicode encodings don't even have a BOM. There are, however, other ways to detect the encoding.
BOM is 00 00 FE FF (for BE) or FF FE 00 00 (for LE).
But UTF-32 is easy to detect even without a BOM. This is because the Unicode code point range is restricted to U+10FFFF, and thus UTF-32 units always have the pattern 00 {00-10} xx xx (for BE) or xx xx {00-10} 00 (for LE). If the data has a length that's a multiple of 4, and follows one of these patterns, you can safely assume it's UTF-32. False positives are nearly impossible due to the rarity of 00 bytes in byte-oriented encodings.
No BOM, but you don't need one. ASCII can be easily identified by the lack of bytes in the 80-FF range.
BOM is EF BB BF. But you can't rely on this. Lots of UTF-8 files don't have a BOM, especially if they originated on non-Windows systems.
But you can safely assume that if a file validates as UTF-8, it is UTF-8. False positives are rare.
Specifically, given that the data is not ASCII, the false positive rate for a 2-byte sequence is only 3.9% (1920/49152). For a 7-byte sequence, it's less than 1%. For a 12-byte sequence, it's less than 0.1%. For a 24-byte sequence, it's less than 1 in a million.
BOM is FE FF (for BE) or FF FE (for LE). Note that the UTF-16LE BOM is found at the start of the UTF-32LE BOM, so check UTF-32 first.
If you happen to have a file that consists mainly of ISO-8859-1 characters, having half of the file's bytes be 00 would also be a strong indicator of UTF-16.
Otherwise, the only reliable way to recognize UTF-16 without a BOM is to look for surrogate pairs (D[8-B]xx D[C-F]xx), but non-BMP characters are too rarely-used to make this approach practical.
If your file starts with the bytes 3C 3F 78 6D 6C (i.e., the ASCII characters "<?xml"), then look for an encoding=
declaration. If present, then use that encoding. If absent, then assume UTF-8, which is the default XML encoding.
If you need to support EBCDIC, also look for the equivalent sequence 4C 6F A7 94 93.
In general, if you have a file format that contains an encoding declaration, then look for that declaration rather than trying to guess the encoding.
There are hundreds of other encodings, which require more effort to detect. I recommend trying Mozilla's charset detector or a .NET port of it.
If you've ruled out the UTF encodings, and don't have an encoding declaration or statistical detection that points to a different encoding, assume ISO-8859-1 or the closely related Windows-1252. (Note that the latest HTML standard requires a “ISO-8859-1” declaration to be interpreted as Windows-1252.) Being Windows' default code page for English (and other popular languages like Spanish, Portuguese, German, and French), it's the most commonly encountered encoding other than UTF-8.
You need to change the sshd_config
file in the remote server (probably in /etc/ssh/sshd_config
).
Change
PasswordAuthentication no
to
PasswordAuthentication yes
And then restart the sshd
daemon.
Have you considered using the CCR since you are writing to separate files you can do everything in parallel (read and write) and the CCR makes it very easy to do this.
static void Main(string[] args)
{
Dispatcher dp = new Dispatcher();
DispatcherQueue dq = new DispatcherQueue("DQ", dp);
Port<long> offsetPort = new Port<long>();
Arbiter.Activate(dq, Arbiter.Receive<long>(true, offsetPort,
new Handler<long>(Split)));
FileStream fs = File.Open(file_path, FileMode.Open);
long size = fs.Length;
fs.Dispose();
for (long i = 0; i < size; i += split_size)
{
offsetPort.Post(i);
}
}
private static void Split(long offset)
{
FileStream reader = new FileStream(file_path, FileMode.Open,
FileAccess.Read);
reader.Seek(offset, SeekOrigin.Begin);
long toRead = 0;
if (offset + split_size <= reader.Length)
toRead = split_size;
else
toRead = reader.Length - offset;
byte[] buff = new byte[toRead];
reader.Read(buff, 0, (int)toRead);
reader.Dispose();
File.WriteAllBytes("c:\\out" + offset + ".txt", buff);
}
This code posts offsets to a CCR port which causes a Thread to be created to execute the code in the Split method. This causes you to open the file multiple times but gets rid of the need for synchronization. You can make it more memory efficient but you'll have to sacrifice speed.
def lensort(list_1):
list_2=[];list_3=[]
for i in list_1:
list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
list_3.append(i[0])
return list_3
This works for me!
The message you received is common when you have ruby 2.0.0p0 (2013-02-24)
on top of Windows.
The message "DL is deprecated, please use Fiddle
" is not an error; it's only a warning.
The source is the Deprecation notice for DL introduced some time ago in dl.rb
( see revisions/37910 ).
On Windows the lib/ruby/site_ruby/2.0.0/readline.rb
file still requires dl.rb
so the warning message comes out when you require 'irb'
( because irb requires 'readline'
) or when anything else wants to require 'readline'
.
You can open readline.rb
with your favorite text editor and look up the code ( near line 4369 ):
if RUBY_VERSION < '1.9.1'
require 'Win32API'
else
require 'dl'
class Win32API
DLL = {}
We can always hope for an improvement to work out this deprecation in future releases of Ruby.
EDIT: For those wanting to go deeper about Fiddle vs DL, let it be said that their purpose is to dynamically link external libraries with Ruby; you can read on the ruby-doc website about DL or Fiddle.
If you can live with 01 for January instead of 1, then try...
d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")
You can check the docs for other formatting directives.
Hope you dont mind Xml.Linq and .net3.5+
XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);
Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects
Just using XAML, no extensions, no converters:
<Grid>
<TextBox Width="250" VerticalAlignment="Center" HorizontalAlignment="Left" x:Name="SearchTermTextBox" Margin="5"/>
<TextBlock IsHitTestVisible="False" Text="Enter Search Term Here" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0" Foreground="DarkGray">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=SearchTermTextBox}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
I met with the same problem when I did MSI install of MySQL and there were no my-medium.ini files too when I tried the above steps. Only installing the ZIP file of MySQL helped me. So, I suggest you to uninstall the MSI installed folder and reinstall using the ZIP file.
.transbg{/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";}
To be complete, a short introduction for "shell noobs":
First of all, start your shell - you can find it inside the common desktop environments under the name "Terminal" or "Shell" somewhere in the desktops application menu.
You can also try using the key combo CTRL+F2, followed by one of those commands (depending on the desktop envrionment you're using) and the ENTER key:
xfce4-terminal
gnome-console
terminal
rxvt
konsole
If all of the above fail, try using xterm
- it'll work in most cases.
Hint for the following commands: Execute the commands without the $
- it's just a marker identifying that you're on the shell.
After that just fire up mongod
with the --version
flag:
$ mongod --version
It shows you then something like
$ mongod --version
db version v2.4.6
Wed Oct 16 16:17:00.241 git version: nogitversion
To update it just execute
$ sudo apt-get update
and then
$ sudo apt-get install mongodb
In GNU/Linux you can use this command
/etc/init.d/virtualbox
Options
for example
/etc/init.d/virtualbox force-reload
Good Luck
Use:
SELECT *
FROM [Janus999DB].[dbo].[tblCustomerPlay]
WHERE DatePlayed < GetDate()
AND DatePlayed > dateadd(minute, -30, GetDate())
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
I presume you're running Linux on an amd64 machine.
The Folder your executable is residing in (lib32
) suggests a 32-bit executable which requires 32-bit libraries.
These seem not to be present on your system, so you need to install them manually.
The package name depends on your distribution, for Debian it's ia32-libs
, for Fedora libstdc++.<version>.i686
.
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0
produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1]
is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
You could also use clip-path
to clip (hide) all overflowing edges but the one you want to show:
.shadow {
box-shadow: 0 4px 4px black;
clip-path: polygon(0 0, 100% 0, 100% 200%, 0 200%);
}
See clip-path (MDN). The arguments to polygon
are the top-left point, the top-right point, the bottom-right point, and the bottom-left point. By setting the bottom edge to 200%
(or whatever number bigger than 100%
) you constrain your overflow to only the bottom edge.
Examples:
.shadow {
box-shadow: 0 0 8px 5px rgba(200, 0, 0, 0.5);
}
.shadow-top {
clip-path: polygon(0% -20%, 100% -20%, 100% 100%, 0% 100%);
}
.shadow-right {
clip-path: polygon(0% 0%, 120% 0%, 120% 100%, 0% 100%);
}
.shadow-bottom {
clip-path: polygon(0% 0%, 100% 0%, 100% 120%, 0% 120%);
}
.shadow-left {
clip-path: polygon(-20% 0%, 100% 0%, 100% 100%, -20% 100%);
}
.shadow-bottom-right {
clip-path: polygon(0% 0%, 120% 0%, 120% 120%, 0% 120%);
}
/* layout for example */
.box {
display: inline-block;
vertical-align: top;
background: #338484;
color: #fff;
width: 4em;
height: 2em;
margin: 1em;
padding: 1em;
}
_x000D_
<div class="box">none</div>
<div class="box shadow shadow-all">all</div>
<div class="box shadow shadow-top">top</div>
<div class="box shadow shadow-right">right</div>
<div class="box shadow shadow-bottom">bottom</div>
<div class="box shadow shadow-left">left</div>
<div class="box shadow shadow-bottom-right">bottom right</div>
_x000D_
go 1.0 includes a http server & util for serving files with a few lines of code.
package main
import (
"fmt"; "log"; "net/http"
)
func main() {
fmt.Println("Serving files in the current directory on port 8080")
http.Handle("/", http.FileServer(http.Dir(".")))
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Run this source using go run myserver.go
or to build an executable go build myserver.go
You could use gitk --all
and search for commits "touching paths" and the pathname you are interested in.
This function gives you all the diffs (and what stayed the same) based on the dictionary keys only. It also highlights some nice Dict comprehension, Set operations and python 3.6 type annotations :)
from typing import Dict, Any, Tuple
def get_dict_diffs(a: Dict[str, Any], b: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
added_to_b_dict: Dict[str, Any] = {k: b[k] for k in set(b) - set(a)}
removed_from_a_dict: Dict[str, Any] = {k: a[k] for k in set(a) - set(b)}
common_dict_a: Dict[str, Any] = {k: a[k] for k in set(a) & set(b)}
common_dict_b: Dict[str, Any] = {k: b[k] for k in set(a) & set(b)}
return added_to_b_dict, removed_from_a_dict, common_dict_a, common_dict_b
If you want to compare the dictionary values:
values_in_b_not_a_dict = {k : b[k] for k, _ in set(b.items()) - set(a.items())}
This answer is from 2013 and is seriously outdated. As of Android 3.2 there are now 6 groups of screen density. This answer will be updated as soon as I am able, but with no ETA. Refer to the official documentation for all the densities at the moment (although information on specific pixel sizes is as always hard to find).
Create 4 images, one for each screen density:
Read 9-patch image introduction in Android Developer Guide
With this, Android will select the appropriate file for the device's image density, then it will stretch the image according to the 9-patch standard.
I am answering in respect to the design-related aspect of the question. I am not a developer, so I won't be able to provide code for implementing many of the solutions provided. Alas, my intent is to help designers who are as lost as I was when I helped develop my first Android App.
With Android, companies can develop their mobile phones and tables of almost any size, with almost any resolution they want. Because of that, there is no "right image size" for a splash screen, as there are no fixed screen resolutions. That poses a problem for people that want to implement a splash screen.
(On a side note, splash screens are somewhat discouraged among the usability guys. It is argued that the user already knows what app he tapped on, and branding your image with a splash screen is not necessary, as it only interrupts the user experience with an "ad". It should be used, however, in applications that require some considerable loading when initialized (5s+), including games and such, so that the user is not stuck wondering if the app crashed or not)
So, given so many different screen resolutions in the phones on the market, Google implemented some alternatives and nifty solutions that can help. The first thing you have to know is that Android separates ALL screens into 4 distinct screen densities:
What you (if you're a designer) need to know from this is that Android basically chooses from 4 images to display, depending on the device. So you basically have to design 4 different images (although more can be developed for different formats such as widescreen, portrait/landscape mode, etc).
With that in mind know this: unless you design a screen for every single resolution that is used in Android, your image will stretch to fit screen size. And unless your image is basically a gradient or blur, you'll get some undesired distortion with the stretching. So you have basically two options: create an image for each screen size/density combination, or create four 9-patch images.
The hardest solution is to design a different splash screen for every single resolution. You can start by following the resolutions in the table at the end of this page (there are more. Example: 960 x 720 is not listed there). And assuming you have some small detail in the image, such as small text, you have to design more than one screen for each resolution. For example, a 480x800 image being displayed in a medium screen might look ok, but on a smaller screen (with higher density/dpi) the logo might become too small, or some text might become unreadable.
The other solution is to create a 9-patch image. It is basically a 1-pixel-transparent-border around your image, and by drawing black pixels in the top and left area of this border you can define which portions of your image will be allowed to stretch. I won't go into the details of how 9-patch images work but, in short, the pixels that align to the markings in the top and left area are the pixels that will be repeated to stretch the image.
So you can place 1 dot on either side of your logo (in the top border), and 1 dot above and below it (on the left border), and these marked rows and columns will be the only pixels to stretch.
Here's a 9-patch image, 102x102px (100x100 final size, for app purposes):
Here's a 200% zoom of the same image:
Notice the 1px marks on top and left saying which rows/columns will expand.
Here's what this image would look like in 100x100 inside the app:
And here's what it would like if expanded to 460x140:
One last thing to consider. These images might look fine on your monitor screen and on most mobiles, but if the device has a very high image density (dpi), the image would look too small. Probably still legible, but on a tablet with 1920x1200 resolution, the image would appear as a very small square in the middle. So what's the solution? Design 4 different 9-patch launcher images, each for a different density set. To ensure that no shrinking will occur, you should design in the lowest common resolution for each density category. Shrinking is undesirable here because 9-patch only accounts for stretching, so in a shrinking process small text and other elements might lose legibility.
Here's a list of the smallest, most common resolutions for each density category:
So design four splash screens in the above resolutions, expand the images, putting a 1px transparent border around the canvas, and mark which rows/columns will be stretchable. Keep in mind these images will be used for ANY device in the density category, so your ldpi image (240 x 320) might be stretched to 1024x600 on an extra large tablet with small image density (~120 dpi). So 9-patch is the best solution for the stretching, as long as you don't want a photo or complicated graphics for a splash screen (keep in mind these limitations as you create the design).
Again, the only way for this stretching not to happen is to design one screen each resolution (or one for each resolution-density combination, if you want to avoid images becoming too small/big on high/low density devices), or to tell the image not to stretch and have a background color appear wherever stretching would occur (also remember that a specific color rendered by the Android engine will probably look different from the same specific color rendered by photoshop, because of color profiles).
I hope this made any sense. Good luck!
It is possible by managing a flag in SharedPreferences or in Application Activity.
On starting of app (on Splash Screen) set the flag = false; On Logout Click event just set the flag true and in OnResume() of every activity, check if flag is true then call finish().
It works like a charm :)
FYI, it looks like the syntax for retrieving the values has changed according to:
http://freemarker.sourceforge.net/docs/ref_builtins_hash.html
<#assign h = {"name":"mouse", "price":50}>
<#assign keys = h?keys>
<#list keys as key>${key} = ${h[key]}; </#list>
I finally got this to work on my own hosted xampp windows 10 server web site. I.e. padlocks came up as ssl. I am using xampp version from November 2020.
Went to certbot.eff.org. Selected from their home page software [apache] and system [windows]. Then downloaded and installed certbot software found at the next page into my C drive.
Then from command line [cmd in Windows Start and then before you open cmd right click to run cmd as admin] I enhtered the command from Certbot page above. I.e. navigated to system32-- C:\WINDOWS\system32> certbot certonly --standalone
Then followed the prompts and enteredmy domain name. This created certs as cert1.pem and key1.pem in C:\Certbot yourwebsitedomain folder. the cmd windows tells you where these are.
Then took these and changed their names from cert1.pem to my domainname or shorter+cert.pem and same for domainname or shorter+key.key. Copied these into C:\xampp\apache\ssl.crt and ssl.key folders respectively.
Then for G:\xampp\apache\conf\extra\httpd-vhosts entered the following:
<VirtualHost *:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainname.hopto.org/public/" ###NB My document root is public. Yours may not be. Or could have an index.php page before /public###
ServerName yourwebsitedomainnamee.hopto.org
<Directory G:/xampp/htdocs/yourwebsitedomainname.hopto.org>
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
ErrorLog "G:/xampp/apache/logs/error.log"
CustomLog "G:/xampp/apache/logs/access.log" common
SSLEngine on
SSLCertificateFile "G:\xampp\apache\conf\ssl.crt\abscert.pem"
SSLCertificateKeyFile "G:\xampp\apache\conf\ssl.key\abskey.pem"
</VirtualHost>
<VirtualHost _default_:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainnamee.hopto.org/public/"
###NB My document root is public. Yours may not be. Or could have an index.php page before /public###
SSLEngine on
SSLCertificateFile "conf/ssl.crt/abscert.pem"
SSLCertificateKeyFile "conf/ssl.key/abskey.pem"
CustomLog "G:/xampp/apache/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
Note1. I used www.noip.com to register the domain name. Note2. Rather then try to get them to give me a ssl certificate, as I could not get it to work, the above worked instead. Note3 I use the noip DUC software to keep my personally hosted web site in sync with noip. Note4. Very important to stop and start xampp server after each change you make in xampp. If xampp fails for some reason instead of starting the xampp consol try the start xampp as this will give you problems you can bug fix. Copy these quickly and paste into note.txt.
Swift 3:
button.setImage(UIImage(named: "checkmark_white"), for: .normal)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
You may be forgetting something. Before #include <iostream>
, write #include <stdafx.h>
and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."
This is how I do it:
public static String readFromAssets(Context context, String filename) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
// do reading, usually loop until end of file reading
StringBuilder sb = new StringBuilder();
String mLine = reader.readLine();
while (mLine != null) {
sb.append(mLine); // process line
mLine = reader.readLine();
}
reader.close();
return sb.toString();
}
use it as follows:
readFromAssets(context,"test.txt")
I had the same need to fill up a column with a sequence series for each value on another column. I tried all the answers above and could not fix the problem. I solved it with a simple VBA macro.
My data have the same structure (but with 3000 rows):
Here below the code:
> Sub Seq_N3() ' ' Seq_N3 Macro ' Sequence numbering of N3 based on N2 value
> do N2
> Dim N2 As Integer
> Dim seq As Integer
>
> With ActiveSheet
>
> For N2 = 1 To 7 Step 1
> seq = 1 '
> .Range("B2").Select '
>
> Do While ActiveCell.Offset(0, -1).Value2 <> 0
>
> If ActiveCell.Offset(0, -1).Value2 = N2 Then
> ActiveCell.Value2 = seq
> seq = seq + 1
> ActiveCell.Offset(1, 0).Select
> Else
> ActiveCell.Offset(1, 0).Select
> End If
>
> Loop
>
> Next N2
>
> End With End Sub
Hope it helps!
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
An example with a little less stringified html:
var container = $('#my-container'),
table = $('<table>');
users.forEach(function(user) {
var tr = $('<tr>');
['ID', 'Name', 'Address'].forEach(function(attr) {
tr.append('<td>' + user[attr] + '</td>');
});
table.append(tr);
});
container.append(table);
Try __FILE__
and __LINE__
.
You might also find __DATE__
and __TIME__
useful.
Though unless you have to debug a program on the clientside and thus need to log these informations you should use normal debugging.
Following Aristotle Pagaltzis and the idea of COALESCE
from Eric B’s answer, here it is an upsert option to update only few columns or insert full row if it does not exist.
In this case, imagine that title and content should be updated, keeping the other old values when existing and inserting supplied ones when name not found:
NOTE id
is forced to be NULL when INSERT
as it is supposed to be autoincrement. If it is just a generated primary key then COALESCE
can also be used (see Aristotle Pagaltzis comment).
WITH new (id, name, title, content, author)
AS ( VALUES(100, 'about', 'About this site', 'Whatever new content here', 42) )
INSERT OR REPLACE INTO page (id, name, title, content, author)
SELECT
old.id, COALESCE(old.name, new.name),
new.title, new.content,
COALESCE(old.author, new.author)
FROM new LEFT JOIN page AS old ON new.name = old.name;
So the general rule would be, if you want to keep old values, use COALESCE
, when you want to update values, use new.fieldname
CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index
values are likely to get screwed with.
If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.
So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased;
is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.
typeof foo === "undefined"
is different from foo === undefined
, never confuse them. typeof foo === "undefined"
is what you really need. Also, use !==
in place of !=
So the statement can be written as
function (data) {
if (typeof data !== "undefined" && data !== null) {
// some code here
}
}
Edit:
You can not use foo === undefined
for undeclared variables.
var t1;
if(typeof t1 === "undefined")
{
alert("cp1");
}
if(t1 === undefined)
{
alert("cp2");
}
if(typeof t2 === "undefined")
{
alert("cp3");
}
if(t2 === undefined) // fails as t2 is never declared
{
alert("cp4");
}
I always try to factor out complex boolean expressions into meaningful variables (you could probably think of better names based on what these columns are used for):
bool notColumnsABC = (columnname != a && columnname != b && columnname != c);
bool notColumnA2OrBoxIsChecked = ( columnname != A2 || checkbox.checked );
if ( notColumnsABC
&& notColumnA2OrBoxIsChecked )
{
"statement 1"
}
I know its too longtime to reply but just as an information purpose for future readers:
WebRequest
System.Object
System.MarshalByRefObject
System.Net.WebRequest
The WebRequest
is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest
and FileWebRequest
.
You use Create method of WebRequest
to create an instance of WebRequest
. GetResponseStream
returns data stream
.
There are also FileWebRequest
and FtpWebRequest
classes that inherit
from WebRequest
. Normally, you would use WebRequest
to, well, make a request and convert the return to either HttpWebRequest
, FileWebRequest
or FtpWebRequest
, depend on your request. Below is an example:
Example:
var _request = (HttpWebRequest)WebRequest.Create("http://stackverflow.com");
var _response = (HttpWebResponse)_request.GetResponse();
WebClient
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Net.WebClient
WebClient
provides common operations to sending
and receiving
data from a resource identified by a URI
. Simply, it’s a higher-level abstraction of HttpWebRequest
. This ‘common operations’ is what differentiate WebClient
from HttpWebRequest
, as also shown in the sample below:
Example:
var _client = new WebClient();
var _stackContent = _client.DownloadString("http://stackverflow.com");
There are also DownloadData
and DownloadFile
operations under WebClient
instance. These common operations also simplify code of what we would normally do with HttpWebRequest
. Using HttpWebRequest
, we have to get the response of our request, instantiate StreamReader
to read the response and finally, convert the result to whatever type we expect. With WebClient
, we just simply call DownloadData, DownloadFile or DownloadString
.
However, keep in mind that WebClient.DownloadString
doesn’t consider the encoding
of the resource you requesting. So, you would probably end up receiving weird characters if you don’t specify and encoding.
NOTE: Basically "WebClient takes few lines of code as compared to Webrequest"
It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.
http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760
To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.
I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.
The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.
Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).
This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.
Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications
Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)
The complete solution including email addresses in path names for spring 4.2 is
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="mediaTypes">
<value>
json=application/json
xml=application/xml
</value>
</property>
</bean>
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager">
<mvc:path-matching suffix-pattern="false" registered-suffixes-only="true" />
</mvc:annotation-driven>
Add this to the application-xml
Try this, a lot less code:
System.Text.Encoding.UTF8.GetBytes("TEST String");
Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.
My setup was as follows:
I put the following formula in cell A1 of Sheet3:
=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)
Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.
Notes:
In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.
A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.
After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)
and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.
Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.
Cells A2, A3, etc. will get these formulas:
=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)
Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.
The Venn diagrams don't really do it for me.
They don't show any distinction between a cross join and an inner join, for example, or more generally show any distinction between different types of join predicate or provide a framework for reasoning about how they will operate.
There is no substitute for understanding the logical processing and it is relatively straightforward to grasp anyway.
on
clause against all rows from step 1 keeping those where the predicate evaluates to true
(NB: In practice the query optimiser may find more efficient ways of executing the query than the purely logical description above but the final result must be the same)
I'll start off with an animated version of a full outer join. Further explanation follows.
Source Tables
First start with a CROSS JOIN
(AKA Cartesian Product). This does not have an ON
clause and simply returns every combination of rows from the two tables.
SELECT A.Colour, B.Colour FROM A CROSS JOIN B
Inner and Outer joins have an "ON" clause predicate.
SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour = B.Colour
The above is the classic equi join.
The inner join condition need not necessarily be an equality condition and it need not reference columns from both (or even either) of the tables. Evaluating A.Colour NOT IN ('Green','Blue')
on each row of the cross join returns.
SELECT A.Colour, B.Colour FROM A INNER JOIN B ON 1 =1
The join condition evaluates to true for all rows in the cross join result so this is just the same as a cross join. I won't repeat the picture of the 16 rows again.
Outer Joins are logically evaluated in the same way as inner joins except that if a row from the left table (for a left join) does not join with any rows from the right hand table at all it is preserved in the result with NULL
values for the right hand columns.
This simply restricts the previous result to only return the rows where B.Colour IS NULL
. In this particular case these will be the rows that were preserved as they had no match in the right hand table and the query returns the single red row not matched in table B
. This is known as an anti semi join.
It is important to select a column for the IS NULL
test that is either not nullable or for which the join condition ensures that any NULL
values will be excluded in order for this pattern to work correctly and avoid just bringing back rows which happen to have a NULL
value for that column in addition to the un matched rows.
Right outer joins act similarly to left outer joins except they preserve non matching rows from the right table and null extend the left hand columns.
Full outer joins combine the behaviour of left and right joins and preserve the non matching rows from both the left and the right tables.
No rows in the cross join match the 1=0
predicate. All rows from both sides are preserved using normal outer join rules with NULL in the columns from the table on the other side.
With a minor amend to the preceding query one could simulate a UNION ALL
of the two tables.
Note that the WHERE
clause (if present) logically runs after the join. One common error is to perform a left outer join and then include a WHERE clause with a condition on the right table that ends up excluding the non matching rows. The above ends up performing the outer join...
... And then the "Where" clause runs. NULL= 'Green'
does not evaluate to true so the row preserved by the outer join ends up discarded (along with the blue one) effectively converting the join back to an inner one.
If the intention was to include only rows from B where Colour is Green and all rows from A regardless the correct syntax would be
See these examples run live at SQLFiddle.com.
try to disabled Dark Mode on Mysql Workbench run this on terminal
defaults write com.oracle.workbench.MySQLWorkbench NSRequiresAquaSystemAppearance -bool yes
It's about how the operating system recognizes line ends.
Morale: if you are developing for Windows, stick to \r\n. Or even better, use C# string functions to deal with strings which already consider line endings (WriteLine, and such).
I think the following is the easiest way to do it.
<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>
You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);
You can use the index
method available on Array
with a predicate (see Apple's documentation here).
func index(where predicate: (Element) throws -> Bool) rethrows -> Int?
For your specific example this would be:
Swift 5.0
if let i = array.firstIndex(where: { $0.name == "Foo" }) {
return array[i]
}
Swift 3.0
if let i = array.index(where: { $0.name == Foo }) {
return array[i]
}
Swift 2.0
if let i = array.indexOf({ $0.name == Foo }) {
return array[i]
}
ES6/ES2015 version:
import customData from './customData.json';
You can just split the string..
public String[] split(String regex)
Note that java.lang.String.split uses delimiter's regular expression value. Basically like this...
String filename = "abc.def.ghi"; // full file name
String[] parts = filename.split("\\."); // String array, each element is text between dots
String beforeFirstDot = parts[0]; // Text before the first dot
Of course, this is split into multiple lines for clairity. It could be written as
String beforeFirstDot = filename.split("\\.")[0];
My solution is similar to what people answered but adds sizeThatFits
to help UIKit
to figure out the right size.
class InsetLabel : UILabel {
@objc var textInsets: UIEdgeInsets = .zero
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: textInsets))
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var s = super.sizeThatFits(CGSize(width: size.width - (textInsets.left + textInsets.right), height: size.height - (textInsets.top + textInsets.bottom)))
s.height += textInsets.top + textInsets.bottom
return s
}
}
var myobj = {"A":["Abe"], "B":["Bob"]};
var keysArray = Object.keys(myobj);
var valuesArray = Object.keys(myobj).map(function(k) {
return String(myobj[k]);
});
var mydata = valuesArray[keysArray.indexOf("A")]; // Abe
while true ; do
...
if [ something ]; then
break
fi
done
Current Date using java 8: First, let's use java.time.LocalDate to get the current system date:
LocalDate localDate = LocalDate.now();
To get the date in any other timezone we can use LocalDate.now(ZoneId):
LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));
We can also use java.time.LocalDateTime to get an instance of LocalDate:
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();
You cant blame code all the time sometime may be your url is wrong , double check urls
I could not resolve this with CSS. It seems like Boostrap is getting the last say even though I have by site.css after bootstrap. In any event, this worked for me.
$(document).ready(function () {
var elements = document.getElementsByClassName("form-control");
Array.from(elements).forEach(function () {
this.addEventListener("click", cbChange, false);
})
});
function cbChange(event) {
var ele = event.target;
var obj = document.getElementById(ele.id);
obj.style.borderColor = "lightgrey";
}
Later I found this to work in the css. Obviously with form-controls only
.form-control.focus, .form-control:focus {
border-color: gainsboro;
}
Here are before and after shots from Chrome Developer tool. Notice the difference in border color between focus on and focus off. On a side note, this does not work for buttons. With buttons. With buttons you have to change outline property to none.
here is an alt version that also works for me and has attachments (posted already above but complete version unlike the source link, which people posted they cant get it to work since its missing data)
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public Mail(String user, String pass) {
this();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
public void setTo(String[] toArr) {
// TODO Auto-generated method stub
this._to=toArr;
}
public void setFrom(String string) {
// TODO Auto-generated method stub
this._from=string;
}
public void setSubject(String string) {
// TODO Auto-generated method stub
this._subject=string;
}
// more of the getters and setters …..
}
and to call it in an activity...
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button addImage = (Button) findViewById(R.id.send_email);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mail m = new Mail("[email protected]", "password");
String[] toArr = {"[email protected]", "[email protected]"};
m.setTo(toArr);
m.setFrom("[email protected]");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
try {
m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
});
}
Examine error log (start eventvwr.msc). MySQL typically writes something to the Application log.
In very rare cases it does not write anything (I'm only aware of one particular bug http://bugs.mysql.com/bug.php?id=56821, where services did not work at all). There is also error log file, normally named .err in the data directory that has the same info as written to windows error log.
A bit late in the game, i know... but this is what i recently did. It is slightly different than yours, but allows the programmer to dictate what the equality operation needs to be (predicate). Which i find very useful when dealing with different types, since i then have a generic way of doing it regardless of object type and <T>
built in equality operator.
It also has a very very small memory footprint, and is very, very fast/efficient... if you care about that.
At worse, you'll just add this to your list of extensions.
Anyway... here it is.
public static int IndexOf<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
int retval = -1;
var enumerator = source.GetEnumerator();
while (enumerator.MoveNext())
{
retval += 1;
if (predicate(enumerator.Current))
{
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
return retval;
}
}
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
return -1;
}
Hopefully this helps someone.
Here is an another way find value index in complex array in javascript. Hope help somebody indeed. Let us assume we have a JavaScript array as following,
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
You can somehow reproduce the behavior of "OR" using & and :not.
SomeElement.SomeClass [data-statement="things are getting more complex"] :not(:not(A):not(B)) {
/* things aren't so complex for A or B */
}
ValidateForm
returns boolean
,not a string
.
When you do this if(ValidateForm() == 'false')
, is the same of if(false == 'false')
, which is not true.
function post(url, formId) {
if(!ValidateForm()) {
// False
} else {
// True
}
}
Use file_get_contents
in combination with json_decode
and echo
.
Inside Fragments (onCreateView)
Toast.makeText(getActivity(), "your message" , Toast.LENGTH_LONG).show();
Inside Classes (onCreate)
Toast.makeText(myClassName.this, "your message" , Toast.LENGTH_LONG).show();
Create a BroadcastReceiver
and register it to receive ACTION_BOOT_COMPLETED. You also need RECEIVE_BOOT_COMPLETED permission.
Read: Listening For and Broadcasting Global Messages, and Setting Alarms
The first problem is that your query string is wrong:
I think this: "INSERT INTO employee(hans,germany) values(?,?)"
should be like this: "INSERT INTO employee(name,country) values(?,?)"
The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.
You should add these to your code:
String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();
Use a comma to specify a port number with SQL Server:
mycomputer.test.xxx.com,1234
It's not necessary to specify an instance name when specifying the port.
Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.
The correct answer is
git checkout -m origin/master
It merges changes from the origin master branch with your local even uncommitted changes.
Okay, as of 0.7.7 this is available, but not in the manner that lubar describes. I ended up needing to parse through some commit logs on git hub to figure this one out, but the following code does actually work for me now:
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
var address = socket.handshake.address;
console.log('New connection from ' + address.address + ':' + address.port);
});
Just add 360° if the answer from atan2 is less than 0°.
Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/
If you want to center map onto a marker and you have the cordinate, something like click on a list item and the map should center on that coordinate then the following code will work:
In HTML:
<ul class="locationList" ng-repeat="LocationDetail in coordinateArray| orderBy:'LocationName'">
<li>
<div ng-click="focusMarker(LocationDetail)">
<strong><div ng-bind="locationDetail.LocationName"></div></strong>
<div ng-bind="locationDetail.AddressLine"></div>
<div ng-bind="locationDetail.State"></div>
<div ng-bind="locationDetail.City"></div>
<div>
</li>
</ul>
In Controller:
$scope.focusMarker = function (coords) {
map.setCenter(new google.maps.LatLng(coords.Latitude, coords.Longitude));
map.setZoom(14);
}
Location Object:
{
"Name": "Taj Mahal",
"AddressLine": "Tajganj",
"City": "Agra",
"State": "Uttar Pradesh",
"PhoneNumber": "1234 12344",
"Latitude": "27.173891",
"Longitude": "78.042068"
}
Just set the path variable to JDK bin in environment variables.
Variable Name : PATH
Variable Value : C:\Program Files\Java\jdk1.8.0_31\bin
But the best practice is to set JAVA_HOME and PATH as follow.
Variable Name : JAVA_HOME
Variable Value : C:\Program Files\Java\jdk1.8.0_31
Variable Name : PATH
Variable Value : %JAVA_HOME%\bin
function checkForm(& $fields){
foreach($fields as $field){
if($field['required'] && strlen($_POST[$field['name']]) <= 0){
$fields[$field]['value'] = "Some error";
}
}
return $fields;
}
This is what I would Suggest pass by reference
In case if someone interests to pass data to dialog:
app.controller('ModalCtrl', function($scope, $modal) {
$scope.name = 'theNameHasBeenPassed';
$scope.showModal = function() {
$scope.opts = {
backdrop: true,
backdropClick: true,
dialogFade: false,
keyboard: true,
templateUrl : 'modalContent.html',
controller : ModalInstanceCtrl,
resolve: {} // empty storage
};
$scope.opts.resolve.item = function() {
return angular.copy(
{name: $scope.name}
); // pass name to resolve storage
}
var modalInstance = $modal.open($scope.opts);
modalInstance.result.then(function(){
//on ok button press
},function(){
//on cancel button press
console.log("Modal Closed");
});
};
})
var ModalInstanceCtrl = function($scope, $modalInstance, $modal, item) {
$scope.item = item;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
Demo Plunker
You don't need jQuery for that, you can do it with normal javascript:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "a,b,c,d";
var res = str.split(","); // this returns an array
you can also import the FunctionType from types and test it with the class.__dict__
:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
I got this error in Xamarin when I was using
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="4dp"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
</android.support.v7.widget.CardView>
in a layout file without installing the nuget package for android.support.v7.widget.CardView
Installing the applicable nuget package fixed the issue. Hope it helps, I didn't see this answer anywhere in the list
In the simple setup you are likely using, getchar
works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF
; in fact, EOF
is not really a character, but a magic value that indicates the end of the file. But EOF
is not part of the string read. It's what getchar
returns when there is nothing left to read.
Official(?) instructions: http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages
If you have replaced a package with another version, then you can just delete the package(s) you don't need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).
If you want to delete the currently installed version of a package (or all versions of a package), you should first run:
easy_install -mxN PackageName
This will ensure that Python doesn't continue to search for a package you're planning to remove. After you've done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass selItem = (MyClass) adapter.getItem(position);
}
}
I use sublime Text on linux.
This is an expansion of @Dathan's answer, using html2canvas and FileSaver.js.
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
canvas.toBlob(function(blob) {
saveAs(blob, "Dashboard.png");
});
}
});
});
});
This code block waits for the button with the id btnSave
to be clicked. When it is, it converts the widget
div to a canvas element and then uses the saveAs() FileSaver interface (via FileSaver.js in browsers that don't support it natively) to save the div as an image named "Dashboard.png".
An example of this working is available at this fiddle.
I'd use np.all here, if you have an array a:
>>> np.all(a==0)
We can get the element screenshot by cropping entire page screenshot as below:
driver.get("http://www.google.com");
WebElement ele = driver.findElement(By.id("hplogo"));
// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = ele.getLocation();
// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screenshot, screenshotLocation);
You could also use the whitelist method -
var str = $('#Search').val();
var regex = /[^\w\s]/gi;
if(regex.test(str) == true) {
alert('Your search string contains illegal characters.');
}
The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.
I was hit by this problem, too. I'm using my custom build of AOSP on Nexus 5X. I've added a single line in build/core/main.mk:
diff --git a/core/main.mk b/core/main.mk
index a6f829ab6..555657539 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -362,6 +362,8 @@ else # !enable_target_debugging
ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=0
endif # !enable_target_debugging
+ADDITIONAL_DEFAULT_PROPERTIES += ro.adb.secure=1
+
## eng ##
ifeq ($(TARGET_BUILD_VARIANT),eng)
Now adb shell
works fine
Those materials are useful (Chinese articles): http://www.voidcn.com/blog/kc58236582/article/p-6335996.html, http://blog.csdn.net/fanmengke_im/article/details/28389439
I had the same error when I run the route in the browser, but in postman, it works fine. It issue with mine was that, there was no /
after the route before the query string.
127.0.0.1:5000/api/v1/search/?location=Madina
raise the error and removing /
after the search
worked for me.
regarding AlexB's post:
\' Apostrophe or single quote
\" Double quote
escaping single quotes is only valid in single quoted json strings
escaping double quotes is only valid in double quoted json strings
example:
'Bart\'s car' -> valid
'Bart says \"Hi\"' -> invalid
If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.
Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.
If you really had to achieve this affect while keeping the children as position: absolute
, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.
Alternatively, just use float: left
/float:right
and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden
on the parent (or any other clearfix technique) to cause its height to expand to that of its children.
article {
position: relative;
overflow: hidden;
}
.one {
position: relative;
float: left;
margin-top: 10px;
margin-left: 10px;
background: red;
width: 30px;
height: 30px;
}
.two {
position: relative;
float: right;
margin-top: 10px;
margin-right: 10px;
background: blue;
width: 30px;
height: 30px;
}
You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contents
select project navigator > select Target > Identity > Display Name > Name
You should use val
instead of value
.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('input[name="testing"]').val('Work!');
});
</script>
I was curious about which method would be faster:
I found that depending on the size of the input data and the number of groups, the Distinct method can be a lot more performant. (as the number of groups tends towards the number of elements in the list, distinct runs faster).
Code runs in LinqPad!
void Main()
{
List<C> cs = new List<C>();
foreach(var i in Enumerable.Range(0,Int16.MaxValue*1000))
{
int modValue = Int16.MaxValue; //vary this value to see how the size of groups changes performance characteristics. Try 1, 5, 10, and very large numbers
int j = i%modValue;
cs.Add(new C{I = i, J = j});
}
cs.Count ().Dump("Size of input array");
TestGrouping(cs);
TestDistinct(cs);
}
public void TestGrouping(List<C> cs)
{
Stopwatch sw = Stopwatch.StartNew();
sw.Restart();
var groupedCount = cs.GroupBy (o => o.J).Select(s => s.First()).Count();
groupedCount.Dump("num groups");
sw.ElapsedMilliseconds.Dump("elapsed time for using grouping");
}
public void TestDistinct(List<C> cs)
{
Stopwatch sw = Stopwatch.StartNew();
var distinctCount = cs.Distinct(new CComparerOnJ()).Count ();
distinctCount.Dump("num distinct");
sw.ElapsedMilliseconds.Dump("elapsed time for using distinct");
}
public class C
{
public int I {get; set;}
public int J {get; set;}
}
public class CComparerOnJ : IEqualityComparer<C>
{
public bool Equals(C x, C y)
{
return x.J.Equals(y.J);
}
public int GetHashCode(C obj)
{
return obj.J.GetHashCode();
}
}
If you'd like to exclude the false or empty rows (such as 0 => ''
), where using empty()
will fail, you can try:
if (array_filter($playerlist) == []) {
// Array is empty!
}
array_filter()
: If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.
If you'd like to remove all NULL, FALSE and empty strings (''
), but leave zero values (0
), you can use strlen
as a callback, e.g.:
$is_empty = array_filter($playerlist, 'strlen') == [];
Adding new remote
git remote add upstream https://github.com/example-org/example-repo.git
git remote -vv
Fetch form multiple locations
git fetch --all
Push to locations
git push -u upstream/dev
Check if your firewall didn't add a rule and blocked the connection to adb server. It uses newdev.dll and your network. It just happened here, I removed the blocking rule from the firewall, and now it is fine.
you need to set the margin of the body to 0 for the table to stretch the full width. alternatively you can set the margin of the table to a negative number as well.
In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class.
don't know if that's an option in your case though.
As of jQuery 1.7 you should use jQuery.fn.on
with the selector parameter filled:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Explanation:
This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors
) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild
). When there is a match then your custom handler function is executed.
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
In Android, How to use a Cursor with a raw query in sqlite:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
"where Age > 10 LIMIT 5", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
c.close();
The problem here is
if (stop = true)
is an assignation not a comparision.
Try if (stop == true)
Also take a look to the Top Ten Errors Java Programmers Make.
It is very simple.
As you say, it starts with data:image/jpeg;base64,
.
Below is an example taken from wikipedia, but it is only an example
I think that programing Base 64 encoded images is a little dificult, so there is an webapp to do that.
Here is the link for the app: https://www.opinionatedgeek.com/codecs/base64decoder
<div>
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
</div>
_x000D_
In windows, this short program accomplishes the goal: getch
pauses the console until a key is pressed (https://www.geeksforgeeks.org/difference-getchar-getch-getc-getche/)
#include<iostream.h>
#include<conio.h>
using namespace std;
void check()
{
char chk; int j;
cout<<"\n\nPress any key to continue...";
chk=getch();
j=chk;
for(int i=1;i<=256;i++)
if(i==j) break;
clrscr();
}
void main()
{
clrscr();
check();
cout<<"\n\nIt works!";
getch();
}
It should be noted that getch is not part of the standard library.
For adding argument to delay function.
First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.
let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)
Then in the called function
func functionHereWithArgument (timer : NSTimer)
{
if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
{
let argumentInt : Int = (userInfo[argumentInt] as! Int)
}
}
In this particular case, Option 1 is better.
The guard statement (checking isDebugEnabled()
) is there to prevent potentially expensive computation of the log message when it involves invocation of the toString()
methods of various objects and concatenating the results.
In the given example, the log message is a constant string, so letting the logger discard it is just as efficient as checking whether the logger is enabled, and it lowers the complexity of the code because there are fewer branches.
Better yet is to use a more up-to-date logging framework where the log statements take a format specification and a list of arguments to be substituted by the logger—but "lazily," only if the logger is enabled. This is the approach taken by slf4j.
See my answer to a related question for more information, and an example of doing something like this with log4j.
You can set this programmatically in the controller:-
HttpContext.Current.Server.ScriptTimeout = 300;
Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)
I had this problem with Firefox and my server. I contacted GoDaddy customer support, and they had me install the intermediate server certificate:
http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate
After a re-start of the World Wide Web Publishing Service, everything worked perfectly.
If you do not have full access to your server, your ISP will have to do this for you.
And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:
http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php
Use the below class to push it to last line of the page and also make it to center of it.
If you are using ruby on rails HAML page you can make use of the below code.
%footer.card.text-center
Pls don't forget to use twitter bootstrapp
The default behaviour for error_log() is to output to the Apache error log. If this isn't happening check your php.ini settings for the error_log directive. Leave it unset to use the Apache log file for the current vhost.
I use svnsync, which sets up a remote server as a mirror/slave. We had a server go down two weeks ago, and I was able to switch the slave into primary position quite easily (only had to reset the UUID on the slave repository to the original).
Another benefit is that the sync can be run by a middle-man, rather than as a task on either server. I've had a client to two VPNs sync a repository between them.
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.
main.go
var StartTime = time.Now()
func main() {
otherPackage.StartTime = StartTime
}
otherpackage.go
var StartTime time.Time
Consider using django-bulk-update
found here on GitHub.
Install: pip install django-bulk-update
Implement: (code taken directly from projects ReadMe file)
from bulk_update.helper import bulk_update
random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()
for person in people:
r = random.randrange(4)
person.name = random_names[r]
bulk_update(people) # updates all columns using the default db
Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.
My issue was that I started server as sudo once and then tried to restart as a local user.
Here mysql was not able to write to '.err' file owned by root. I had to remove that file and restart the server:
sudo rm /usr/local/var/mysql/*.err
mysql.server start
Note: This answer was originally posted here
I am posting this answer because I would like to share additional details about the available options that I did not find in the other answers
To create a DataFrame from an RDD of Rows, there are two main options:
1) As already pointed out, you could use toDF()
which can be imported by import sqlContext.implicits._
. However, this approach only works for the following types of RDDs:
RDD[Int]
RDD[Long]
RDD[String]
RDD[T <: scala.Product]
(source: Scaladoc of the SQLContext.implicits
object)
The last signature actually means that it can work for an RDD of tuples or an RDD of case classes (because tuples and case classes are subclasses of scala.Product
).
So, to use this approach for an RDD[Row]
, you have to map it to an RDD[T <: scala.Product]
. This can be done by mapping each row to a custom case class or to a tuple, as in the following code snippets:
val df = rdd.map({
case Row(val1: String, ..., valN: Long) => (val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")
or
case class MyClass(val1: String, ..., valN: Long = 0L)
val df = rdd.map({
case Row(val1: String, ..., valN: Long) => MyClass(val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")
The main drawback of this approach (in my opinion) is that you have to explicitly set the schema of the resulting DataFrame in the map function, column by column. Maybe this can be done programatically if you don't know the schema in advance, but things can get a little messy there. So, alternatively, there is another option:
2) You can use createDataFrame(rowRDD: RDD[Row], schema: StructType)
as in the accepted answer, which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:
val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)
Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType
class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.
Here's how I did it... No need for try-catch block... The best solution is always the simplest... Enjoy!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}
Remember to not capitalize your text when writing this command. For example:
Do write:
rails g model product title:string description:text image_url:string price:decimal
Do not write:
rails g Model product title:string description:text image_url:string price:decimal
At least it was a problem to me.
This is how to use chai to deeply test associative arrays.
I had an issue trying to assert that two associative arrays were equal. I know that these shouldn't really be used in javascript but I was writing unit tests around legacy code which returns a reference to an associative array. :-)
I did it by defining the variable as an object (not array) prior to my function call:
var myAssocArray = {}; // not []
var expectedAssocArray = {}; // not []
expectedAssocArray['myKey'] = 'something';
expectedAssocArray['differentKey'] = 'something else';
// legacy function which returns associate array reference
myFunction(myAssocArray);
assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');
Not sure why no-one's just answered this - seems like a perfectly reasonable technical question to ask whether it's possible.
No, I don't think there's a cross-browser way to disable the backspace button. I know it's not enabled by default in FF these days though.
If you want to add wsdl reference in .Net Core project, there is no "Add web reference" option.
To add the wsdl reference go to Solution Explorer, right-click on the References project item and then click on the Add Connected Service option.
Then click 'Microsoft WCF Web Service Reference':
Enter the file path into URI text box and import the WSDL:
It will generate a simple, very basic WCF client and you to use it something like this:
YourServiceClient client = new YourServiceClient();
client.DoSomething();
1.Go to EC2 Dashboard and click "Running Instances" on "Security Groups"
2.select the group of your instance which you need to add security.
3.click on the "Inbound" tab
4.Click "Edit" Button (It will open an popup window)
5.click "Add Rule"
6.Select the "Custom ICMP rule - IPv4" as Type
7.Enter the "0.0.0.0/0" as Source or your public IP
7.Click "Save"
To give more elaboration on the bitwise operator method for those of us who didn't do much boolean algebra during our studies, here is an explanation. Probably not of much use to the OP, but I felt like making it clear why NUMBER & 1 works.
Please note like as someone answered above, the way negative numbers are represented can stop this method working. In fact it can even break the modulo operator method too since each language can differ in how it deals with negative operands.
However if you know that NUMBER will always be positive, this works well.
As Tooony above made the point that only the last digit in binary (and denary) is important.
A boolean logic AND gate dictates that both inputs have to be a 1 (or high voltage) for 1 to be returned.
1 & 0 = 0.
0 & 1 = 0.
0 & 0 = 0.
1 & 1 = 1.
If you represent any number as binary (I have used an 8 bit representation here), odd numbers have 1 at the end, even numbers have 0.
For example:
1 = 00000001
2 = 00000010
3 = 00000011
4 = 00000100
If you take any number and use bitwise AND (& in java) it by 1 it will either return 00000001, = 1 meaning the number is odd. Or 00000000 = 0, meaning the number is even.
E.g
Is odd?
1 & 1 =
00000001 &
00000001 =
00000001 <— Odd
2 & 1 =
00000010 &
00000001 =
00000000 <— Even
54 & 1 =
00000001 &
00110110 =
00000000 <— Even
This is why this works:
if(number & 1){
//Number is odd
} else {
//Number is even
}
Sorry if this is redundant.
Tail the log as a background job (&) and it will interleave with rspec output.
tail -f log/test.log &
bundle exec rspec
Other option to try is to stop SQL Server Reporting Services.
I'm using fileupload-jquery in haml. The original js is below:
<!-- The template to display files available for download -->_x000D_
<script id="template-download" type="text/x-tmpl">_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
<tr class="template-download fade">_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
<span>{%=locale.fileupload.destroy%}</span>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}_x000D_
</script>
_x000D_
At first I used the :cdata
to convert (from html2haml), it doesn't work properly (Delete button can't remove relevant component in callback).
<script id='template-download' type='text/x-tmpl'>_x000D_
<![CDATA[_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
<tr class="template-download fade">_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
<span>{%=locale.fileupload.destroy%}</span>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}_x000D_
]]>_x000D_
</script>
_x000D_
So I use :plain
filter:
%script#template-download{:type => "text/x-tmpl"}_x000D_
:plain_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
<tr class="template-download fade">_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
<span>{%=locale.fileupload.destroy%}</span>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}
_x000D_
The converted result is exactly the same as the original.
So :plain
filter in this senario fits my need.
:plain Does not parse the filtered text. This is useful for large blocks of text without HTML tags, when you don’t want lines starting with . or - to be parsed.
For more detail, please refer to haml.info
For everyone coming to this thread with fractional seconds in your timestamp use:
to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')
Indeed, this is "very complicated in Java":
From: https://jersey.java.net/documentation/latest/client.html
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://foo").path("bar");
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();
If you're open to using RoboGuice, you can have the context injected into any class you want. Here's a small sample of how to do it with RoboGuice 2.0 (beta 4 at time of this writing)
import android.content.Context;
import android.os.Build;
import roboguice.inject.ContextSingleton;
import javax.inject.Inject;
@ContextSingleton
public class DataManager {
@Inject
public DataManager(Context context) {
Properties properties = new Properties();
properties.load(context.getResources().getAssets().open("data.properties"));
} catch (IOException e) {
}
}
}
Please check the following.
<canvas id="myCanvas" width="200" height="100"></canvas>
<div id="mydiv"></div>
JS:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle="red";
ctx.moveTo(0,100);
ctx.lineTo(200,0);
ctx.stroke();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
CSS:
html, body {
margin: 0;
padding: 0;
}
#myCanvas {
padding: 0;
margin: 0;
width: 200px;
height: 100px;
}
#mydiv {
position: absolute;
left: 0px;
right: 0;
height: 102px;
width: 202px;
background: rgba(255,255,255,0);
padding: 0;
margin: 0;
}
To summarise the other answers here – if you want finer control over the space between bullets and the text in a <li>
list item, your options are:
(1) Use a background image:
<style type="text/css">
li {
list-style-type:none;
background-image:url(bullet.png);
}
</style>
<ul>
<li>Some text</li>
</ul>
Advantages:
background-position
to position the image pretty much anywhere you want in relation to the text, using pixels, ems or %Disadvantages:
2. Use padding on the <li>
tag
<style type="text/css">
ul {padding-left:1em}
li {padding-left:1em}
</style>
<ul>
<li>Some text</li>
</ul>
Advantages:
<li>
, you can add as much extra horizontal space between the bullet and the text as you likeDisadvantages:
(3) Wrap the text in an extra <span>
element
<style type="text/css">
li {
padding-left:1em;
color:#f00; /* red bullet */
}
li span {
display:block;
margin-left:-0.5em;
color:#000; /* black text */
}
</style>
<ul>
<li><span>Some text</span></li>
</ul>
Advantages:
padding-top
to the <span>
. Someone else may have a workaround for this, though...)Disadvantages:
Here's hoping for some new list-style features in CSS4, so we can create smarter bullets without resorting to images or exta mark-up :)
public class Class1 {
private String extref="MY";
public String getExtref() {
return extref;
}
public String setExtref(String extref) {
return this.extref = extref;
}
public static void main(String[] args) {
Class1 obj=new Class1();
String value=obj.setExtref("AFF");
int returnedValue=getMethod(value);
System.out.println(returnedValue);
}
/**
* @param value
* @return
*/
private static int getMethod(String value) {
HashMap<Integer, String> hashmap1 = new HashMap<Integer, String>();
hashmap1.put(1,"MY");
hashmap1.put(2,"AFF");
if (hashmap1.containsValue(value))
{
for (Map.Entry<Integer,String> e : hashmap1.entrySet()) {
Integer key = e.getKey();
Object value2 = e.getValue();
if ((value2.toString()).equalsIgnoreCase(value))
{
return key;
}
}
}
return 0;
}
}
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
You need to use [[
, the programmatic equivalent of $
. Otherwise, for example, when i
is col1
, R will look for df$i
instead of df$col1
.
for(i in names(df)){
df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}
You can use
driver.execute_script("window.scrollTo(0, Y)")
where Y is the height (on a fullhd monitor it's 1080). (Thanks to @lukeis)
You can also use
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
to scroll to the bottom of the page.
If you want to scroll to a page with infinite loading, like social network ones, facebook etc. (thanks to @Cuong Tran)
SCROLL_PAUSE_TIME = 0.5
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
another method (thanks to Juanse) is, select an object and
label.sendKeys(Keys.PAGE_DOWN);
Easy way ,but you need bootstrap
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-envelope"></i></span> <!-- icon envelope "class="fa fa-envelope""-->
</div>
<input type="email" id="senha_nova" placeholder="Email">
</div><!-- input-group -->
You could try this:
$width:auto;
@mixin clearfix($width) {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
I'm not sure of your intended result, but setting a default value should return false.
You can try lubridate package which makes life much easier
library(lubridate)
mdy_hms(mydate)
The above will change the date format to POSIXct
A sample working example:
> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt"
For case with factor use as.character
data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))
By mysql 8 and later version, you cannot add a user by granting privileges. it means with this query:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'
IDENTIFIED BY 'type-root-password-here'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
mysql will return this error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'written password' at line 1
this means you don't have a root user for % domain. so you need to first insert the user and then grant privileges like this:
mysql> CREATE USER 'root'@'%' IDENTIFIED BY 'your password';
Query OK, 0 rows affected (0.11 sec)
mysql> GRANT ALL ON *.* TO 'root'@'%';
Query OK, 0 rows affected (0.15 sec)
mysql> FLUSH PRIVILEGES;
Dont forget to replace passwords with your specific passwords.
When doing pan_list.append(p.last)
you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None
).
You should do something like this :
last_list=[]
if p.last_name==None or p.last_name=="":
pass
last_list.append(p.last) # Here I modify the last_list, no affectation
print last_list
How to: Use a Background Thread to Search for Files
You have to be very carefull with access from other threads to GUI specific stuff (it is common for many GUI toolkits). If you want to update something in GUI from processing thread check this answer that I think is useful for WinForms. For WPF see this (it shows how to touch component in UpdateProgress() method so it will work from other threads, but actually I don't like it is not doing CheckAccess()
before doing BeginInvoke
through Dispathcer, see and search for CheckAccess in it)
Was looking .NET specific book on threading and found this one (free downloadable). See http://www.albahari.com/threading/ for more details about it.
I believe you will find what you need to launch execution as new thread in first 20 pages and it has many more (not sure about GUI specific snippets I mean strictly specific to threading). Would be glad to hear what community thinks about this work 'cause I'm reading this one. For now looked pretty neat for me (for showing .NET specific methods and types for threading). Also it covers .NET 2.0 (and not ancient 1.1) what I really appreciate.
This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.
Here is a good post on permanent generation.
I like the descriptions given for each space in Oracle's guide on JConsole:
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.
- Eden Space (heap): The pool from which memory is initially allocated for most objects.
- Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
- Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
- Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
- Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.
Disclaimer: I'm not supporting this answer anymore (I was blind at that time). But thanks for the up-votes =P
You can take this as basis. From WordPress, used to generate pretty urls (the entry point is the slugify() function):
/**
* Converts all accent characters to ASCII characters.
*
* If there are no accent characters, then the string given is just returned.
*
* @param string $string Text that might have accent characters
* @return string Filtered string with replaced "nice" characters.
*/
function remove_accents($string) {
if (!preg_match('/[\x80-\xff]/', $string))
return $string;
if (seems_utf8($string)) {
$chars = array(
// Decompositions for Latin-1 Supplement
chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
chr(195).chr(191) => 'y',
// Decompositions for Latin Extended-A
chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
// Euro Sign
chr(226).chr(130).chr(172) => 'E',
// GBP (Pound) Sign
chr(194).chr(163) => '');
$string = strtr($string, $chars);
} else {
// Assume ISO-8859-1 if not UTF-8
$chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
.chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
.chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
.chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
.chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
.chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
.chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
.chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
.chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
.chr(252).chr(253).chr(255);
$chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
$string = strtr($string, $chars['in'], $chars['out']);
$double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
$double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
$string = str_replace($double_chars['in'], $double_chars['out'], $string);
}
return $string;
}
/**
* Checks to see if a string is utf8 encoded.
*
* @author bmorel at ssi dot fr
*
* @param string $Str The string to be checked
* @return bool True if $Str fits a UTF-8 model, false otherwise.
*/
function seems_utf8($Str) { # by bmorel at ssi dot fr
$length = strlen($Str);
for ($i = 0; $i < $length; $i++) {
if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n = 1; # 110bbbbb
elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n = 2; # 1110bbbb
elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n = 3; # 11110bbb
elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n = 4; # 111110bb
elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n = 5; # 1111110b
else return false; # Does not match any model
for ($j = 0; $j < $n; $j++) { # n bytes matching 10bbbbbb follow ?
if ((++$i == $length) || ((ord($Str[$i]) & 0xC0) != 0x80))
return false;
}
}
return true;
}
function utf8_uri_encode($utf8_string, $length = 0) {
$unicode = '';
$values = array();
$num_octets = 1;
$unicode_length = 0;
$string_length = strlen($utf8_string);
for ($i = 0; $i < $string_length; $i++) {
$value = ord($utf8_string[$i]);
if ($value < 128) {
if ($length && ($unicode_length >= $length))
break;
$unicode .= chr($value);
$unicode_length++;
} else {
if (count($values) == 0) $num_octets = ($value < 224) ? 2 : 3;
$values[] = $value;
if ($length && ($unicode_length + ($num_octets * 3)) > $length)
break;
if (count( $values ) == $num_octets) {
if ($num_octets == 3) {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
$unicode_length += 9;
} else {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
$unicode_length += 6;
}
$values = array();
$num_octets = 1;
}
}
}
return $unicode;
}
/**
* Sanitizes title, replacing whitespace with dashes.
*
* Limits the output to alphanumeric characters, underscore (_) and dash (-).
* Whitespace becomes a dash.
*
* @param string $title The title to be sanitized.
* @return string The sanitized title.
*/
function slugify($title) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
$title = remove_accents($title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:
[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
public string Name;
}
public class Derived : Base
{
public string Something;
}
Now when you serialize object in json will be add "$type"
with "base"
and "derived"
value and it will be use for deserialize
Serialized list example:
[
{"Name":"some name", "$type":"base"},
{"Name":"some name", "Something":"something", "$type":"derived"}
]
You could use the Chr(int) function
select * from [Server].[database].[schema].[tablename]
This is the correct way to call. Be sure to verify that the servers are linked before executing the query!
To check for linked servers call:
EXEC sys.sp_linkedservers
I just had to do this myself, so I thought I would post another answer here.
Here is another way to create a rounded corner border and clip its inner content. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.
The xaml:
<Border
Width="200"
Height="25"
CornerRadius="11"
Background="#FF919194"
>
<Border.Clip>
<RectangleGeometry
RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
>
<RectangleGeometry.Rect>
<MultiBinding
Converter="{StaticResource widthAndHeightToRectConverter}"
>
<Binding
Path="ActualWidth"
RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
/>
<Binding
Path="ActualHeight"
RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
/>
</MultiBinding>
</RectangleGeometry.Rect>
</RectangleGeometry>
</Border.Clip>
<Rectangle
Width="100"
Height="100"
Fill="Blue"
HorizontalAlignment="Left"
VerticalAlignment="Center"
/>
</Border>
The code for the converter:
public class WidthAndHeightToRectConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)values[0];
double height = (double)values[1];
return new Rect(0, 0, width, height);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"
It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"
Everything worked after that. I believe this could be a bug in the Spring JDBC core package...
find . -type d -print0 | xargs -0 -n 1 my_command
Assuming you are using VSTS run vsts-npm-auth -config .npmrc
to generate new .npmrc file with the auth token
The other post is correct to resolve the issue but doesn't address how to do it if the 2-step-verification is turned on. The option to allow the less secure apps is NOT available then. Here is an answer to how to do it:
a. Go to the URL of `https://myaccount.google.com/` and click `Sing-in and security`
b. Click on the app password.
You will reach a page like this,
c. Create name of your app and generate a password for the respective app.
d. Use that password acquired here inside the app.
This should resolve the issue.
Your second date is before your first date (ie. you are querying between September 29 2010 and January 30 2010). Try reversing the order of the dates:
SELECT *
FROM `objects`
WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')
You're going to have a hard time writing to the same file you're reading from. One quick way is to simply do this:
File.WriteAllText("test.txt", File.ReadAllText("test.txt").Replace("some text","some other text"));
You can lay that out better with
string str = File.ReadAllText("test.txt");
str = str.Replace("some text","some other text");
File.WriteAllText("test.txt", str);
So this is my final code after googling for 2 days on how to add a namespace and make soap request along with the SOAP envelope without adding proxy/Service Reference
class Request
{
public static void Execute(string XML)
{
try
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(AppendEnvelope(AddNamespace(XML)));
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static HttpWebRequest CreateWebRequest()
{
string ICMURL = System.Configuration.ConfigurationManager.AppSettings.Get("ICMUrl");
HttpWebRequest webRequest = null;
try
{
webRequest = (HttpWebRequest)WebRequest.Create(ICMURL);
webRequest.Headers.Add(@"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return webRequest;
}
private static string AddNamespace(string XML)
{
string result = string.Empty;
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(XML);
XmlElement temproot = xdoc.CreateElement("ws", "Request", "http://example.com/");
temproot.InnerXml = xdoc.DocumentElement.InnerXml;
result = temproot.OuterXml;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;
}
private static string AppendEnvelope(string data)
{
string head= @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" ><soapenv:Header/><soapenv:Body>";
string end = @"</soapenv:Body></soapenv:Envelope>";
return head + data + end;
}
}
git fetch
git branch -r
git checkout <branch_name>
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
I had the same issue but in this case microsoft-ace-oledb-12-0-provider was already installed on my machine and working fine for other application developed.
The difference between those application and the one with I had the problem was the Old Applications were running on "Local IIS" whereas the one with error was on "IIS Express(running from Visual Studio"). So what I did was-
- Right Click on Project Name.
- Go to Properties
- Go to Web Tab on the right.
- Under Servers select Local IIS and click on Create Virtual Directory button.
- Run the application again and it worked.
In TortoiseSVN you can access and modify some settings in the context menu "Settings/General" in explorer.
E.g. the "Global ignore pattern" can be edited directly in the dialog box. Such changings are the stored in the registry as bahrep pointed out in her answer.
(Win10/TortoiseSVN 1.13.1, Build 28686 - 64 Bit)
You may use this to access a specific folder and get particular image
public void Retrieve(String path, String Name)
{
File imageFile = new File(path+Name);
if(imageFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
myImage = (ImageView) findViewById(R.id.savedImage);
myImage.setImageBitmap(myBitmap);
Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();
}
}
And then you can call it by
Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();
The checking of the presence of the member before assigning it is, in my opinion, quite ugly.
Kohana has a useful function to make selecting parameters simple.
You can make your own like so...
function arrayGet($array, $key, $default = NULL)
{
return isset($array[$key]) ? $array[$key] : $default;
}
And then do something like...
$page = arrayGet($_GET, 'p', 1);
New-style classes have an mro
method you can call which returns a list of parent classes in method resolution order.
The key things here are
That means we need to not just copy the objects to a new array (or a target array), but also create copies of the objects.
...use map
to create a new array, and copy the objects as you go:
const newArray = sourceArray.map(obj => /*...create and return copy of `obj`...*/);
...where the copy operation is whatever way you prefer to copy objects, which varies tremendously project to project based on use case. That topic is covered in depth in the answers to this question. But for instance, if you only want to copy the objects but not any objects their properties refer to, you could use spread notation (ES2015+):
const newArray = sourceArray.map(obj => ({...obj}));
That does a shallow copy of each object (and of the array). Again, for deep copies, see the answers to the question linked above.
Here's an example using a naive form of deep copy that doesn't try to handle edge cases, see that linked question for edge cases:
function naiveDeepCopy(obj) {
const newObj = {};
for (const key of Object.getOwnPropertyNames(obj)) {
const value = obj[key];
if (value && typeof value === "object") {
newObj[key] = {...value};
} else {
newObj[key] = value;
}
}
return newObj;
}
const sourceArray = [
{
name: "joe",
address: {
line1: "1 Manor Road",
line2: "Somewhere",
city: "St Louis",
state: "Missouri",
country: "USA",
},
},
{
name: "mohammed",
address: {
line1: "1 Kings Road",
city: "London",
country: "UK",
},
},
{
name: "shu-yo",
},
];
const newArray = sourceArray.map(naiveDeepCopy);
// Modify the first one and its sub-object
newArray[0].name = newArray[0].name.toLocaleUpperCase();
newArray[0].address.country = "United States of America";
console.log("Original:", sourceArray);
console.log("Copy:", newArray);
_x000D_
.as-console-wrapper {
max-height: 100% !important;
}
_x000D_
...and you want to append the contents of the source array to it, you can use push
and a loop:
for (const obj of sourceArray) {
destinationArray.push(copy(obj));
}
Sometimes people really want a "one liner," even if there's no particular reason for it. If you refer that, you could create a new array and then use spread notation to expand it into a single push
call:
destinationArray.push(...sourceArray.map(obj => copy(obj)));
You can execute commands in parallel with start
like this:
start "" ping myserver
start "" nslookup myserver
start "" morecommands
They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.
Hope this helps!
You can use getattr
getattr(module, class_name)
to access the class. More complete code:
module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()
As mentioned below, we may use importlib
import importlib
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)
instance = class_()
It is because creator of the SSIS packages is someone else and other person is executing the packages.
If suppose A person has created SSIS packages and B person is trying to execute than the above error comes.
You can solve the error by changing creator name from package properties from A to B.
Thanks, Kiran Sagar
Classes that start with "apple-" plus classes that contain " apple-"
$("div[class^='apple-'],div[class*=' apple-']")
Just declare the enum outside the bounds of the class. Like this:
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
...
}
Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
log2(x) = log10(x) / log10(2)
Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.
Assuming terminal Vim on a flavor of *nix:
Ctrl + Z
will suspend the process and get back to your shell
fg
will resume (bring to foreground) your suspended Vim.
Start a subshell using:
:sh
(as configured by)
:set shell?
:!bash
followed by:
Ctrl+D (or exit
, but why type so much?)
to kill the shell and return to Vim.
For Rails (at least in my case) if you are using the angularjs-rails gem, please remember to add the sanitize module
//= require angular
//= require angular-sanitize
And then load it up in your app...
var myDummyApp = angular.module('myDummyApp', ['ngSanitize']);
Then you can do the following:
On the template:
%span{"ng-bind-html"=>"phone_with_break(x)"}
And eventually:
$scope.phone_with_break = function (x) {
if (x.phone != "") {
return x.phone + "<br>";
}
return '';
}
It may not be the elegant way but you can iterate all classes in the assembly and invoke Type.IsSubclassOf(AbstractDataExport)
for each one.
I know this question is old and has lots of great answers but I post this answer because of it's new flavor (es5+)
Object.defineProperties(JSON, {_x000D_
refStringify: {_x000D_
value: function(obj) {_x000D_
_x000D_
let objMap = new Map();_x000D_
let stringified = JSON.stringify(obj,_x000D_
function(key, value) {_x000D_
_x000D_
// only for objects_x000D_
if (typeof value == 'object') {_x000D_
// If has the value then return a reference to it_x000D_
if (objMap.has(value))_x000D_
return objMap.get(value);_x000D_
_x000D_
objMap.set(value, `ref${objMap.size + 1}`);_x000D_
}_x000D_
return value;_x000D_
});_x000D_
return stringified;_x000D_
}_x000D_
},_x000D_
refParse: {_x000D_
value: function(str) {_x000D_
_x000D_
let parsed = JSON.parse(str);_x000D_
let objMap = _createObjectMap(parsed);_x000D_
objMap.forEach((value, key) => _replaceKeyWithObject(value, key));_x000D_
return parsed;_x000D_
}_x000D_
},_x000D_
});_x000D_
_x000D_
// *************************** Example_x000D_
let a = {_x000D_
b: 32,_x000D_
c: {_x000D_
get a() {_x000D_
return a;_x000D_
},_x000D_
get c() {_x000D_
return a.c;_x000D_
}_x000D_
}_x000D_
};_x000D_
let stringified = JSON.refStringify(a);_x000D_
let parsed = JSON.refParse(stringified, 2);_x000D_
console.log(parsed, JSON.refStringify(parsed));_x000D_
// *************************** /Example_x000D_
_x000D_
// *************************** Helper_x000D_
function _createObjectMap(obj) {_x000D_
_x000D_
let objMap = new Map();_x000D_
JSON.stringify(obj, (key, value) => {_x000D_
if (typeof value == 'object') {_x000D_
if (objMap.has(value))_x000D_
return objMap.get(value);_x000D_
objMap.set(value, `ref${objMap.size + 1}`);_x000D_
_x000D_
}_x000D_
return value;_x000D_
});_x000D_
return objMap;_x000D_
}_x000D_
_x000D_
function _replaceKeyWithObject(key, obj, replaceWithObject = obj) {_x000D_
_x000D_
Object.keys(obj).forEach(k => {_x000D_
_x000D_
let val = obj[k];_x000D_
if (val == key)_x000D_
return (obj[k] = replaceWithObject);_x000D_
if (typeof val == 'object' && val != replaceWithObject)_x000D_
_replaceKeyWithObject(key, val, replaceWithObject);_x000D_
});_x000D_
}
_x000D_
If you're talking about XML-files (ISO-8859-1), the XML-declaration inside them specifies the encoding: <?xml version="1.0" encoding="ISO-8859-1" ?>
So, you can use regular expressions (e.g. with perl
) to check every file for such specification.
More information can be found here: How to Determine Text File Encoding.
I had the same problem and error. In my case it was the https_proxy not set. Setting the https_proxy environment variable fixed the issue.
$ export https_proxy=https://<porxy_addres>:<proxy_port>
Example:
$ export https_proxy=https://my.proxy.company.com:8000
Hope this help somebody.
Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start
Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/
If you installed WAMP to c:\wamp
then I believe your webserver root directory would be c:\wamp\www
, however this might vary depending on version.
Yes, this is where you would put your site files to access them through a browser.
That seems to work for me:
<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>
The expected behaviour is to change the colour of the word "fruit".
Perhaps your document was not fully loaded when you called the routine?
For those not getting a solution for older answers, i simply put my file name as the very first line in my code.
like so
#ruby_file_name_here.rb
puts "hello world"
You're trying to assign the return value of clients.get(clients.size())
to the string hey
, but the object returned is a ClientThread
, not a string. As Andre mentioned, you need to use the proper index as well.
As far as your second error is concerned, there is no static method remove()
on the type ClientThread
. Really, you likely wanted the remove method of your List
instance, clients
.
You can remove the last item from the list, if there is one, as follows. Since remove also returns the object that was removed, you can capture the return and use it to print out the name:
int size = clients.size();
if (size > 0) {
ClientThread client = clients.remove(size - 1);
System.out.println(client + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());
}
To reduce verbosity, you can use a static import:
import static java.util.concurrent.TimeUnit.NANOSECONDS;
-and henceforth just type
NANOSECONDS.toSeconds(elapsedTime);
If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.
Documentation is at http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping
This is because map.keys()
returns an iterator. *ngFor
can work with iterators, but the map.keys()
will be called on every change detection cycle, thus producing a new reference to the array, resulting in the error you see. By the way, this is not always an error as you would traditionally think of it; it may even not break any of your functionality, but suggests that you have a data model which seems to behave in an insane way - changing faster than the change detector checks its value.
If you do no want to convert the map to an array in your component, you may use the pipe suggested in the comments. There is no other workaround, as it seems.
P.S. This error will not be shown in the production mode, as it is more like a very strict warning, rather than an actual error, but still, this is not a good idea to leave it be.
Don't forget TemplatedParent:
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
or
{Binding RelativeSource={RelativeSource TemplatedParent}}
The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells. You can find a detailed description here: Google Script count coloured with reference, but the code is below:
function countColoured(reference) {
var sheet = SpreadsheetApp.getActiveSheet();
var formula = SpreadsheetApp.getActiveRange().getFormula();
var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
try {
if (args.length == 1) {
var range = sheet.getRange(args[0]);
}
else {
sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
range = sheet.getRange(args[1]);
}
}
catch(e) {
throw new Error(args.join('!') + ' is not a valid range');
}
var c = 0;
var numRows = range.getNumRows();
var numCols = range.getNumColumns();
for (var i = 1; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++) {
c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
}
}
return c > 0 ? c : "" ;
}
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
Command to put list of all files and folders into a text file is as below:
Eg: dir /b /s | sort > ListOfFilesFolders.txt
We can have this in 2 ways,
Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within
ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons
Or
Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code
if (Request.Form["btnSubmit1"] != null)
{
//
}
if (Request.Form["btnSubmit2"] != null)
{
//
}
You can use cmd + ; for Mac or Ctrl + Alt + Shift + S for Windows/Linux to pull up the Project Structure dialog. In there, you can set the JDK location as well as the Android SDK location.
To get your JDK location, run /usr/libexec/java_home -v 1.7
in terminal. Send 1.7 for Java 7 or 1.8 for Java 8.
TextPad will allow you to perform this operation.
example:
test this sentence
Find what: \([^ ]*\) \(.*\)
Replace with: \U\1\E \2
the \U
will cause all following chars to be upper
the \E
will turn off the \U
the result will be:
TEST this sentence
$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")
Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {
$record = $indexName
foreach ($property in $_.PSObject.Properties){
#doSomething $property.Name, $property.Value
if($property.Name -like '*TextWrittenAsNumber*'){
$record = $record + "," + '"' + $property.Value + '"'
}
else{
$record = $record + "," + $property.Value
}
}
$array.add($record) | out-null
#write-host $record
}
Please don't use this recipe if your situation is not the one described in the question. This recipe is for fixing a bad merge, and replaying your good commits onto a fixed merge.
Although filter-branch
will do what you want, it is quite a complex command and I would probably choose to do this with git rebase
. It's probably a personal preference. filter-branch
can do it in a single, slightly more complex command, whereas the rebase
solution is performing the equivalent logical operations one step at a time.
Try the following recipe:
# create and check out a temporary branch at the location of the bad merge
git checkout -b tmpfix <sha1-of-merge>
# remove the incorrectly added file
git rm somefile.orig
# commit the amended merge
git commit --amend
# go back to the master branch
git checkout master
# replant the master branch onto the corrected merge
git rebase tmpfix
# delete the temporary branch
git branch -d tmpfix
(Note that you don't actually need a temporary branch, you can do this with a 'detached HEAD', but you need to take a note of the commit id generated by the git commit --amend
step to supply to the git rebase
command rather than using the temporary branch name.)
I would rather use Last()
from LINQ to do it.
rows = rows.Remove(rows.Last());
or
rows = rows.Remove(rows.LastOrDefault());
Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.
You can even add a dummy div
to the container and set something like padding-top: 56.25%
to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).
Padding and margin use the percentage of the width, that's really the trick here.
Consider using the MySQL Installer for Windows as it installs and updates the various MySQL products on your system, including MySQL Server, MySQL Workbench, and MySQL Notifier. The Notifier monitors your MySQL instances so you'll know if MySQL is running, and it can also be used to start/stop MySQL.
In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):
-Droot.log.level=TRACE
Now Chrome is multi-user so Extensions
should be nested under the OS user profile then the Chrome user profile, My first Chrome user was called Profile 1
, my Extensions
path was C:\Users\
username
\AppData\Local\Google\Chrome\User Data\
Profile 1
\Extensions\
.
To find yours Navigate to chrome://version/
(I use about:
out of laziness).
Notice the Profile Path
and just append \Extensions\
and you have yours.
Hope this brings this info on this question up to date more.