for large numbers that display with scientific notation set format to just '#'
Short Answer: YES
You can absolutely make a simple rounded button without the need of an additional background image or writing any code for the same. Just follow the screenshot given below, to set the runtime attributes for the button, to get the desired result.
It won't show in the Storyboard
but it will work fine when you run the project.
Note:
The 'Key Path' layer.cornerRadius
and value is 5. The value needs to be changed according to the height and width of the button. The formula for it is the height of button * 0.50. So play around the value to see the expected rounded button in the simulator or on the physical device. This procedure will look tedious when you have more than one button to be rounded in the storyboard.
Just to update this answer unless anyone comes across this later, since JDK 6 you can use
File file = new File('/directory/to/file');
file.setWritable(boolean);
file.setReadable(boolean);
file.setExecutable(boolean);
you can find the documentation on Oracle File(Java Platform SE 7). Bear in mind that these commands only work if the current working user has ownership or write access to that file. I am aware that OP wanted chmod type access for more intricate user configuration. these will set the option across the board for all users.
In my case the problem was that the path was enclosed in quotation marks ("):
-vm
"C:\Program Files\Java\jdk1.8.0_25\bin"
Removing them fixed the problem:
-vm
C:\Program Files\Java\jdk1.8.0_25\bin
Just a hunch, but check out this article on Django template loading. In particular, make sure you have django.template.loaders.app_directories.Loader
in your TEMPLATE_LOADERS list.
The help for %in%, help("%in%")
, includes, in the Examples section, this definition of not in,
"%w/o%" <- function(x, y) x[!x %in% y] #-- x without y
Lets try it:
c(2,3,4) %w/o% c(2,8,9)
[1] 3 4
Alternatively
"%w/o%" <- function(x, y) !x %in% y #-- x without y
c(2,3,4) %w/o% c(2,8,9)
# [1] FALSE TRUE TRUE
Use escape characters: "full\\path\\here"
, "\\"
and "\\\\"
The fastest way to parse HTML in Chrome and Firefox is Range#createContextualFragment:
var range = document.createRange();
range.selectNode(document.body); // required in Safari
var fragment = range.createContextualFragment('<h1>html...</h1>');
var firstNode = fragment.firstChild;
I would recommend to create a helper function which uses createContextualFragment if available and falls back to innerHTML otherwise.
Benchmark: http://jsperf.com/domparser-vs-createelement-innerhtml/3
I used this and it works well:
string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));
foreach (string file in filePaths)
{
if (comboBox1.SelectedItem.ToString() == "")
{
if (file.Contains("c"))
{
comboBox2.Items.Add(Path.GetFileName(file));
}
}
}
yourValue.ToString("0.00") will work.
i have a solution for dynamically created variable value and combined all value in a variable.
if($_SERVER['REQUEST_METHOD']=='POST'){
$r=0;
for($i=1; $i<=4; $i++){
$a = $_POST['a'.$i];
$r .= $a;
}
echo $r;
}
If you're using this for currency, and also want the value to be seperated by ,
's you can use
$ {:,.f2}.format(currency_value)
.
e.g.:
currency_value = 1234.50
$ {:,.f2}.format(currency_value)
-->
$ 1,234.50
Here is a bit of code I wrote some time ago:
print("> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format(total_paid))
> At the end of year 1 total paid is $ 43,806.36
> At the end of year 2 total paid is $ 87,612.72
> At the end of year 3 total paid is $ 131,419.08
> At the end of year 4 total paid is $ 175,225.44
> At the end of year 5 total paid is $ 219,031.80 <-- Note .80 and not .8
> At the end of year 6 total paid is $ 262,838.16
> At the end of year 7 total paid is $ 306,644.52
> At the end of year 8 total paid is $ 350,450.88
> At the end of year 9 total paid is $ 394,257.24
> At the end of year 10 total paid is $ 438,063.60 <-- Note .60 and not .6
> At the end of year 11 total paid is $ 481,869.96
> At the end of year 12 total paid is $ 525,676.32
> At the end of year 13 total paid is $ 569,482.68
> At the end of year 14 total paid is $ 613,289.04
> At the end of year 15 total paid is $ 657,095.40 <-- Note .40 and not .4
> At the end of year 16 total paid is $ 700,901.76
> At the end of year 17 total paid is $ 744,708.12
> At the end of year 18 total paid is $ 788,514.48
> At the end of year 19 total paid is $ 832,320.84
> At the end of year 20 total paid is $ 876,127.20 <-- Note .20 and not .2
Use it like this
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:maxLines = "AN_INTEGER"
android:scrollbars = "vertical"
/>
Use the json
module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
If you need the JSON result string in Python itself, use json.dumps()
(added s
, for 'string'):
json_string = json.dumps(row)
The L
is just Python syntax for a long integer value; the json
library knows how to handle those values, no L
will be written.
Demo string output:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).
I traversed the collection of UIWebView's subviews and set their backgrounds to [UIColor blackColor], the same color as the webpage background. The view will still bounce but it will not show that ugly dark grey background.
Take a look at ImageView.ScaleType to control and understand the way resizing happens in an ImageView
. When the image is resized (while maintaining its aspect ratio), chances are that either the image's height or width becomes smaller than ImageView
's dimensions.
>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
>> tic; ind=find(ismember(strs,'KU')); toc
Elapsed time is 0.001976 seconds.
>> tic; find(strcmp('KU', strs)); toc
Elapsed time is 0.000014 seconds.
SO, clearly strcmp('KU', strs)
takes much lesser time than ismember(strs,'KU')
You can do this with a data URL. This includes the entire document in a single string of HTML. For example, the following HTML:
<html><body>foo</body></html>
can be encoded as this:
data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E
and then set as the src
attribute of the iframe. Example.
Edit: The other alternative is to do this with Javascript. This is almost certainly the technique I'd choose. You can't guarantee how long a data URL the browser will accept. The Javascript technique would look something like this:
var iframe = document.getElementById('foo'),
iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML = 'Hello world';
Edit 2 (December 2017): use the Html5's srcdoc attribute, just like in Saurabh Chandra Patel's answer, who now should be the accepted answer! If you can detect IE/Edge efficiently, a tip is to use srcdoc-polyfill library only for them and the "pure" srcdoc attribute in all non-IE/Edge browsers (check caniuse.com to be sure).
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
Since I only use admin interface in my app, I put this in the admin.py :
admin.site.site_header = 'My administration'
private Uri imageUri;
....
Intent intent = new Intent(this, GoogleActivity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
this.finish();
And then you can fetch it like this:
imageUri = Uri.parse(extras.getString("imageUri"));
You can't cast explicitly anything to a String
that isn't a String
. You should use either:
"" + myInt;
or:
Integer.toString(myInt);
or:
String.valueOf(myInt);
I prefer the second form, but I think it's personal choice.
Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer
(in Java 1.4) or a StringBuilder
in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix)
that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.
Edit 2 I assumed you meant that your integer was an int
and not an Integer
. If it's already an Integer
, just use toString()
on it and be done.
substring(int startpos, int lenght);
I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.
/**
* Delets a dir recursively deleting anything inside it.
* @param dir The dir to delete
* @return true if the dir was successfully deleted
*/
public static boolean deleteDirectory(File dir) {
if(! dir.exists() || !dir.isDirectory()) {
return false;
}
String[] files = dir.list();
for(int i = 0, len = files.length; i < len; i++) {
File f = new File(dir, files[i]);
if(f.isDirectory()) {
deleteDirectory(f);
}else {
f.delete();
}
}
return dir.delete();
}
find
is the common tool for this kind of task :
find ./my_dir -mtime +10 -type f -delete
EXPLANATIONS
./my_dir
your directory (replace with your own)-mtime +10
older than 10 days-type f
only files-delete
no surprise. Remove it to test your find
filter before executing the whole commandAnd take care that ./my_dir
exists to avoid bad surprises !
Step 1. Add 'MvcConfig.java' to your project.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
Step 2. Add configure(WebSecurity web)
override to your SecurityConfig class
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}
Step 3. Place all static resources in webapp/resources/..
It failed because there is no server install on your computer. You need to Download 'MySQL Community Server 8.0.17' & restart your server.
Here are some demo & short cuts if you uses GitHub, the basic ideas are the same.
1. Open terminal like this
2. Paste the below command to terminal followed by a space and then paste the path of the .xcuserstate file simply like this
3. Make sure you have the correct git ignore and then commit the code :)
That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.
For example:
$ cat t.c
#include <stdio.h>
int main()
{
printf("hello\n");
return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0
0x400534
is the address of main
in my case. 0x400408
is also a valid function address in a.out
, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init
. You can see the layout of your executable with readelf -a your_exe
.)
Other times when addr2line
will fail is if you're including a library that has no debug information.
Use this single line and hopefully you will achieve the best result;
use:
android:elevation="3dp"
Adjust the size as much as you need and this is the best and simplest way to achieve the shadow like buttons and other default android shadows.
Let me know if it worked!
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
You can use int()
function to convert float64
type data to an int
. Similarly you can use float64()
Example:
func check(n int) bool {
// count the number of digits
var l int = countDigit(n)
var dup int = n
var sum int = 0
// calculates the sum of digits
// raised to power
for dup > 0 {
**sum += int(math.Pow(float64(dup % 10), float64(l)))**
dup /= 10
}
return n == sum
}
This should get you started:
log4j.rootLogger=QuietAppender, LoudAppender, TRACE
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=quiet.log
...
# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=loud.log
...
log4j.logger.com.yourpackage.yourclazz=TRACE
It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]
?
To change color of the font colour, first select attributed instead of plain like in the image below
You then need to select the text in the attributed field and then select the color button on the right-hand side of the alignments. This will change the color.
You can simply use (char) System.in.read();
casting to char
is necessary to convert int
to char
I quote Andrew Dunstan on the pgsql-hackers list:
At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.
Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.
Offers an arsenal of new functions and operators to add "json-processing".
The answer to the original question in Postgres 9.3:
SELECT *
FROM json_array_elements(
'[{"name": "Toby", "occupation": "Software Engineer"},
{"name": "Zaphod", "occupation": "Galactic President"} ]'
) AS elem
WHERE elem->>'name' = 'Toby';
Advanced example:
For bigger tables you may want to add an expression index to increase performance:
Adds jsonb
(b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb
also supports GIN, btree and hash indexes, GIN being the most potent of these.
json
and jsonb
data types and functions.The manual goes as far as suggesting:
In general, most applications should prefer to store JSON data as
jsonb
, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.
Bold emphasis mine.
Performance benefits from general improvements to GIN indexes.
Complete jsonb
functions and operators. Add more functions to manipulate jsonb
in place and for display.
I had the exact same error (on windows 7) and the cause was different. I solved it in a different way so I thought I'd add the cause and solution here for others.
Even though the error seemed to point to heroku really the error was saying "Heroku can't get to the git repository"
. I swore I had the same keys on all the servers because I created it and uploaded it to one after the other at the same time.
After spending almost a day on this I realized that because git was only showing me the fingerprint and not the actual key. I couldn't verify that it's key matched the one on my HD or heroku. I looked in the known hosts file and guess what... it shows the keys for each server and I was able to clearly see that the git and heroku public keys did not match.
1) I deleted all the files in my key folder, the key from github using their website, and the key from heroku using git bash and the command heroku keys:clear
2) Followed github's instructions here to generate a new key pair and upload the public key to git
3) using git bash-
heroku keys:add
to upload the same key to heroku.
Now git push heroku master
works.
what a nightmare, hope this helped somebody.
Bryan
You have to know if the problem come from the listener or from the database.
So first, restart the listener, it could solve the problem.
Second, it could come from the db if it's not in open mode (nomount, mount, restrict). To check it, connect locally and do the following query:
sqlplus /nolog
connect / as sysdba
SQL> select instance_name, status, database_status from v$instance;
Because (
is special in regex, you should escape it \(
when matching. However, depending on what language you are using, you can easily match (
with string methods like index()
or other methods that enable you to find at what position the (
is in. Sometimes, there's no need to use regex.
Complementing the other answers, you can use the option --no-cache-dir
to disable caching in pip. My virtual machine was crashing when installing many packages at once with pip install -r requirements.txt
. What solved for me was:
pip install --no-cache-dir -r requirements.txt
I had a similar issue where the SelectedItem never got updated.
My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.
public override bool Equals(object obj)
{
return this.Id == (obj as MyCustomObject).Id;
}
HashMap<Integer,String> hs1 = new HashMap<>();
hs1.put(1,"ram");
hs1.put(2,"sita");
hs1.put(3,"laxman");
hs1.put(4,"hanuman");
hs1.put(5,"geeta");
HashMap<Integer,String> hs2 = new HashMap<>();
hs2.put(5,"rat");
hs2.put(6,"lion");
hs2.put(7,"tiger");
hs2.put(8,"fish");
hs2.put(9,"hen");
HashMap<Integer,String> hs3 = new HashMap<>();//Map is which we add
hs3.putAll(hs1);
hs3.putAll(hs2);
System.out.println(" hs1 : " + hs1);
System.out.println(" hs2 : " + hs2);
System.out.println(" hs3 : " + hs3);
Duplicate items will not be added(that is duplicate keys) as when we will print hs3 we will get only one value for key 5 which will be last value added and it will be rat. **[Set has a property of not allowing the duplicate key but values can be duplicate]
I was encountering this error while compiling my application with SDL. This was caused by SDL defining it's own main function in SDL_main.h. To prevent SDL define the main function an SDL_MAIN_HANDLED macro has to be defined before the SDL.h header is included.
A strategy would consist in using ANT to simplify the removal of the signature from each Jar file. It would proceed with the following steps:
Here is an ANT macrodef doing the work:
<macrodef name="unsignjar" description="To unsign a specific Jar file">
<attribute name="jarfile"
description="The jar file to unsign" />
<sequential>
<!-- Copying to the temporary manifest file -->
<copy toFile="@{jarFile}_MANIFEST.tmp">
<resources>
<zipentry zipfile="@{jarFile}" name="META-INF/MANIFEST.MF"/>
</resources>
</copy>
<!-- Removing the Name and SHA entries from the temporary file -->
<replaceregexp file="@{jarFile}_MANIFEST.tmp" match="\nName:(.+?)\nSH" replace="SH" flags="gis" byline="false"/>
<replaceregexp file="@{jarFile}_MANIFEST.tmp" match="SHA(.*)" replace="" flags="gis" byline="false"/>
<!-- Creating a temporary Jar file with the temporary manifest -->
<jar jarfile="@{jarFile}.tmp"
manifest="@{jarFile}_MANIFEST.tmp">
<zipfileset src="@{jarFile}">
<include name="**"/>
<exclude name="META-INF/*.SF"/>
<exclude name="META-INF/*.DSA"/>
<exclude name="META-INF/*.RSA"/>
</zipfileset>
</jar>
<!-- Removing the temporary manifest -->
<delete file="@{jarFile}_MANIFEST.tmp" />
<!-- Swapping the original Jar file with the temporary one -->
<move file="@{jarFile}.tmp"
tofile="@{jarFile}"
overwrite="true" />
</sequential>
`
The definition can then be called this way in an ANT task:
<target name="unsignJar">
<unsignjar jarFile="org.test.myjartounsign.jar" />
</target>
The ideal datatype for storing Lat Long values in SQL Server is decimal(9,6)
As others have said, this is at approximately 10cm precision, whilst only using 5 bytes of storage.
e.g. CAST(123.456789 as decimal(9,6)) as [LatOrLong]
If you are using mac-OS , export JAVA_HOME=/usr/libexec/java_home
need to be changed to export JAVA_HOME=$(/usr/libexec/java_home)
.
Steps to do this :
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
where /usr/libexec/java_home
is the path of your jvm
There is an easier way which works for all buttons, just change appearance of buttons in your theme, try this:
in values-21/styles.xml
<resources>
<style name="myBaseTheme"
parent="@android:style/Theme.Material.Light">
<item name="android:colorPrimary">@color/bg</item>
<item name="android:colorPrimaryDark">@color/bg_p</item>
<item name="android:textAppearanceButton">@style/textAppearanceButton</item>
</style>
<style name="textAppearanceButton" parent="@android:style/TextAppearance.Material.Widget.Button">
<item name="android:textAllCaps">false</item>
</style>
</resources>
PS: it's recommended to follow material design's principles, you should show capitalized text in Buttons, http://www.google.com/design/spec/components/buttons.html
This "answer" is more of an addendum to VonC's answer; just noting that the syntax can be simplified via a typedef, and aggregate initialization can be used:
typedef int FUNC(int, int);
FUNC sum, subtract, mul, div;
FUNC *p[4] = { sum, subtract, mul, div };
int main(void)
{
int result;
int i = 2, j = 3, op = 2; // 2: mul
result = p[op](i, j); // = 6
}
// maybe even in another file
int sum(int a, int b) { return a+b; }
int subtract(int a, int b) { return a-b; }
int mul(int a, int b) { return a*b; }
int div(int a, int b) { return a/b; }
If you need an ordered dictionary, you can use odict.
The Scanner class is bases on logic implemented in String next(Pattern)
method. The additional API method like nextDouble()
or nextFloat()
. Provide the pattern inside.
Then class description says:
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
From the description it can be sad that someone has forgot about char as it is a primitive type for sure.
But the concept of class is to find patterns, a char has no pattern is just next character. And this logic IMHO caused that nextChar has not been implemented.
If you need to read a filed char by char you can used more efficient class.
// open in default browser
Process.Start("http://www.stackoverflow.net");
// open in Internet Explorer
Process.Start("iexplore", @"http://www.stackoverflow.net/");
// open in Firefox
Process.Start("firefox", @"http://www.stackoverflow.net/");
// open in Google Chrome
Process.Start("chrome", @"http://www.stackoverflow.net/");
You can use something like this:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class testHashes {
public static void main(String args[]){
Map<String,String> myMap1 = new HashMap<String, String>();
List<Map<String , String>> myMap = new ArrayList<Map<String,String>>();
myMap1.put("URL", "Val0");
myMap1.put("CRC", "Vla1");
myMap1.put("SIZE", "Val2");
myMap1.put("PROGRESS", "Val3");
myMap.add(0,myMap1);
myMap.add(1,myMap1);
for (Map<String, String> map : myMap) {
System.out.println(map.get("URL"));
System.out.println(map.get("CRC"));
System.out.println(map.get("SIZE"));
System.out.println(map.get("PROGRESS"));
}
//System.out.println(myMap);
}
}
https://groups.google.com/forum/#!topic/google-appengine-stackoverflow/QZGJg2tlfA4
From what I've found online, this is a bug introduced in JDK 1.7.0_45. I've read it will be fixed in the next release of Java, but it's not out yet. Supposedly, it was fixed in 1.7.0_60b01, but I can't find where to download it and 1.7.0_60b02 re-introduces the bug.
I managed to get around the problem by reverting back to JDK 1.7.0_25. Probably not the solution you wanted, but it's the only way I've been able to get it working. Don't forget add JDK 1.7.0_25 in Eclipse after installing the JDK.
Please DO NOT REPLY directly to this email but go to StackOverflow: Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined
If you are like me, and starring at your angular/ionic typescript, which looks like..
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, {
headers: new HttpHeaders(
{
'Access-Control-Allow-Origin': 'https://localhost:5100',
'Access-Control-Allow-Methods': 'POST',
'Content-Type': 'application/pdf',
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
And while you are setting options but can't seem to figure why they aren't anywhere..
Well.. if you were like me and started this post
from a copy/paste of a get
, then...
Change to:
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, null, { // <----- notice the null *****
headers: new HttpHeaders(
{
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
You can start web pages using command line in any browser typing this command
cd %your chrome directory%
start /max http://google.com
save it as bat and run it :)
You are POSTing the json incorrectly -- but even if it were correct, you would not be able to test using print_r($_POST)
(read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input")
, which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
In your code, you are indicating Content-Type:application/json
, but you are not json-encoding all of the POST data -- only the value of the "customer" POST field. Instead, do something like this:
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";
Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.
Yes, it is possible to take a snapshot of a web page using Selenium WebDriver.
The getScreenshotAs()
method provided by the WebDriver API does the work for us.
Syntax: getScreenshotAs(OutputType<X> target)
Return type: X
Parameters: target
– Check the options provided by OutputType
Applicability: Not specific to any DOM element
Example:
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
Refer to the below working code snippet for more details.
public class TakeScreenShotDemo {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http: //www.google.com”);
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
// Creating a destination file
File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
try {
FileUtils.copyFile(file, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Visit Snapshot using WebDriver for getting more details.
You may need to consider some further aspects for code robustness;
when you're storing an integer-valued variable as an environment variable, try
os.environ['DEBUSSY'] = str(myintvariable)
then for retrieval, consider that to avoid errors, you should try
os.environ.get('DEBUSSY', 'Not Set')
possibly substitute '-1' for 'Not Set'
so, to put that all together
myintvariable = 1
os.environ['DEBUSSY'] = str(myintvariable)
strauss = int(os.environ.get('STRAUSS', '-1'))
# NB KeyError <=> strauss = os.environ['STRAUSS']
debussy = int(os.environ.get('DEBUSSY', '-1'))
print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)
I have Written a small script to download the live youtube video, you may use as single command as well. script it can be invoked simply as,
~/ytdl_lv.sh <URL> <output file name>
e.g.
~/ytdl_lv.sh https://www.youtube.com/watch?v=BLIGxsYLyjc myfile.mp4
script is as simple as below,
#!/bin/bash
# ytdl_lv.sh
# Author Prashant
#
URL=$1
OUTNAME=$2
streamlink --hls-live-restart -o ${OUTNAME} ${URL} best
here the best is the stream quality, it also can be 144p (worst), 240p, 360p, 480p, 720p (best)
switch is definitely preferred. It's easier to look at a switch's list of cases & know for sure what it is doing than to read the long if condition.
The duplication in the if
condition is hard on the eyes. Suppose one of the ==
was written !=
; would you notice? Or if one instance of 'numError' was written 'nmuError', which just happened to compile?
I'd generally prefer to use polymorphism instead of the switch, but without more details of the context, it's hard to say.
As for performance, your best bet is to use a profiler to measure the performance of your application in conditions that are similar to what you expect in the wild. Otherwise, you're probably optimizing in the wrong place and in the wrong way.
I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.
1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)
2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.
3) add your user account to the group that has permission on the folder (mine was www-data).
A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).
You should better use the errbar
function from the Hmisc
package:
d = data.frame(
x = c(1:5)
, y = c(1.1, 1.5, 2.9, 3.8, 5.2)
, sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
)
##install.packages("Hmisc", dependencies=T)
library("Hmisc")
# add error bars (without adjusting yrange)
plot(d$x, d$y, type="n")
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
)
# new plot (adjusts Yrange automatically)
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
)
FileReader reads from files on the file system.
Perhaps you intended to use something like this to load a file from the class path
// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
.getResourceAsStream("config.txt");
Or you could extract the file from the jar before reading it.
For one-liners, userandom.sample(list_to_be_shuffled, length_of_the_list)
with an example:
import random
random.sample(list(range(10)), 10)
outputs: [2, 9, 7, 8, 3, 0, 4, 1, 6, 5]
Since C++11 you can use std::chrono
:
std::chrono::system_clock::now()
.time_since_epoch()
duration_cast<milliseconds>(d)
std::chrono::milliseconds
to integer (uint64_t
to avoid overflow)#include <chrono>
#include <cstdint>
#include <iostream>
uint64_t timeSinceEpochMillisec() {
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main() {
std::cout << timeSinceEpochMillisec() << std::endl;
return 0;
}
You have to use attachEvent
in IE versions prior to IE9. Detect whether addEventListener
is defined and use attachEvent
if it isn't:
if(_checkbox.addEventListener)
_checkbox.addEventListener("click",setCheckedValues,false);
else
_checkbox.attachEvent("onclick",setCheckedValues);
// ^^ -- onclick, not click
Note that IE11 will remove attachEvent
.
See also:
You can override any built-in function by just re-declaring it.
parseFloat = function(a){
alert(a)
};
Now parseFloat(3)
will alert 3.
Yes, this can be done with the UIWebView.
If you are trying to display a PDF file residing on a server somewhere, you can simply load it in your web view directly:
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSURL(string: "https://www.example.com/document.pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
Or if you have a PDF file bundled with your application (in this example named "document.pdf"):
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"document" withExtension:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSBundle.mainBundle().URLForResource("document", withExtension: "pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
You can find more information here: Technical QA1630: Using UIWebView to display select document types.
For that particular case there is file.path
:
File <- file.path("~",
"a",
"very",
"long",
"path",
"here",
"that",
"goes",
"beyond",
"80",
"characters",
"and",
"then",
"some",
"more")
setwd(File)
An example:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
Alex Robinson and bmju provided valuable information to understand cross-origin issues. I wanted to add that you may need to make an explicit OPTIONS call in your client code before making the desired GET/POST (e.g. against a CORS OAuth service endpoint). Your browser/library may not automatically handle the OPTIONS request. Gruber, this is one of the possible answers to your question.
@HTML.ActionLink
generates a HTML anchor tag
. While @Url.Action
generates a URL
for you. You can easily understand it by;
// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")
// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")
// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>
Both of these approaches are different and it totally depends upon your need.
An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:
- Annotation of existing resources;
- Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
- Providing a block of data, such as the result of submitting a form, to a data-handling process;
- Extending a database through an append operation.
Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]);
Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
it's also possible to create a unique constraint of more than 1 column:
ALTER TABLE the_table
ADD CONSTRAINT constraint_name UNIQUE (column1, column2);
DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
if (dr["Column_Name"] == DBNull.Value)
{
//Do something
}
else
{
//Do something
}
}
The fact that the first digit has to be in the range 5-9
only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:
^([5-9]\d|\d{3,})$
This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The |
means "or", so either [5-9]\d
or any number with 3 or more digits. \d
is simply a shortcut for [0-9]
.
Edit: To disallow numbers like 001
:
^([5-9]\d|[1-9]\d{2,})$
This forces the first digit to be not a zero in the case of 3 or more digits.
I think this is due to the connection established with the client machine is not secure.
It is due to the fact that you are talking to an HTTP server, not an HTTPS server. Probably you didn't use the correct port number for HTTPS.
You need to set oracle to listen on all ip addresses (by default, it listens only to localhost connections.)
listener.ora
This file is located in:
%ORACLE_HOME%\network\admin\listener.ora
.Replace localhost
with 0.0.0.0
# ...
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
)
)
# ...
Windows: WinKey + r
services.msc
Linux (CentOs):
sudo systemctl restart oracle-xe
There is a three-way to show toast on flutter App.
I will tell you about all three way that I know and choose which one you want to use. I would recommend the second one.
1: using of the external package.
this is the first method which is the easiest way to show toast on flutter app.
first of all, you have to add this package to pubspec.YAML
flutter_just_toast:^version_here
then import the package in the file where you want to show a toast.
'package:flutter_just_toast/flutter_just_toast.dart';
and the last step shows the toast.
Toast.show( message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
2 : using official way.
this method is also simple but you have to deal with it. I am not saying that it is hard it is simple and clean I would recommend this method.
for this method, all you have to do show toast is using the below code.
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Sending Message"),
));
but remember that you have to use the scaffold context.
3: using native API.
now, this method does not make sense anymore when you already have the two methods above. using this method you have to write native code for android and iOS and then convert it to plugin and you are ready to go. this method will consume your time and you have to reinvent the wheel. which has already been invented.
You have to check on this.
HTML
<button id="saveActionId"> Save </button>
manifest.json
"permissions": [
"activeTab",
"tabs"
]
JavaScript
The below code will save all the urls of active window into JSON object as part of button click.
var saveActionButton = document.getElementById('saveActionId');
saveActionButton.addEventListener('click', function() {
myArray = [];
chrome.tabs.query({"currentWindow": true}, //{"windowId": targetWindow.id, "index": tabPosition});
function (array_of_Tabs) { //Tab tab
arrayLength = array_of_Tabs.length;
//alert(arrayLength);
for (var i = 0; i < arrayLength; i++) {
myArray.push(array_of_Tabs[i].url);
}
obj = JSON.parse(JSON.stringify(myArray));
});
}, false);
You basically have four potential solutions to fix a "javax.net.ssl.SSLHandshakeException: " exception on Android
Also, I want to elaborate more to point number 1. We can selectively skip some domain using manifest network config as explain:
Create a file "network_security_config.xml" in xml folder in res folder with following content.
<network-security-config xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<domain-config>
<domain includeSubdomains="true">191.1.1.0</domain>
<domain includeSubdomains="true">your_domain</domain>
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
</trust-anchors>
</domain-config>
</network-security-config>
Add "network_security_config.xml" to application tag in manifest as:
android:networkSecurityConfig="@xml/network_security_config"
Thats it..done!!. You successfully skipped the SSL certificate.
You want to use a FrameLayout or a Merge layout to achieve this. Android dev guide has a great example of this here: Android Layout Tricks #3: Optimize by merging.
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
Found another interesting solution
SELECT salary
FROM emp
WHERE salary = (SELECT DISTINCT(salary)
FROM emp as e1
WHERE (n) = (SELECT COUNT(DISTINCT(salary))
FROM emp as e2
WHERE e1.salary <= e2.salary))
Sorry. Forgot to write. n is the nth number of salary which you want.
Here is my version of this which I hope can save some of your time :)
jQuery PART:
$(".dropdown-menu").on('click', 'li a', function(){
var selText = $(this).children("h4").html();
$(this).parent('li').siblings().removeClass('active');
$('#vl').val($(this).attr('data-value'));
$(this).parents('.btn-group').find('.selection').html(selText);
$(this).parents('li').addClass("active");
});
HTML PART:
<div class="container">
<div class="btn-group">
<a class="btn btn-default dropdown-toggle btn-blog " data-toggle="dropdown" href="#" id="dropdownMenu1" style="width:200px;"><span class="selection pull-left">Select an option </span>
<span class="pull-right glyphiconglyphicon-chevron-down caret" style="float:right;margin-top:10px;"></span></a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li><a href="#" class="" data-value=1><p> HER Can you write extra text or <b>HTLM</b></p> <h4> <span class="glyphicon glyphicon-plane"></span> <span> Your Option 1</span> </h4></a> </li>
<li><a href="#" class="" data-value=2><p> HER Can you write extra text or <i>HTLM</i> or some long long long long long long long long long long text </p><h4> <span class="glyphicon glyphicon-briefcase"></span> <span>Your Option 2</span> </h4></a>
</li>
<li class="divider"></li>
<li><a href="#" class="" data-value=3><p> HER Can you write extra text or <b>HTLM</b> or some </p><h4> <span class="glyphicon glyphicon-heart text-danger"></span> <span>Your Option 3</span> </h4></a>
</li>
</ul>
</div>
<input type="text" id="vl" />
</div>
The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath()
(and thus NOT getServletPath()
as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}
.
<p>The context path is: ${pageContext.request.contextPath}.</p>
If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base>
tag:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
<!doctype html>
<html lang="en">
<head>
<title>SO question 2204870</title>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
<script src="js/global.js"></script>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<ul>
<li><a href="home.jsp">Home</a></li>
<li><a href="faq.jsp">FAQ</a></li>
<li><a href="contact.jsp">Contact</a></li>
</ul>
</body>
</html>
All links in the page will then automagically be relative to the <base>
so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /
, then they will not be relative to the <base>
anymore, but to the domain root instead.
Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:
string s = //{ "user" : { "id" : 12345, "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);
You'll get back something, where you can do:
var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.
Look at result
in the debugger to see, what's in there.
Use some regex like [0-9]
or \d
:
$words = preg_replace('/\d+/', '', $words );
You might want to read the preg_replace() documentation as this is directly shown there.
Here is an async helper function written in typescript that seems to do the trick for me. I guess this will not work for long-lived processes but still might be handy for someone?
import * as child_process from "child_process";
private async spawn(command: string, args: string[]): Promise<{code: number | null, result: string}> {
return new Promise((resolve, reject) => {
const spawn = child_process.spawn(command, args)
let result: string
spawn.stdout.on('data', (data: any) => {
if (result) {
reject(Error('Helper function does not work for long lived proccess'))
}
result = data.toString()
})
spawn.stderr.on('data', (error: any) => {
reject(Error(error.toString()))
})
spawn.on('exit', code => {
resolve({code, result})
})
})
}
Never put ListView
in ScrollView
. ListView
itself is scrollable.
For Bootstrap 3.
<div class="paragraphs">
<div class="row">
<div class="col-md-4">
<div class="content-heading clearfix media">
<h3>Experience   </h3>
<img class="pull-left" src="../site/img/success32.png"/>
</div>
<p>Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
</div>
</div>
</div>
pch=20 returns a symbol sized between "." and 19.
It's a filled symbol (which is probably what you want).
Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,
dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)
with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
ann=F, bg="steelblue2", fg=NULL))
I'm not aware of anything built-in. It's pretty simple to implement:
class assertMethodIsCalled(object):
def __init__(self, obj, method):
self.obj = obj
self.method = method
def called(self, *args, **kwargs):
self.method_called = True
self.orig_method(*args, **kwargs)
def __enter__(self):
self.orig_method = getattr(self.obj, self.method)
setattr(self.obj, self.method, self.called)
self.method_called = False
def __exit__(self, exc_type, exc_value, traceback):
assert getattr(self.obj, self.method) == self.called,
"method %s was modified during assertMethodIsCalled" % self.method
setattr(self.obj, self.method, self.orig_method)
# If an exception was thrown within the block, we've already failed.
if traceback is None:
assert self.method_called,
"method %s of %s was not called" % (self.method, self.obj)
class test(object):
def a(self):
print "test"
def b(self):
self.a()
obj = test()
with assertMethodIsCalled(obj, "a"):
obj.b()
This requires that the object itself won't modify self.b, which is almost always true.
Using vw
, em
& co. works for sure, but IMO it always needs a human's touch for fine-tuning.
Here's a script I just wrote based on @tnt-rox' answer that tries to automatize that human's touch:
$('#controller').click(function(){_x000D_
$('h2').each(function(){_x000D_
var_x000D_
$el = $(this),_x000D_
max = $el.get(0),_x000D_
el = null_x000D_
;_x000D_
max =_x000D_
max_x000D_
? max.offsetWidth_x000D_
: 320_x000D_
;_x000D_
$el.css({_x000D_
'font-size': '1em',_x000D_
'display': 'inline',_x000D_
});_x000D_
el = $el.get(0);_x000D_
_x000D_
el.get_float = function(){_x000D_
var_x000D_
fs = 0_x000D_
;_x000D_
if (this.style && this.style.fontSize) {_x000D_
fs = parseFloat(this.style.fontSize.replace(/([\d\.]+)em/g, '$1'));_x000D_
}_x000D_
return fs;_x000D_
};_x000D_
_x000D_
el.bigger = function(){_x000D_
this.style.fontSize = (this.get_float() + 0.1) + 'em';_x000D_
};_x000D_
_x000D_
while (el.offsetWidth < max) {_x000D_
el.bigger();_x000D_
}_x000D_
_x000D_
// Finishing touch._x000D_
$el.css({_x000D_
'font-size': ((el.get_float() -0.1) +'em'),_x000D_
'line-height': 'normal',_x000D_
'display': '',_x000D_
});_x000D_
}); // end of (each)_x000D_
}); // end of (font scaling test)
_x000D_
div {_x000D_
width: 50%;_x000D_
background-color: tomato;_x000D_
font-family: 'Arial';_x000D_
}_x000D_
_x000D_
h2 {_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
h2:nth-child(2) {_x000D_
font-style: italic;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="button" id="controller" value="Apply" />_x000D_
<div>_x000D_
<h2>Lorem ipsum dolor</h2>_x000D_
<h2>Test String</h2>_x000D_
<h2>Sweet Concatenation</h2>_x000D_
<h2>Font Scaling</h2>_x000D_
</div>
_x000D_
It basically reduces the font-size to 1em
and then starts incrementing by 0.1 until it reaches maximum width.
For postgresql:
SELECT * AS rec
FROM (
SELECT lastname, COUNT(*) AS counter
FROM students
GROUP BY lastname) AS tbl
WHERE counter > 1;
Straight from the React docs:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
(This is posting JSON, but you could also do, for example, multipart-form.)
This error appear because the compiler could not found "my-upload-key.keystore" file in your project
After you have generated the file you need to paste it into project's andorid/app folder
this worked for me!
Just create a .bat file with the line
hostname
in it. That's it. Windows also supports the hostname command.
Remove all widths set using CSS and set white-space to nowrap like so:
.content-loader tr td {
white-space: nowrap;
}
I would also remove the fixed width from the container (or add overflow-x: scroll
to the container) if you want the fields to display in their entirety without it looking odd...
See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp
I just went through this myself and chose to set the default value at the reducer INIT function.
If you bind your select with redux then best not 'de-bind' it with a select default value that doesn't represent the actual value, instead set the value when you initialize the object.
The problem is that your REGX pattern will only match the input "0-9".
To meet your requirement (0-9999999), you should rewrite your regx pattern:
ng-pattern="/^[0-9]{1,7}$/"
My example:
HTML:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="price" name="price_field"
ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<span ng-show="myForm.price_field.$error.required">This field is required!</span>
<input type="submit" value="submit"/>
</form>
</div>
JS:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
Here is a jsFiddle demo.
This is what I finally could do for installing psych package in R-3.4.1 when I got the same warning
1:Googled for that package.
2:downloaded it manually having tar.gz extension
3:Chose the option "Package Archive File (.zip;.tar.gz)" for install packages in R
4:browsed locally to the place where it was downloaded and clicked install
You may get a warning: dependencies 'xyz' not available for the package ,then first install those from the repository and then do steps 3-4 .
Check this
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 group by parent_id;
If you mean an in-place sort (i.e. the list is updated):
people.Sort((x, y) => string.Compare(x.LastName, y.LastName));
If you mean a new list:
var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional
This is a extension method for the texbox. Simply Add the Placeholder Text programmatically:
myTextBox.AddPlaceholderText("Hello World!");
The extension method:
public static void AddPlaceholderText(this TextBox textBox, string placeholderText)
{
if (string.IsNullOrWhiteSpace(textBox.Text))
textBox.Text = placeholderText;
textBox.SetResourceReference(Control.ForegroundProperty,
textBox.Text != placeholderText
? "SystemControlForegroundBaseHighBrush"
: "SystemControlForegroundBaseMediumBrush");
var ignoreSelectionChanged = false;
textBox.SelectionChanged += (sender, args) =>
{
if (ignoreSelectionChanged) { ignoreSelectionChanged = false; return; }
if (textBox.Text != placeholderText) return;
ignoreSelectionChanged = true;
textBox.Select(0, 0);
};
var lastText = textBox.Text;
var ignoreTextChanged = false;
textBox.TextChanged += (sender, args) =>
{
if (ignoreTextChanged) { ignoreTextChanged = false; return; }
if (string.IsNullOrWhiteSpace(textBox.Text))
{
ignoreTextChanged = true;
textBox.Text = placeholderText;
textBox.Select(0, 0);
}
else if (lastText == placeholderText)
{
ignoreTextChanged = true;
textBox.Text = textBox.Text.Substring(0, 1);
textBox.Select(1, 0);
}
textBox.SetResourceReference(Control.ForegroundProperty,
textBox.Text != placeholderText
? "SystemControlForegroundBaseHighBrush"
: "SystemControlForegroundBaseMediumBrush");
lastText = textBox.Text;
};
}
Happy coding, BierDav
For Windows 7 macros are stored at C:\Users\
Username
\AppData\Roaming\Notepad++\shortcuts.xml
.
Use next
:
(1..10).each do |a|
next if a.even?
puts a
end
prints:
1
3
5
7
9
For additional coolness check out also redo
and retry
.
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
It's a great idea to use cURL as suggested by rojoca.
Here is an example. You can monitor text.txt while the script is running in background:
<?php
function doCurl($begin)
{
echo "Do curl<br />\n";
$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = preg_replace('/\?.*/', '', $url);
$url .= '?begin='.$begin;
echo 'URL: '.$url.'<br>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo 'Result: '.$result.'<br>';
curl_close($ch);
}
if (empty($_GET['begin'])) {
doCurl(1);
}
else {
while (ob_get_level())
ob_end_clean();
header('Connection: close');
ignore_user_abort();
ob_start();
echo 'Connection Closed';
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
$begin = $_GET['begin'];
$fp = fopen("text.txt", "w");
fprintf($fp, "begin: %d\n", $begin);
for ($i = 0; $i < 15; $i++) {
sleep(1);
fprintf($fp, "i: %d\n", $i);
}
fclose($fp);
if ($begin < 10)
doCurl($begin + 1);
}
?>
Just call: ruby your_program.rb
or
#!/usr/bin/env ruby
,chmod +x your_program.rb
./your_program.rb some_param
My problem was in integration of Ant + ProGuard + AdMob SDK library + Debug mode. I was building debug APK using Ant and Added AdMob SDK JAR to libs/
directory. Eclipse generated the debug APK normally, but Ant could not. I was getting the following error.
[apply] UNEXPECTED TOP-LEVEL EXCEPTION: [apply] java.lang.IllegalArgumentException: already added: Lcom/google/ads/AdActivity; [apply] at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
I also had ProGuard turned on for debug build in my build.xml
(default is off):
<target name="-debug-obfuscation-check">
<property name="proguard.enabled" value="true"/>
</target>
That was the problem. Somehow ProGuard and AdMob SDK do not live together in debug mode. ProGuard did not obfuscate AdActivity
class so it appeared in bin/proguard/obfuscated.jar
unobfuscated, but the same class exists in the AdMob SDK JAR file. Eclipse was building debug APK without ProGuard, so it worked fine.
So my solution was just to turn off ProGuard for debug builds in build.xml
.
I hope it helps somebody.
On OSX, I'm using -f to specify the input format, -j to not attempt to set any date, and an output format specifier. For example:
$ date -j -f "%m/%d/%y %H:%M:%S %p" "8/22/15 8:15:00 am" +"%m%d%y"
082215
Your example:
$ date -j -f "%d %b %Y" "27 JUN 2011" +%Y%m%d
20110627
If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.
In your case, you might do better to have a generic draw()
method, and rely on the subclasses (Rectangle
, Ellipse
) to implement the draw()
method as what you had been thinking of as "drawEllipse" and "drawRectangle".
e.relatedTarget.data('load-url');
won't work
use dataset.loadUrl
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = e.relatedTarget.dataset.loadUrl;
$(this).find('.modal-body').load(loadurl);
});
Wrong:
case AnotherClass.MyEnum.VALUE_A
Right:
case VALUE_A:
Some web hosting providers allow you to change PHP parameters in the .htaccess
file.
You can add the following line:
php_value display_errors 1
I had the same issue as yours and this solution fixed it.
Most probably in your manage.py
the first line starts with !/usr/bin/python
which means you are using the system global python rather than the one in your virtual environment.
so replace
/usr/bin/python
with
~/projectpath/venv/bin/python
and you should be good.
First of all my Search query value is from a user's input. I have tried all the answers on this one and all the results Google have given me, 90% of the answers says put '%''%' and the other 10% says a more complicated answers.
For some reason all of those did not work for me.
How ever I remembered that in MySQL (phpmyadmin) there is this built in search function so I tried it just to see how MySQL handles a search with an apostrophe, turns out MySQL just escaping apostrophe with a backslash LIKE '%\'%'
so why just I replace apostrophe with a \'
in every user's query.
This is what I come up with:
if(!empty($user_search)) {
$r_user_search = str_ireplace("'","\'","$user_search");
$find_it = "SELECT * FROM table WHERE column LIKE '%$r_user_search%'";
$results = $pdo->prepare($find_it);
$results->execute();
This solves my problem. Also please correct me if this is still has security issues.
While I'd suggest using expect, too, for non-interactive use the normal shell commands might suffice. Telnet accepts its command on stdin, so you just need to pipe or write the commands into it:
telnet 10.1.1.1 <<EOF
remotecommand 1
remotecommand 2
EOF
(Edit: Judging from the comments, the remote command needs some time to process the inputs or the early SIGHUP is not taken gracefully by the telnet. In these cases, you might try a short sleep on the input:)
{ echo "remotecommand 1"; echo "remotecommand 2"; sleep 1; } | telnet 10.1.1.1
In any case, if it's getting interactive or anything, use expect
.
I believe that the blog post JavaScript Beginners – Select a dropdown option by value might help you.
<a href="javascript:void(0);" onclick="selectItemByValue(document.getElementById('personlist'),11)">change</a>
function selectItemByValue(elmnt, value){
for(var i=0; i < elmnt.options.length; i++)
{
if(elmnt.options[i].value === value) {
elmnt.selectedIndex = i;
break;
}
}
}
For JetBrains Rider:
First Option
Second option:
That's it!
I'm surprised that nobody gave CSS table layout as a solution:
.Row {_x000D_
display: table;_x000D_
width: 100%; /*Optional*/_x000D_
table-layout: fixed; /*Optional*/_x000D_
border-spacing: 10px; /*Optional*/_x000D_
}_x000D_
.Column {_x000D_
display: table-cell;_x000D_
background-color: red; /*Optional*/_x000D_
}
_x000D_
<div class="Row">_x000D_
<div class="Column">C1</div>_x000D_
<div class="Column">C2</div>_x000D_
<div class="Column">C3</div>_x000D_
</div>
_x000D_
Works in IE8+
Check out a JSFiddle Demo
This worked for me
pip install django-csvimport --upgrade
$(".class").click(function(){
alert($(this).attr('id'));
});
only on jquery button click we can do this class should be written there
suppose you don't have column for auto increment like id, no, then you can add using following query:
ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
If you've column, then alter to auto increment using following query:
ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
Try the following:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
If you try this:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.
With cache()
, you use only the default storage level :
MEMORY_ONLY
for RDDMEMORY_AND_DISK
for DatasetWith persist()
, you can specify which storage level you want for both RDD and Dataset.
From the official docs:
- You can mark an
RDD
to be persisted using thepersist
() orcache
() methods on it.- each persisted
RDD
can be stored using a differentstorage level
- The
cache
() method is a shorthand for using the default storage level, which isStorageLevel.MEMORY_ONLY
(store deserialized objects in memory).
Use persist()
if you want to assign a storage level other than :
MEMORY_ONLY
to the RDDMEMORY_AND_DISK
for DatasetInteresting link for the official documentation : which storage level to choose
Previous answer didn't work for me.
But this worked perfectly. Convert Data URI to File then append to FormData
Your code is way more cluttered than necessary.
Replace (Not (X Is Nothing))
with X IsNot Nothing
and omit the outer parentheses:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For i As Integer = 0 To comp.Container.Components.Count() - 1
fixUIIn(comp.Container.Components(i), style)
Next
End If
Much more readable. … Also notice that I’ve removed the redundant Step 1
and the probably redundant .Item
.
But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each
instead:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For Each component In comp.Container.Components
fixUIIn(component, style)
Next
End If
Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.
function start() {_x000D_
document.getElementById("textBox1").scrollTop +=5;_x000D_
scrolldelay = setTimeout(function() {start();}, 40);_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
clearTimeout(scrolldelay);_x000D_
}_x000D_
_x000D_
function reset(){_x000D_
var loc = document.getElementById("textBox1").scrollTop;_x000D_
document.getElementById("textBox1").scrollTop -= loc;_x000D_
clearTimeout(scrolldelay);_x000D_
}_x000D_
//adjust height of paragraph in css_x000D_
//element textbox in div_x000D_
//adjust speed at scrolltop and start
_x000D_
BrowserWindow
only has an effect on Windows and Linux platforms. you have to package the .icns for max
To set the icon on OS X using electron-packager
, set the icon using the --icon switch.
It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.
--icon
switch. Here is what you can do.
build
in your project directory and put the .icns
the icon in the directory as named icon.icns
.electron-builder --dir
.You will find your application icon will be automatically picked up from that directory location and used for an application while packaging.
Note: The given answer is for recent version of
electron-builder
and tested with electron-builder v21.2.0
This is how I did it. Nice and simple.
String emailUrl = "mailto:[email protected]?subject=Subject Text&body=Body Text";
Intent request = new Intent(Intent.ACTION_VIEW);
request.setData(Uri.parse(emailUrl));
startActivity(request);
You can use the following to programmatically center TextView
text in Kotlin:
textview.gravity = Gravity.CENTER
The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.
If the URL of your website is: http://www.example.com/mywebsite/
then starting at the root level starts above the "mywebsite" folder path.
<?php echo date('U') ?>
If you want, put it in a MySQL input type timestamp. The above works very well (only in PHP 5 or later):
<?php $timestamp_for_mysql = date('c') ?>
It 'a permission problem when IIS is running I had this problem and I solved it in this way
I went on folders
C:\Windows\ System32\config\SystemProfile
and
C:\Windows\SysWOW64\config\SystemProfile
are protected system folders, they usually have the lock.
Right-click-> Card security-> Click on Edit-> Add untente "Autenticadet User" and assign permissions.
At this point everything is solved, if you still have problems try to give all permissions to "Everyone"
I think there are more solutions!
You can start the app, and here are 3 things you can do:
Settings
> Manage License...
> Remove License
, and that removes for all Jetbrains products*.File
> Close Project
, and follow the first step.Help
> Register...
> Remove license
.*In case you have a license for a pack of products. If not, you have to remove the license per product individually. Check the 3rd step.
Give your ul
an id
,
<ul id='yourUlId' class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">
then do
var yourUl = document.getElementById("yourUlId");
yourUl.style.display = yourUl.style.display === 'none' ? '' : 'none';
IF you're using jQuery, this becomes:
var $yourUl = $("#yourUlId");
$yourUl.css("display", $yourUl.css("display") === 'none' ? '' : 'none');
Finally, you specifically said that you wanted to manipulate this css property, and not simply show or hide the underlying element. Nonetheless I'll mention that with jQuery
$("#yourUlId").toggle();
will alternate between showing or hiding this element.
You can use:
<script type="text/javascript">
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
also check basics of the iFrame element
You can simply do it with train_test_split()
method available in Scikit learn:
from sklearn.model_selection import train_test_split
train, test = train_test_split(X, test_size=0.25, stratify=X['YOUR_COLUMN_LABEL'])
I have also prepared a short GitHub Gist which shows how stratify
option works:
https://gist.github.com/SHi-ON/63839f3a3647051a180cb03af0f7d0d9
Try this:
git fetch --all
git reset --hard origin/master
Explanation:
git fetch
downloads the latest from remote without trying to merge or rebase anything.
Please let me know if you have any questions!
If you're using a shell, the filepath to the Download (no "s") folder is
/storage/emulated/0/Download
Use the following command:
in.nextLine();
right after
System.out.println("Invalid input. Please Try Again.");
System.out.println();
or after the following curly bracket (where your comment regarding it, is).
This command advances the scanner to the next line (when reading from a file or string, this simply reads the next line), thus essentially flushing it, in this case. It clears the buffer and readies the scanner for a new input. It can, preferably, be used for clearing the current buffer when a user has entered an invalid input (such as a letter when asked for a number).
Documentation of the method can be found here: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
Hope this helps!
Try this:
$('[id$=lblVessel]').text("NewText");
The id$=
will match the elements that end with that text, which is how ASP.NET auto-generates IDs. You can make it safer using span[id=$=lblVessel]
but usually this isn't necessary.
If you are familiar with gcc, as you indicated in the question, you can install MinGW, which will set a linux-like compile environment in Win7. Otherwise, Visual Studio 2010 Express is the best choice.
The -B
switch to make, whose long form is --always-make
, tells make
to disregard timestamps and make the specified targets. This may defeat the purpose of using make, but it may be what you need.
I would additionally suggest a 4th option as a better alternative to the proposed options by @zbynour.
Use $rootScope.$emit
rather than $rootScope.$broadcast
regardless of the relationship between trasmitting and receiving controller. That way, the event remains within the set of $rootScope.$$listeners
whereas with $rootScope.$broadcast
the event propagates to all children scopes, most of which will probably not be listeners of that event anyway. And of course in the receiving controller's end you just use $rootScope.$on
.
For this option you must remember to destroy the controller's rootScope listeners:
var unbindEventHandler = $rootScope.$on('myEvent', myHandler);
$scope.$on('$destroy', function () {
unbindEventHandler();
});
An example here:
movies = Movie.query.filter(Movie.rating != 0).order_by(desc(Movie.rating)).all()
I query the db for movies with rating <> 0, and then I order them by rating with the higest rating first.
Take a look here: Select, Insert, Delete in Flask-SQLAlchemy
\n
is a line break. /n
is not.
use of \n
with
Now if you are trying to echo string to the page:
echo "kings \n garden";
output will be:
kings garden
you won't get garden
in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n
. You need to use the nl2br()
function for that.
What it does is:
Returns string with
<br />
or<br>
inserted before all newlines (\r\n, \n\r, \n and \r).
echo nl2br ("kings \n garden");
kings
garden
Note Make sure you're echoing/printing
\n
in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is
so "\n" not '\n'
Now if you echo to text file you can use just \n
and it will echo to a new line, like:
$myfile = fopen("test.txt", "w+") ;
$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
output will be:
kings
garden
To achieve a generic solution, why not do this:
$(':reset').live('click', function(){
var $r = $(this);
setTimeout(function(){
$r.closest('form').find('.select2-offscreen').trigger('change');
}, 10);
});
This way: You'll not have to make a new logic for each select2 on your application.
And, you don't have to know the default value (which, by the way, does not have to be ""
or even the first option)
Finally, setting the value to :selected
would not always achieve a true reset, since the current selected might well have been set programmatically on the client, whereas the default action of the form select
is to return input element values to the server-sent ones.
EDIT:
Alternatively, considering the deprecated status of live
, we could replace the first line with this:
$('form:has(:reset)').on('click', ':reset', function(){
or better still:
$('form:has(:reset)').on('reset', function(){
PS: I personally feel that resetting on reset, as well as triggering blur
and focus
events attached to the original select, are some of the most conspicuous "missing" features in select2!
Since Pabluez's answer back in December, there is now a better way to customize Bootstrap.
Use: Bootswatch to generate your bootstrap.css
Bootswatch builds the normal Twitter Bootstrap from the latest version (whatever you install in the bootstrap directory), but also imports your customizations. This makes it easy to use the the latest version of Bootstrap, while maintaining custom CSS, without having to change anything about your HTML. You can simply sway boostrap.css files.
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
BigInteger
must support values in the range-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.Implementation note:
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range of-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive).
Not knowing how the OP happened to have {" String", "Tom Selleck "," Fish "}
in an array in the first place (6 years ago), I thought I'd share what I ended up with.
My array is the result of using split on a string which might have extra spaces around delimiters. My solution was to address this at the point of the split. My code follows. After testing, I put splitWithTrim() in my Utils class of my project. It handles my use case; you might want to consider what sorts of strings and delimiters you might encounter if you decide to use it.
public class Test {
public static void main(String[] args) {
test(" abc def ghi jkl ", " ");
test(" abc; def ;ghi ; jkl; ", ";");
}
public static void test(String str, String splitOn) {
System.out.println("Splitting \"" + str + "\" on \"" + splitOn + "\"");
String[] parts = splitWithTrim(str, splitOn);
for (String part : parts) {
System.out.println("(" + part + ")");
}
}
public static String[] splitWithTrim(String str, String splitOn) {
if (splitOn.equals(" ")) {
return str.trim().split(" +");
} else {
return str.trim().split(" *" + splitOn + " *");
}
}
}
Output of running the test application is:
Splitting " abc def ghi jkl " on " "
(abc)
(def)
(ghi)
(jkl)
Splitting " abc; def ;ghi ; jkl; " on ";"
(abc)
(def)
(ghi)
(jkl)
int64_t
is typedef
you can find that in <stdint.h>
in C
Integrated application pool mode
When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.
There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.
Classic application pool mode
When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.
This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.
Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.
Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?
Original source: Introduction to IIS Architecture
Here you can not push the object to a state array like this. You can push like your way in normal array. Here you have to set the state,
this.setState({
myArray: [...this.state.myArray, 'new value']
})
Here are some ways to edit the text and the size of the box:
rows="insertNumber"
cols="insertNumber"
style="font-size:12pt"
Example:
<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter
Text Here</textarea>
It's pretty easy, just do it like this
$scope.props = [{order:"1"},{order:"5"},{order:"2"}]
ng-repeat="prop in props | orderBy:'order'"
Give the submit buttons for both forms different names and use PHP to check which button has submitted data.
Form one button - btn1 Form two button -btn2
PHP Code:
if($_POST['btn1']){
//Login
}elseif($_POST['btn2']){
//Register
}
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
This is just because node is asynchronous and it will not wait for the read function and as soon as the program starts it will console the value as undefined, Which is actually true because there is no value assigned to content variable. To handle we can use promises, generators etc. We can use promise in this way.
new Promise((resolve,reject)=>{
fs.readFile('./index.html','utf-8',(err, data)=>{
if (err) {
reject(err); // in the case of error, control flow goes to the catch block with the error occured.
}
else{
resolve(data); // in the case of success, control flow goes to the then block with the content of the file.
}
});
})
.then((data)=>{
console.log(data); // use your content of the file here (in this then).
})
.catch((err)=>{
throw err; // handle error here.
})
You can use the following CSS to make a div 100% of the height of the browser window:
display: block;
position: relative;
bottom: 0;
height: 100%;
For Ruby:
require 'rubygems'
require 'aws-sdk'
require 'net/http'
metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )
ec2 = AWS::EC2.new()
instance = ec2.instances[instance_id]
This question is old but I wanted to add an alternative to the accepted answer which didn't exist at the time.
Image Mapster is a jQuery plugin that I wrote to solve some of the shortcomings of Map Hilight (and it was initially an extension of that plugin, though it's since been almost completely rewritten). Initially, this was just the ability to maintain selection state for areas, fix browser compatibility problems. Since its initial release a few months ago, though, I have added a lot of features including the ability to use an alternate image as the source for the highlights.
It also has the ability to identify areas as "masks," meaning you can create areas with "holes", and additionally create complex groupings of areas. For example, area A could cause another area B to be highlighted, but area B itself would not respond to mouse events.
There are a few examples on the web site that show most of the features. The github repository also has more examples and complete documentation.
This error is causing due to disabled of rewrite mod in apache httpd.conf document ,just uncomment it and enjoy the seo friendly permalinks
always works well:
function getCookie(cname) {
var name = cname + "=",
ca = document.cookie.split(';'),
i,
c,
ca_length = ca.length;
for (i = 0; i < ca_length; i += 1) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) !== -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(variable, value, expires_seconds) {
var d = new Date();
d = new Date(d.getTime() + 1000 * expires_seconds);
document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
}
No requirements for jQuery or anything. Pure old good JavaScript.
To really be universal, I'm using this:
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'
|| $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
header('Location: '.$protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
I like $_SERVER['REQUEST_URI']
because it respects mod_rewrite and/or any GET variables.
https detection from https://stackoverflow.com/a/2886224/947370
It is true that, functionally, both queries should be processed the same way. However, experience has shown that if you are selecting from views that use the new join syntax, it is important to structure your queries using it as well. Oracle's optimizer can get confused if a view uses a "join" statement, but a query accessing the view uses the traditional method of joining in the "where" clause.
The PATH will be reset when using su or sudo by the definition of ENV_SUPATH, and ENV_PATH defined in /etc/login.defs
In My case, I am running a local Django backend in IP 127.0.0.1:8000
with Expo start.
Just make sure you have the server in public domain
not hosted lcoally on your machine
$('#parent2').prepend($('#table1_length')).prepend($('#table1_filter'));
doesn't work for you? I think it should...
[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]
Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance.
A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your gwt.xml
:
<define-property name="user.agent" values="ie6,gecko,gecko1_8"></define-property>
or in gwt 2.x syntax, and for one browser only:
<set-property name="user.agent" value="gecko1_8"/>
This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack.
Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time.
Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.
UPDATE 2020
Database Inspector (for Android Studio version 4.1). Read the Medium article
For older versions of Android Studio I recommend these 3 options:
In build.gradle:
dependencies {
// Stetho core
compile 'com.facebook.stetho:stetho:1.5.1'
//If you want to add a network helper
compile 'com.facebook.stetho:stetho-okhttp:1.5.1'
}
Initialize the library in the application object:
Stetho.initializeWithDefaults(this);
And you can view you database in Chrome from chrome://inspect
Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window
, document
and such specified in a file called lib.d.ts
. If I do a grep for require
in this file I can find no definition of a function require
. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare
syntax:
declare function require(name:string);
var sampleModule = require('modulename');
On my system, this compiles just fine.
Use
git cherry-pick <commit-hash>
So this will pick your behind commit to git location you are on.
Make sure that your package is installed in your $GOPATH
directory or already inside your workspace/package.
For example: if your $GOPATH = "c:\go"
, make sure that the package inside C:\Go\src\pkgName
I use This in page.`
public void DTToExcel(DataTable dt)
{
// dosya isimleri ileride ayni anda birden fazla kullanici ayni dosya üzerinde islem yapmak ister düsüncesiyle guid yapildi.
string FileName = Guid.NewGuid().ToString();
FileInfo f = new FileInfo(Server.MapPath("Downloads") + string.Format("\\{0}.xlsx", FileName));
if (f.Exists)
f.Delete(); // delete the file if it already exist.
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Charset = Encoding.UTF8.WebName;
response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
response.AddHeader("Content-Type", "application/Excel");
response.ContentType = "application/vnd.xlsx";
//response.AddHeader("Content-Length", file.Length.ToString());
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw)) //datatable'a aldigimiz sorguyu bir datagrid'e atayip html'e çevir.
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
dg.Dispose();
dt.Dispose();
response.End();
}
}
}
npm install -g npm@version
in which you want to downgrade
npm install -g [email protected]
use utf8;
does not enable Unicode output - it enables you to type Unicode in your program. Add this to the program, before your print()
statement:
binmode(STDOUT, ":utf8");
See if that helps. That should make STDOUT
output in UTF-8 instead of ordinary ASCII.
Select all text in the document and press Ctrl + E + D.
I found this arrow(start, end)
function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.
You can try like below
DECLARE @sqlCommand NVARCHAR(4000)
DECLARE @ID INT
DECLARE @Name NVARCHAR(100)
SET @ID = 4
SET @sqlCommand = 'SELECT @Name = [Name]
FROM [AdventureWorks2014].[HumanResources].[Department]
WHERE DepartmentID = @ID'
EXEC sp_executesql @sqlCommand, N'@ID INT, @Name NVARCHAR(100) OUTPUT',
@ID = @ID, @Name = @Name OUTPUT
SELECT @Name ReturnedName
Source : blog.sqlauthority.com
We have been having a discussion back here at the office and we think that trying to automatically correct the way people input names in the current way you want it doing is fraught with possible issues.
We have come up with several cases where different types of auto capitalization fall apart and these are just for English names alone, each language has its own complexities.
Issues with capitalizing the first letter of each name:
• Acronyms such as IBM aren’t allowed to be inputted, would turn into Ibm.
• The Name McDonald would turn into Mcdonald which is incorrect, the same thing is MacDonald too.
• Double barrelled names such as Marie-Tonks would get turned into Marie-tonks.
• Names like O’Connor would turn into O’connor.
For most of these you could write custom rules to deal with it, however, this still has issues with Acronyms as before and you get a new issue:
• Adding in a rule to fix names with Mac such as MacDonald, would the break names such as Macy turning it into MacY.
The only solution we have come up with that is never incorrect is to capitalize every letter which is a brute force method that the DBS appear to also use.
So if you want to automate the process it is as good as impossible to do without a dictionary of every single name and word and how it should be capitlized, If you don't have a rule that covers everything don't use it as it will just annoy your users and prompt people who want to enter their names correctly to go else where.
Finding Email-id:
import re
a=open("aa.txt","r")
#c=a.readlines()
b=a.read()
c=b.split("\n")
print(c)
for d in c:
obj=re.search(r'[\w.]+\@[\w.]+',d)
if obj:
print(obj.group())
#for more calcification click on image above..
*<tr><a href="javascript:void(0);" class="remove">X</a></tr>*
<script type='text/javascript'>
$("table").on('click', '.remove', function () {
$(this).parent().parent('tr').remove();
});
You can also use git-copy.
Install it with Gem,
gem install git-copy
Then
git copy https://github.com/exampleuser/old-repository.git \
https://github.com/exampleuser/new-repository.git
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
You can use textract module in python
Textract
for install
pip install textract
for read pdf
import textract
text = textract.process('path/to/pdf/file', method='pdfminer')
For detail Textract
The problem is, you are creating a transport
object and using it's connect method to authenticate yourself.
But then you use a static
method to send the message which ignores authentication done by the object.
So, you should either use the sendMessage(message, message.getAllRecipients())
method on the object or use an authenticator as suggested by others to get authorize
through the session.
Here's the Java Mail FAQ, you need to read.