You should try something like this, I am doing this for my project, its a fallback system
//function to get the remote data
function url_get_contents ($url) {
if (function_exists('curl_exec')){
$conn = curl_init($url);
curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($conn, CURLOPT_FRESH_CONNECT, true);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
$url_get_contents_data = (curl_exec($conn));
curl_close($conn);
}elseif(function_exists('file_get_contents')){
$url_get_contents_data = file_get_contents($url);
}elseif(function_exists('fopen') && function_exists('stream_get_contents')){
$handle = fopen ($url, "r");
$url_get_contents_data = stream_get_contents($handle);
}else{
$url_get_contents_data = false;
}
return $url_get_contents_data;
}
then later you can do like this
$data = url_get_contents("http://www.google.com");
if($data){
//Do Something....
}
You JSON is not a valid string as P. Galbraith has told you above.
and here is the solution for it.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Use this code it will work for you.
Enable allow_url_fopen From cPanel Or WHM in PHP INI Section
To allow https wrapper:
php_openssl
extension must exist and be enabled allow_url_fopen
must be set to on
In the php.ini file you should add this lines if not exists:
extension=php_openssl.dll
allow_url_fopen = On
Yes! By passing a stream context in the third parameter:
Here with a timeout of 1s:
file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));
Source in comment section of https://www.php.net/manual/en/function.file-get-contents.php
method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout
Other contexts: https://www.php.net/manual/en/context.php
Sending an HTTP POST request using file_get_contents
is not that hard, actually : as you guessed, you have to use the $context
parameter.
There's an example given in the PHP manual, at this page : HTTP context options (quoting) :
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents
-- nothing more ;-)
As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...
file_get_contents()
is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.
fopen()
with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.
I got a similar problem.
Due to timeout !
Timeout can be indicated like this :
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => "POST",
'content' => http_build_query($data2),
'timeout' => 30,
),
);
$context = stream_context_create($options); $retour =
$retour = @file_get_contents("http://xxxxx.xxx/xxxx", false, $context);
You can do that, or you can use the readfile
function, which outputs it for you:
header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();
Edit: Derp, fixed obvious glaring typo.
original answer moved to this topic .
Use file_get_contents
in combination with json_decode
and echo
.
I had a similar problem, what solved it was html_entity_decode
.
My code is:
$content = file_get_contents("http://example.com/fr");
$x = new SimpleXMLElement($content);
foreach($x->channel->item as $entry) {
$subEntry = html_entity_decode($entry->description);
}
In here I am retrieving an xml file (in French), that's why I'm using this $x object variable. And only then I decode it into this variable $subEntry
.
I tried mb_convert_encoding
but this didn't work for me.
I had the same issue for another secure page when using wget
or file_get_contents
. A lot of research (including some of the responses on this question) resulted in a simple solution - installing Curl and PHP-Curl - If I've understood correctly, Curl has the Root CA for Comodo which resolved the issue
Install Curl and PHP-Curl addon, then restart Apache
sudo apt-get install curl
sudo apt-get install php-curl
sudo /etc/init.d/apache2 reload
All now working.
Wrap your $adr
in urlencode()
.
I was having this problem and this solved it for me.
JSONP allows you to specify a callback function that is passed your JSON object. This allows you to bypass the same origin policy and load JSON from an external server into the JavaScript on your webpage.
I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.
Example code:
import { useRef } from 'react'
function Component() {
const inputRef = useRef()
return (
<input ref={inputRef} />
<div
onScroll={() => {
const { offsetTop } = inputRef.current
...
}}
>
)
}
The best solution is the attribute selector in CSS (input[type="text"]
) as the others suggested.
But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.
In this case your only option seems to be to define classes on input elements.
<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...
and target them with a class selector:
input.input-box, textarea { background: cyan; }
I preffer the following way, it can be used by any button.
<button class='pushme' data-default-text="PUSH ME" data-new-text="DON'T PUSH ME">PUSH ME</button>
$(".pushme").click(function () {
var $element = $(this);
$element.text(function(i, text) {
return text == $element.data('default-text') ? $element.data('new-text')
: $element.data('default-text');
});
});
From Linux Terminal:
adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"
From Windows PowerShell:
adb shell
getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'
Sample output for Samsung:
[gsm.version.baseband]: [G900VVRU2BOE1]
[gsm.version.ril-impl]: [Samsung RIL v3.0]
[net.knoxscep.version]: [2.0.1]
[net.knoxsso.version]: [2.1.1]
[net.knoxvpn.version]: [2.2.0]
[persist.service.bdroid.version]: [4.1]
[ro.board.platform]: [msm8974]
[ro.boot.hardware]: [qcom]
[ro.boot.serialno]: [xxxxxx]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [G900VVRU2BOE1]
[ro.build.version.release]: [5.0]
[ro.build.version.sdk]: [21]
[ro.build.version.sdl]: [2101]
[ro.com.google.gmsversion]: [5.0_r2]
[ro.config.timaversion]: [3.0]
[ro.hardware]: [qcom]
[ro.opengles.version]: [196108]
[ro.product.brand]: [Verizon]
[ro.product.manufacturer]: [samsung]
[ro.product.model]: [SM-G900V]
[ro.product.name]: [kltevzw]
[ro.revision]: [14]
[ro.serialno]: [e5ce97c7]
You can do this also:
Let’s say df
is your dataframe. Then df.shape
gives you the shape of your dataframe i.e (row,col)
Thus, assign the below command to get the required
row = df.shape[0], col = df.shape[1]
dex
file is a file that is executed on the Dalvik VM.
Dalvik VM includes several features for performance optimization, verification, and monitoring, one of which is Dalvik Executable (DEX).
Java source code is compiled by the Java compiler into .class
files. Then the dx
(dexer) tool, part of the Android SDK processes the .class
files into a file format called DEX
that contains Dalvik byte code. The dx
tool eliminates all the redundant information that is present in the classes. In DEX
all the classes of the application are packed into one file. The following table provides comparison between code sizes for JVM jar files and the files processed by the dex
tool.
The table compares code sizes for system libraries, web browser applications, and a general purpose application (alarm clock app). In all cases dex tool reduced size of the code by more than 50%.
In standard Java environments each class in Java code results in one .class
file. That means, if the Java source code file has one public class and two anonymous classes, let’s say for event handling, then the java compiler will create total three .class
files.
The compilation step is same on the Android platform, thus resulting in multiple .class
files. But after .class
files are generated, the “dx” tool is used to convert all .class
files into a single .dex
, or Dalvik Executable, file. It is the .dex
file that is executed on the Dalvik VM. The .dex
file has been optimized for memory usage and the design is primarily driven by sharing of data.
You want to treat dot (.
) like comma (,
). So, replace
if (double.TryParse(values[i, j], out tmp))
with
if (double.TryParse(values[i, j].Replace('.', ','), out tmp))
In your JSON format, it do not have starting JSON object
Like :
{
"info" : <!-- this is starting JSON object -->
{
"caller":"getPoiById",
"results":
{
"indexForPhone":0,
"indexForEmail":"NULL",
.
.
}
}
}
Above Json starts with info
as JSON object. So while executing :
JSONObject json = new JSONObject(result); // create JSON obj from string
JSONObject json2 = json.getJSONObject("info"); // this will return correct
Now, we can access result
field :
JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"
I think this was missing and so the problem was solved while we use JSONTokener
like answer of yours.
Your answer is very fine. Just i think i add this information so i answered
Thank you
The change
event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)
Consider the following code:
$('input[name="job[video_need]"]').on('change', function () {
var value;
if ($(this).val() == 'none') {
value = 'hide';
} else {
value = 'show';
}
$('#video-script-collapse').collapse(value);
});
I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.
UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}
Example:
UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;
The fact that you're using a view model has no bearing. The standard way of using PagedList
is to store "one page of items" as a ViewBag
variable. All you have to determine is what collection constitutes what you'll be paging over. You can't logically page multiple collections at the same time, so assuming you chose Instructors
:
ViewBag.OnePageOfItems = myViewModelInstance.Instructors.ToPagedList(pageNumber, 10);
Then, the rest of the standard code works as it always has.
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
file_get_contents('php://input') will not always work.
I have a request with in the headers "content-length=735" and "php://input" is empty string. So depends on how good/valid the HTTP request is.
It is language dependent - IIRC C# optimises this, so there isn't any difference, but JavaScript (for example) will do the whole memory allocation shebang each time.
Maybe something like this:
sed 's/ab/~~/g; s/bc/ab/g; s/~~/bc/g'
Replace ~
with a character that you know won't be in the string.
Recently I found a quite interesting solution to the problem.
You could use appearance: none;
to turn off the checkbox's default style and then write your own over it like described here (Example 4).
input[type=checkbox] {_x000D_
width: 23px;_x000D_
height: 23px;_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
margin-right: 10px;_x000D_
background-color: #878787;_x000D_
outline: 0;_x000D_
border: 0;_x000D_
display: inline-block;_x000D_
-webkit-box-shadow: none !important;_x000D_
-moz-box-shadow: none !important;_x000D_
box-shadow: none !important;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:focus {_x000D_
outline: none;_x000D_
border: none !important;_x000D_
-webkit-box-shadow: none !important;_x000D_
-moz-box-shadow: none !important;_x000D_
box-shadow: none !important;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked {_x000D_
background-color: green;_x000D_
text-align: center;_x000D_
line-height: 15px;_x000D_
}
_x000D_
<input type="checkbox">
_x000D_
Unfortunately browser support is quite bad for the appearance
option. From my personal testing I only got Opera and Chrome working correctly. But this would be the way to go to keep it simple when better support comes or you only want to use Chrome/Opera.
A simpler way to do this would be:
Sub populateB()
For Each Cel in Range("A1:A100")
If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next
End Sub
Move doSomething
definition outside of its class declaration and after B
and also make add
accessible to A
by public
-ing it or friend
-ing it.
class B;
class A
{
void doSomething(B * b);
};
class B
{
public:
void add() {}
};
void A::doSomething(B * b)
{
b->add();
}
If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module
$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s
You could use PHP's json_decode function:
$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];
Swift 2.0
Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.
import UIKit
class PopOverViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.preferredContentSize = CGSizeMake(200, 200)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")
}
func dismiss(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
See ViewController:
// ViewController.swift
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
func showPopover(base: UIView)
{
if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .Popover
if let pctrl = navController.popoverPresentationController {
pctrl.delegate = self
pctrl.sourceView = base
pctrl.sourceRect = base.bounds
self.presentViewController(navController, animated: true, completion: nil)
}
}
}
override func viewDidLoad(){
super.viewDidLoad()
}
@IBAction func onShow(sender: UIButton)
{
self.showPopover(sender)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !
I was getting the same error because of jquery CDN (<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
) was added two times in the HTML head.
Ian put this in the comment, but I think it's a good answer:
if (exists("aVariable"))
{
do whatever
}
note that the variable name is quoted.
Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?
You're looking for java.util.LinkedHashMap. You'll get a list of Map.Entry<K,V> pairs, which always get iterated in the same order. That order is the same as the order by which you put the items in. Alternatively, use the java.util.SortedMap, where the keys must either have a natural ordering or have it specified by a Comparator
.
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
Oracle specific, and doesn't rely on pre-existing large tables or complicated system views over data dictionary objects.
SELECT c1 from dual
MODEL DIMENSION BY (1 as rn) MEASURES (sysdate as c1)
RULES ITERATE (365)
(c1[ITERATION_NUMBER]=SYSDATE-ITERATION_NUMBER)
order by 1
For z-index to work, you also need to give it a position:
header {
width: 100%;
height: 100px;
background: url(../img/top.png) repeat-x;
z-index: 110;
position: relative;
}
If "partly cherry picking" means "within files, choosing some changes but discarding others", it can be done by bringing in git stash
:
git reset HEAD^
to convert the entire cherry-picked commit into unstaged working changes.git stash save --patch
: interactively select unwanted material to stash.git commit
git stash drop
. Tip: if you give the stash of unwanted changes a name: git stash save --patch junk
then if you forget to do (6) now, later you will recognize the stash for what it is.
It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.
let's go to the code example,
In [6]: a = 10
In [7]: id(a)
Out[7]: 10914656
In [8]: b = 10
In [9]: id(b)
Out[9]: 10914656
In [10]: c = 11
In [11]: id(c)
Out[11]: 10914688
In [12]: d = 21
In [13]: id(d)
Out[13]: 10915008
In [14]: e = 11
In [15]: id(e)
Out[15]: 10914688
In [16]: e = 21
In [17]: id(e)
Out[17]: 10915008
In [18]: e is d
Out[18]: True
In [19]: e = 30
In [20]: id(e)
Out[20]: 10915296
From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.
so any variable which is having same value shares the memory.
Not for list and dictionary objects
let's come to your question.
when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.
you can simply use it like this
In [49]: dictionary = {
...: 'k1':1,
...: 'k2':1,
...: 'k3':2,
...: 'k4':2}
...:
...:
In [50]: id(dictionary['k1'])
Out[50]: 10914368
In [51]: id(dictionary['k2'])
Out[51]: 10914368
In [52]: id(dictionary['k3'])
Out[52]: 10914400
In [53]: id(dictionary['k4'])
Out[53]: 10914400
From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P
#define NAME(x) printf("Hello " #x);
main(){
NAME(Ian)
}
//will print: Hello Ian
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
Something like this should work: From Frans Bouma's Blog
SELECT * FROM
(
SELECT a.*, rownum r__
FROM
(
SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'
ORDER BY OrderDate DESC, ShippingDate DESC
) a
WHERE rownum < ((pageNumber * pageSize) + 1 )
)
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)
If you are getting this error, it could be because you don't have a route defined for your get.
For example:
const express = require('express');
const app = express();
app.get('/people', function (req, res) {
res.send('hello');
})
app.listen(3000);
http://http://localhost:3000/people --> this works
http://http://localhost:3000 --> this will output Cannot GET / message.
I used vw
(viewport width) and vh
(viewport height). viewport is your entire screen. 100vw
is your screens total width and 100vh
is total height.
.class_name{
width: 50vw;
height: 50vh;
border: 1px solid red;
position: fixed;
left: 25vw;top: 25vh;
}
Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...
public ActionResult ViewNextItem(string id)...
There are no provisions in C++ to test for the validity of a pointer as a general case. One can obviously assume that NULL (0x00000000) is bad, and various compilers and libraries like to use "special values" here and there to make debugging easier (For example, if I ever see a pointer show up as 0xCECECECE in visual studio I know I did something wrong) but the truth is that since a pointer is just an index into memory it's near impossible to tell just by looking at the pointer if it's the "right" index.
There are various tricks that you can do with dynamic_cast and RTTI such to ensure that the object pointed to is of the type that you want, but they all require that you are pointing to something valid in the first place.
If you want to ensure that you program can detect "invalid" pointers then my advice is this: Set every pointer you declare either to NULL or a valid address immediately upon creation and set it to NULL immediately after freeing the memory that it points to. If you are diligent about this practice, then checking for NULL is all you ever need.
Use the low-level $.ajax()
call:
$.ajax({
url: "/yourservlet",
data: { },
complete: function(xmlHttp) {
// xmlHttp is a XMLHttpRquest object
alert(xmlHttp.status);
}
});
Try this for a redirect:
if (xmlHttp.code != 200) {
top.location.href = '/some/other/page';
}
You can format your output in Java as described in below code snippet.
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012"
System.out.format("%,8d%n", n); // --> " 461,012"
System.out.format("%+,8d%n%n", n); // --> "+461,012"
}
}
You can read more here.
dataString suggests the data is formatted in a string (and maybe delimted by a character).
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
}
if dataString is not a string but infact an array (what your question indicates) use JSON.
Let's look at this with the help of an example. Suppose we have a direct mapped cache and the write back policy is used. So we have a valid bit, a dirty bit, a tag and a data field in a cache line. Suppose we have an operation : write A ( where A is mapped to the first line of the cache).
What happens is that the data(A) from the processor gets written to the first line of the cache. The valid bit and tag bits are set. The dirty bit is set to 1.
Dirty bit simply indicates was the cache line ever written since it was last brought into the cache!
Now suppose another operation is performed : read E(where E is also mapped to the first cache line)
Since we have direct mapped cache, the first line can simply be replaced by the E block which will be brought from memory. But since the block last written into the line (block A) is not yet written into the memory(indicated by the dirty bit), so the cache controller will first issue a write back to the memory to transfer the block A to memory, then it will replace the line with block E by issuing a read operation to the memory. dirty bit is now set to 0.
So write back policy doesnot guarantee that the block will be the same in memory and its associated cache line. However whenever the line is about to be replaced, a write back is performed at first.
A write through policy is just the opposite. According to this, the memory will always have a up-to-date data. That is, if the cache block is written, the memory will also be written accordingly. (no use of dirty bits)
Here's a response to your latest question about the difference between x86_64
and arm64
:
x86_64
architecture is required for running the 64bit simulator.
arm64
architecture is required for running the 64bit device (iPhone
5s, iPhone 6, iPhone 6 Plus, iPad Air, iPad mini with Retina
display).
You are getting this is because you are using a Anaconda distribution of Jupyter notebook. So just do conda install pandas
restart your jupyter notebook
and rerun your cell. It should work.
If you are trying this on a Virtual Env try this
conda create -n name_of_my_env python
This will create a minimal environment with only Python installed in it. To put your self inside this environment run:2 source activate name_of_my_env
On Windows the command is:
activate name_of_my_env
The final step required is to install pandas. This can be done with the following command:
conda install pandas
To install a specific pandas version:
conda install pandas=0.20.3
To install other packages, IPython for example:
conda install ipython
To install the full Anaconda distribution:
conda install anaconda
If you need packages that are available to pip but not conda, then install pip, and then use pip to install those packages:
conda install pip
pip install django
Installing from PyPI
pandas can be installed via pip from PyPI.
pip install pandas
Installing with ActivePython
Hope this helps.
Unfortunately, strptime()
can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:
Support for the
%Z
directive is based on the values contained intzname
and whetherdaylight
is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).
strftime()
doesn't officially support %z
.
You are stuck with python-dateutil
to support timezone parsing, I am afraid.
Simplay you can place HTML select attribute to option
a
like shown below
Define the attributes like selected="selected"
<select>
<option selected="selected">a</option>
<option>b</option>
<option>c</option>
</select>
import matplotlib.pyplot as plt
import numpy as np
#%matplotlib inline
x=list(range(10))
def fun(k):
return np.sin(k)
y=list(map(fun,x))
plt.plot(x,y,'-.')
#print(x)
#print(y)
plt.show()
Any of LinearLayout.LayoutParams
and TableLayout.LayoutParams
worked for me, for buttons the right one is TableRow.LayoutParams
. That is:
TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
About using MATCH_PARENT
or WRAP_CONTENT
be the same.
The name
property is marked as protected
. This was added in TypeScript 1.3 and is now firmly established.
The makeSound
method is marked as abstract
, as is the class. You cannot directly instantiate an Animal
now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.
abstract class Animal {
constructor(protected name: string) { }
abstract makeSound(input : string) : string;
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:
class Animal {
constructor(public name) { }
makeSound(input : string) : string {
throw new Error('This method is abstract');
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity
In order to work on all modern browsers, you will need two steps:
Add javascript:void(0);
as src
attribute for the iframe element. Otherwise the content will be overriden by the empty src
on Firefox.
<iframe src="javascript:void(0);"></iframe>
Programatically change the content of the inner html
element.
$(iframeSelector).contents().find('html').html(htmlContent);
Step 1 from comment (link) by @susan
Step 2 from solutions (link1, link2) by @erimerturk and @x10
Use
[A-Z]?
to make the letter optional. {1}
is redundant. (Of course you could also write [A-Z]{0,1}
which would mean the same, but that's what the ?
is there for.)
You could improve your regex to
^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})
And, since in most regex dialects, \d
is the same as [0-9]
:
^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})
But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?
function printDiv() {
var divToPrint = document.getElementById('printArea');
newWin= window.open();
newWin.document.write(divToPrint.innerHTML);
newWin.location.reload();
newWin.focus();
newWin.print();
newWin.close();
}
This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.
The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
Put the CSS files in public/stylesheets and then use:
<%= stylesheet_link_tag "filename" %>
to link to the stylesheet in your layouts or erb files in your views.
Similarly you put images in public/images and javascript files in public/javascripts.
In dead simple way it makes this meaning.
Functions :
These subprograms return a single value; mainly used to compute and return a value.
Procedure :
These subprograms do not return a value directly; mainly used to perform an action.
Example Program:
CREATE OR REPLACE PROCEDURE greetings
BEGIN
dbms_output.put_line('Hello World!');
END ;
/
Executing a Standalone Procedure :
A standalone procedure can be called in two ways:
• Using the EXECUTE
keyword
• Calling the name of procedure from a PL/SQL block
The procedure can also be called from another PL/SQL block:
BEGIN
greetings;
END;
/
Function:
CREATE OR REPLACE FUNCTION totalEmployees
RETURN number IS
total number(3) := 0;
BEGIN
SELECT count(*) into total
FROM employees;
RETURN total;
END;
/
Following program calls the function totalCustomers
from an another block
DECLARE
c number(3);
BEGIN
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/
This isn't a very beautiful answer, but it's what I use to create zero-length vectors:
0[-1] # numeric
""[-1] # character
TRUE[-1] # logical
0L[-1] # integer
A literal is a vector of length 1, and [-1]
removes the first element (the only element in this case) from the vector, leaving a vector with zero elements.
As a bonus, if you want a single NA
of the respective type:
0[NA] # numeric
""[NA] # character
TRUE[NA] # logical
0L[NA] # integer
To help everyone avoid confusion, I will reformulate the question in two parts.
First : "how can make an authenticated HTTP request with a browser, using BASIC auth?".
In the browser you can do a http basic auth first by waiting the prompt to come, or by editing the URL if you follow this format: http://myusername:[email protected]
NB: the curl command mentionned in the question is perfectly fine, if you have a command-line and curl installed. ;)
References:
Also according to the CURL manual page https://curl.haxx.se/docs/manual.html
HTTP
Curl also supports user and password in HTTP URLs, thus you can pick a file
like:
curl http://name:[email protected]/full/path/to/file
or specify user and password separately like in
curl -u name:passwd http://machine.domain/full/path/to/file
HTTP offers many different methods of authentication and curl supports
several: Basic, Digest, NTLM and Negotiate (SPNEGO). Without telling which
method to use, curl defaults to Basic. You can also ask curl to pick the
most secure ones out of the ones that the server accepts for the given URL,
by using --anyauth.
NOTE! According to the URL specification, HTTP URLs can not contain a user
and password, so that style will not work when using curl via a proxy, even
though curl allows it at other times. When using a proxy, you _must_ use
the -u style for user and password.
The second and real question is "However, on somesite.com, I'm not getting an authorization prompt at all, just a page that says I'm not authorized. Did somesite not implement the Basic Auth workflow correctly, or is there something else I need to do?"
The curl documentation says the -u
option supports many method of authentication, Basic being the default.
Below is for Python-
df.select("col_name").rdd.flatMap(lambda x: x).collect()
Before datalist
(see note below), you would supply an additional input
element for people to type in their own option.
<select name="example">
<option value="A">A</option>
<option value="B">B</option>
<option value="-">Other</option>
</select>
<input type="text" name="other">
_x000D_
This mechanism works in all browsers and requires no JavaScript.
You could use a little JavaScript to be clever about only showing the input
if the "Other" option was selected.
The datalist
element is intended to provide a better mechanism for this concept. In some browsers, e.g. iOS Safari < 12.2, this was not supported or the implementation had issues. Check the Can I Use page to see current datalist support.
<input type="text" name="example" list="exampleList">
<datalist id="exampleList">
<option value="A">
<option value="B">
</datalist>
_x000D_
Although that did work, it took out the entire background colour as well. I was looking for a way to do just the border and just replace that XML layout code with this one and I was good to go!
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
</shape>
Suppose you have this file:
$ cat /tmp/test.txt
Line 1
Line 2 has leading space
Line 3 followed by blank line
Line 5 (follows a blank line) and has trailing space
Line 6 has no ending CR
There are four elements that will alter the meaning of the file output read by many Bash solutions:
If you want the text file line by line including blank lines and terminating lines without CR, you must use a while loop and you must have an alternate test for the final line.
Here are the methods that may change the file (in comparison to what cat
returns):
1) Lose the last line and leading and trailing spaces:
$ while read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
(If you do while IFS= read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
instead, you preserve the leading and trailing spaces but still lose the last line if it is not terminated with CR)
2) Using process substitution with cat
will reads the entire file in one gulp and loses the meaning of individual lines:
$ for p in "$(cat /tmp/test.txt)"; do printf "%s\n" "'$p'"; done
'Line 1
Line 2 has leading space
Line 3 followed by blank line
Line 5 (follows a blank line) and has trailing space
Line 6 has no ending CR'
(If you remove the "
from $(cat /tmp/test.txt)
you read the file word by word rather than one gulp. Also probably not what is intended...)
The most robust and simplest way to read a file line-by-line and preserve all spacing is:
$ while IFS= read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
' Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space '
'Line 6 has no ending CR'
If you want to strip leading and trading spaces, remove the IFS=
part:
$ while read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
'Line 6 has no ending CR'
(A text file without a terminating \n
, while fairly common, is considered broken under POSIX. If you can count on the trailing \n
you do not need || [[ -n $line ]]
in the while
loop.)
More at the BASH FAQ
It may means that you forgot include a header file that define this struct/union. For example:
foo.h file:
typedef union
{
struct
{
uint8_t FIFO_BYTES_AVAILABLE : 4;
uint8_t STATE : 3;
uint8_t CHIP_RDY : 1;
};
uint8_t status;
} RF_CHIP_STATUS_t;
RF_CHIP_STATUS_t getStatus();
main.c file:
.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the #include "foo.h" */
.
.
.
The problem is that jQuery doesn't trigger the native click
event for <a>
elements so that navigation doesn't happen (the normal behavior of an <a>
), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
To trigger it manually, try:
var a = $("<a>")
.attr("href", "http://i.stack.imgur.com/L8rHf.png")
.attr("download", "img.png")
.appendTo("body");
a[0].click();
a.remove();
DEMO: http://jsfiddle.net/HTggQ/
Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
Those methods to tell if a function is implemented also fail if variable is not defined so we are using something more powerful that supports receiving an string:
function isFunctionDefined(functionName) {
if(eval("typeof(" + functionName + ") == typeof(Function)")) {
return true;
}
}
if (isFunctionDefined('myFunction')) {
myFunction(foo);
}
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
name.id
is sufficient unless you really need the other variables outside the function.$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)
I'm building a booking system and found this page. I'm interested in range intersection only, so I built this structure; it is enough to play with DateTime ranges.
You can check Intersection and check if a specific date is in range, and get the intersection type and the most important: you can get intersected Range.
public struct DateTimeRange
{
#region Construction
public DateTimeRange(DateTime start, DateTime end) {
if (start>end) {
throw new Exception("Invalid range edges.");
}
_Start = start;
_End = end;
}
#endregion
#region Properties
private DateTime _Start;
public DateTime Start {
get { return _Start; }
private set { _Start = value; }
}
private DateTime _End;
public DateTime End {
get { return _End; }
private set { _End = value; }
}
#endregion
#region Operators
public static bool operator ==(DateTimeRange range1, DateTimeRange range2) {
return range1.Equals(range2);
}
public static bool operator !=(DateTimeRange range1, DateTimeRange range2) {
return !(range1 == range2);
}
public override bool Equals(object obj) {
if (obj is DateTimeRange) {
var range1 = this;
var range2 = (DateTimeRange)obj;
return range1.Start == range2.Start && range1.End == range2.End;
}
return base.Equals(obj);
}
public override int GetHashCode() {
return base.GetHashCode();
}
#endregion
#region Querying
public bool Intersects(DateTimeRange range) {
var type = GetIntersectionType(range);
return type != IntersectionType.None;
}
public bool IsInRange(DateTime date) {
return (date >= this.Start) && (date <= this.End);
}
public IntersectionType GetIntersectionType(DateTimeRange range) {
if (this == range) {
return IntersectionType.RangesEqauled;
}
else if (IsInRange(range.Start) && IsInRange(range.End)) {
return IntersectionType.ContainedInRange;
}
else if (IsInRange(range.Start)) {
return IntersectionType.StartsInRange;
}
else if (IsInRange(range.End)) {
return IntersectionType.EndsInRange;
}
else if (range.IsInRange(this.Start) && range.IsInRange(this.End)) {
return IntersectionType.ContainsRange;
}
return IntersectionType.None;
}
public DateTimeRange GetIntersection(DateTimeRange range) {
var type = this.GetIntersectionType(range);
if (type == IntersectionType.RangesEqauled || type==IntersectionType.ContainedInRange) {
return range;
}
else if (type == IntersectionType.StartsInRange) {
return new DateTimeRange(range.Start, this.End);
}
else if (type == IntersectionType.EndsInRange) {
return new DateTimeRange(this.Start, range.End);
}
else if (type == IntersectionType.ContainsRange) {
return this;
}
else {
return default(DateTimeRange);
}
}
#endregion
public override string ToString() {
return Start.ToString() + " - " + End.ToString();
}
}
public enum IntersectionType
{
/// <summary>
/// No Intersection
/// </summary>
None = -1,
/// <summary>
/// Given range ends inside the range
/// </summary>
EndsInRange,
/// <summary>
/// Given range starts inside the range
/// </summary>
StartsInRange,
/// <summary>
/// Both ranges are equaled
/// </summary>
RangesEqauled,
/// <summary>
/// Given range contained in the range
/// </summary>
ContainedInRange,
/// <summary>
/// Given range contains the range
/// </summary>
ContainsRange,
}
There are several ways to do it. The subplots
method creates the figure along with the subplots that are then stored in the ax
array. For example:
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:
fig = plt.figure()
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.subplot(2, 2, 4)
plt.plot(x, y)
plt.show()
Some points.
Use $.data Instead of $.fn.data
// regular
$(elem).data(key,value);
// 10x faster
$.data(elem,key,value);
Then, You can get the previous value through the event object, without complicating your life:
$('#myInputElement').change(function(event){
var defaultValue = event.target.defaultValue;
var newValue = event.target.value;
});
Be warned that defaultValue is NOT the last set value. It's the value the field was initialized with. But you can use $.data to keep track of the "oldValue"
I recomend you always declare the "event" object in your event handler functions and inspect them with firebug (console.log(event)) or something. You will find a lot of useful things there that will save you from creating/accessing jquery objects (which are great, but if you can be faster...)
Three steps needed:
Explicitly mark SSL2.0, TLS1.0, TLS1.1 as forbidden on your server machine, by adding Enabled=0
and DisabledByDefault=1
to your registry (the full path is HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols
). See screen for details
Explicitly enable TLS1.2
by following the steps from 1. Just use Enabled=1
and DisabledByDefault=0
respectively.
NOTE: verify server version: Windows Server 2003
does not support the TLS 1.2
protocol
Enable TLS1.2
only on app level, like @John Wu suggested above.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Hope this guide helps.
UPDATE As @Subbu mentioned: Official guide
//How about byte-ing it?
Number.prototype.isInt= function(){
return this== this>> 0;
}
I always feel kind of bad for bit operators in javascript-
they hardly get any exercise.
You need to do
Update table_xpto
set column_xpto = x.xpto_New
,column2 = x.column2New
from table_xpto xpto
inner join table_xptoNew xptoNew ON xpto.bla = xptoNew.Bla
where <clause where>
If you need a better answer, you can give us more information :)
Given the proliferation of different ways to read an Excel file in R
and the plethora of answers here, I thought I'd try to shed some light on which of the options mentioned here perform the best (in a few simple situations).
I myself have been using xlsx
since I started using R
, for inertia if nothing else, and I recently noticed there doesn't seem to be any objective information about which package works better.
Any benchmarking exercise is fraught with difficulties as some packages are sure to handle certain situations better than others, and a waterfall of other caveats.
That said, I'm using a (reproducible) data set that I think is in a pretty common format (8 string fields, 3 numeric, 1 integer, 3 dates):
set.seed(51423)
data.frame(
str1 = sample(sprintf("%010d", 1:NN)), #ID field 1
str2 = sample(sprintf("%09d", 1:NN)), #ID field 2
#varying length string field--think names/addresses, etc.
str3 =
replicate(NN, paste0(sample(LETTERS, sample(10:30, 1L), TRUE),
collapse = "")),
#factor-like string field with 50 "levels"
str4 = sprintf("%05d", sample(sample(1e5, 50L), NN, TRUE)),
#factor-like string field with 17 levels, varying length
str5 =
sample(replicate(17L, paste0(sample(LETTERS, sample(15:25, 1L), TRUE),
collapse = "")), NN, TRUE),
#lognormally distributed numeric
num1 = round(exp(rnorm(NN, mean = 6.5, sd = 1.5)), 2L),
#3 binary strings
str6 = sample(c("Y","N"), NN, TRUE),
str7 = sample(c("M","F"), NN, TRUE),
str8 = sample(c("B","W"), NN, TRUE),
#right-skewed integer
int1 = ceiling(rexp(NN)),
#dates by month
dat1 =
sample(seq(from = as.Date("2005-12-31"),
to = as.Date("2015-12-31"), by = "month"),
NN, TRUE),
dat2 =
sample(seq(from = as.Date("2005-12-31"),
to = as.Date("2015-12-31"), by = "month"),
NN, TRUE),
num2 = round(exp(rnorm(NN, mean = 6, sd = 1.5)), 2L),
#date by day
dat3 =
sample(seq(from = as.Date("2015-06-01"),
to = as.Date("2015-07-15"), by = "day"),
NN, TRUE),
#lognormal numeric that can be positive or negative
num3 =
(-1) ^ sample(2, NN, TRUE) * round(exp(rnorm(NN, mean = 6, sd = 1.5)), 2L)
)
I then wrote this to csv and opened in LibreOffice and saved it as an .xlsx file, then benchmarked 4 of the packages mentioned in this thread: xlsx
, openxlsx
, readxl
, and gdata
, using the default options (I also tried a version of whether or not I specify column types, but this didn't change the rankings).
I'm excluding RODBC
because I'm on Linux; XLConnect
because it seems its primary purpose is not reading in single Excel sheets but importing entire Excel workbooks, so to put its horse in the race on only its reading capabilities seems unfair; and xlsReadWrite
because it is no longer compatible with my version of R
(seems to have been phased out).
I then ran benchmarks with NN=1000L
and NN=25000L
(resetting the seed before each declaration of the data.frame
above) to allow for differences with respect to Excel file size. gc
is primarily for xlsx
, which I've found at times can create memory clogs. Without further ado, here are the results I found:
benchmark1k <-
microbenchmark(times = 100L,
xlsx = {xlsx::read.xlsx2(fl, sheetIndex=1); invisible(gc())},
openxlsx = {openxlsx::read.xlsx(fl); invisible(gc())},
readxl = {readxl::read_excel(fl); invisible(gc())},
gdata = {gdata::read.xls(fl); invisible(gc())})
# Unit: milliseconds
# expr min lq mean median uq max neval
# xlsx 194.1958 199.2662 214.1512 201.9063 212.7563 354.0327 100
# openxlsx 142.2074 142.9028 151.9127 143.7239 148.0940 255.0124 100
# readxl 122.0238 122.8448 132.4021 123.6964 130.2881 214.5138 100
# gdata 2004.4745 2042.0732 2087.8724 2062.5259 2116.7795 2425.6345 100
So readxl
is the winner, with openxlsx
competitive and gdata
a clear loser. Taking each measure relative to the column minimum:
# expr min lq mean median uq max
# 1 xlsx 1.59 1.62 1.62 1.63 1.63 1.65
# 2 openxlsx 1.17 1.16 1.15 1.16 1.14 1.19
# 3 readxl 1.00 1.00 1.00 1.00 1.00 1.00
# 4 gdata 16.43 16.62 15.77 16.67 16.25 11.31
We see my own favorite, xlsx
is 60% slower than readxl
.
Due to the amount of time it takes, I only did 20 repetitions on the larger file, otherwise the commands were identical. Here's the raw data:
# Unit: milliseconds
# expr min lq mean median uq max neval
# xlsx 4451.9553 4539.4599 4738.6366 4762.1768 4941.2331 5091.0057 20
# openxlsx 962.1579 981.0613 988.5006 986.1091 992.6017 1040.4158 20
# readxl 341.0006 344.8904 347.0779 346.4518 348.9273 360.1808 20
# gdata 43860.4013 44375.6340 44848.7797 44991.2208 45251.4441 45652.0826 20
Here's the relative data:
# expr min lq mean median uq max
# 1 xlsx 13.06 13.16 13.65 13.75 14.16 14.13
# 2 openxlsx 2.82 2.84 2.85 2.85 2.84 2.89
# 3 readxl 1.00 1.00 1.00 1.00 1.00 1.00
# 4 gdata 128.62 128.67 129.22 129.86 129.69 126.75
So readxl
is the clear winner when it comes to speed. gdata
better have something else going for it, as it's painfully slow in reading Excel files, and this problem is only exacerbated for larger tables.
Two draws of openxlsx
are 1) its extensive other methods (readxl
is designed to do only one thing, which is probably part of why it's so fast), especially its write.xlsx
function, and 2) (more of a drawback for readxl
) the col_types
argument in readxl
only (as of this writing) accepts some nonstandard R
: "text"
instead of "character"
and "date"
instead of "Date"
.
I'm using next approach:
ProductID OrderID,...
ProductID Title Name LanguageID
LanguageID Name Culture,....
I think it is the version error.
try installing this in following order:
sudo apt-get install python3-mysqldb
pip3 install mysqlclient
python3 manage.py makemigrations
python3 manage.py migrate
- (BOOL)deviceiPhoneOriPod
{
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType rangeOfString:@"iPhone"].location!=NSNotFound)
return YES;
else
return NO;
}
From lambda answer, I have made something closer to the requirements.
boolean imageCreated = false;
Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
if (!imageCreated) {
imageCreated = true;
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
bmp = Bitmap.createBitmap(400, 400, conf);
Canvas canvas1 = new Canvas(bmp);
Paint color = new Paint();
color.setTextSize(30);
color.setColor(Color.WHITE);
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
R.drawable.messi,opt);
Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
canvas1.drawBitmap(resized, 40, 40, color);
canvas1.drawText("Le Messi", 30, 40, color);
currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
.icon(BitmapDescriptorFactory.fromBitmap(bmp))
// Specifies the anchor to be at a particular point in the marker image.
.anchor(0.5f, 1));
} else {
currentLocationMarker.setPosition(currentLocation);
}
}
I was experiencing the white line to the right on my iPad as well in horizontal position only. I was using a fixed-position div with a background set to 960px wide and z-index of -999. This particular div only shows up on an iPad due to a media query. Content was then placed into a 960px wide div wrapper. The answers provided on this page were not helping in my case. To fix the white stripe issue I changed the width of the content wrapper to 958px. Voilá. No more white right white stripe on the iPad in horizontal position.
I just experienced the same problem.
It may be an occlusion in the instructions regarding how to install (or upgrade) Android Studio with all the SDK Tools which both you and I missed or possibly a bug created by a new release of Studio which does not follow the same file conventions as the older versions. I lean towards the latter since many of the SO posts on this topic seems to point to an ANDROID_PATH with a folder called android-sdk which does not appear in the latest (2.3.0.8) version.
There appears to be a workaround though, which I just got to work on my machine. Here's what I did:
Download tools_r25.2.3-windows.zip from Android Downloads.
Extracted zip on desktop
Replaced C:\Users\username\AppData\Local\Android\sdk\tools with extracted sub-folder tools/
In project folder:
$ cordova platforms remove android
$ cordova platforms add android
You may also need to force remove the node_modules in android. Hopefully this helps.
The standard way, which has already been proposed several times is:
for (var name in myObject) {
alert(name);
}
However Internet Explorer 6, 7 and 8 have a bug in the JavaScript interpreter, which has the effect that some keys are not enumerated. If you run this code:
var obj = { toString: 12};
for (var name in obj) {
alert(name);
}
If will alert "12" in all browsers except IE. IE will simply ignore this key. The affected key values are:
isPrototypeOf
hasOwnProperty
toLocaleString
toString
valueOf
To be really safe in IE you have to use something like:
for (var key in myObject) {
alert(key);
}
var shadowedKeys = [
"isPrototypeOf",
"hasOwnProperty",
"toLocaleString",
"toString",
"valueOf"
];
for (var i=0, a=shadowedKeys, l=a.length; i<l; i++) {
if map.hasOwnProperty(a[i])) {
alert(a[i]);
}
}
The good news is that EcmaScript 5 defines the Object.keys(myObject)
function, which returns the keys of an object as array and some browsers (e.g. Safari 4) already implement it.
Yes:
float[] values = {0.1f, 0.2f, 0.3f};
This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:
values = new float[3];
or
values = new float[] {0.1f, 0.2f, 0.3f};
Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?
This is working for me (i use laravel 5.6).
$collection = MyModel::all()->groupBy('column');
If you want to convert the collection to plain php array, you can use toArray()
$array = MyModel::all()->groupBy('column')->toArray();
To Access the Camera and take pictures and set ImageView on Android
You have to use Uri file = Uri.fromFile(getOutputMediaFile());
for marshmallow.
Use below link to get path
Use RxCpp,
std::cout << "Waiting..." << std::endl;
auto values = rxcpp::observable<>::timer<>(std::chrono::seconds(1));
values.subscribe([](int v) {std::cout << "Called after 1s." << std::endl;});
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
On Windows 10, to create the virtual environment, I replace "pip mkvirtualenv myproject" by "mkvirtualenv myproject" and that works well.
No need to add new plugin in pom.xml. Just run this command
mvn org.codehaus.mojo:exec-maven-plugin:1.5.0:java -Dexec.mainClass="com.example.Main" | grep -Ev '(^\[|Download\w+:)'
See the maven exec plugin for more usage.
The absolute path to the directory where
./manage.py collectstatic
will collect static files for deployment. Example:STATIC_ROOT="/var/www/example.com/static/"
now the command ./manage.py collectstatic
will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/
. now you only need to serve this directory on apache or nginx..etc.
The
URL
of which the static files inSTATIC_ROOT
directory are served(by Apache or nginx..etc). Example:/static/
orhttp://static.example.com/
If you set STATIC_URL = 'http://static.example.com/'
, then you must serve the STATIC_ROOT
folder (ie "/var/www/example.com/static/"
) by apache or nginx at url 'http://static.example.com/'
(so that you can refer the static file '/var/www/example.com/static/jquery.js'
with 'http://static.example.com/jquery.js'
)
Now in your django-templates, you can refer it by:
{% load static %}
<script src="{% static "jquery.js" %}"></script>
which will render:
<script src="http://static.example.com/jquery.js"></script>
you can use this trick :
String s = "p";
char c = s.charAt(0);
Here's a solution with robocopy which copies the content of Folder1 into Folder2 going trough all subdirectories and automatically overwriting the files with the same name:
robocopy C:\Folder1 C:\Folder2 /COPYALL /E /IS /IT
Here:
/COPYALL
copies all file information
/E
copies subdirectories including empty directories
/IS
includes the same files
/IT
includes modified files with the same name
For more parameters see the official documentation: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy
Note: it can be necessary to run the command as administrator, because of the argument /COPYALL
. If you can't: just get rid of it.
Hope this helps somebody!
<style> html { scroll-behavior: smooth;} </style>
<a id="top"></>
<!--content here-->
<a href="#top">Back to top..</a>
I have seen many answers to this question and found some answer is lengthy and some answer is a little bit wrong. I have created my own code by using the above IDs and class.
$('#ckbCheckAll').click(function(){
if($(this).prop("checked")) {
$(".checkBoxClass").prop("checked", true);
} else {
$(".checkBoxClass").prop("checked", false);
}
});
$('.checkBoxClass').click(function(){
if($(".checkBoxClass").length == $(".checkBoxClass:checked").length) {
$("#ckbCheckAll").prop("checked", true);
}else {
$("#ckbCheckAll").prop("checked", false);
}
});
In the above code, where user clicks on select all checkbox and all checkbox will be selected and vice versa and second code will work when the user selects checkbox one by one then select all checkbox will be checked or unchecked according to a number of checkboxes checked.
You can use following java code to get new inserted id.
ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, quizid);
ps.setInt(2, userid);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
lastInsertId = rs.getInt(1);
}
The spaceship method is useful when you define it in your own class and include the Comparable module. Your class then gets the >, < , >=, <=, ==, and between?
methods for free.
class Card
include Comparable
attr_reader :value
def initialize(value)
@value = value
end
def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other
self.value <=> other.value
end
end
a = Card.new(7)
b = Card.new(10)
c = Card.new(8)
puts a > b # false
puts c.between?(a,b) # true
# Array#sort uses <=> :
p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>]
There's actually a very little known class in the BCL for this purpose exactly: CommaDelimitedStringCollectionConverter. It serves as a middle ground of sorts between having a ConfigurationElementCollection
(as in Richard's answer) and parsing the string yourself (as in Adam's answer).
For example, you could write the following configuration section:
public class MySection : ConfigurationSection
{
[ConfigurationProperty("MyStrings")]
[TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
public CommaDelimitedStringCollection MyStrings
{
get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
}
}
You could then have an app.config that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="foo" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
</configSections>
<foo MyStrings="a,b,c,hello,world"/>
</configuration>
Finally, your code would look like this:
var section = (MySection)ConfigurationManager.GetSection("foo");
foreach (var s in section.MyStrings)
Console.WriteLine(s); //for example
To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.
import java.text.SimpleDateFormat;
import java.util.Date;
public class test {
public static void main(String argv[]){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println(strDate);
}
}
No need for jQuery. And it isn't necessary to open a new window. Protocols which doesn't return HTTP data to the browser (mailto:
, irc://
, magnet:
, ftp://
(<- it depends how it is implemented, normally the browser has an FTP client built in)) can be queried in the same window without losing the current content. In your case:
function redirect()
{
window.location.href = "mailto:[email protected]";
}
<body onload="javascript: redirect();">
Or just directly
<body onload="javascript: window.location.href='mailto:[email protected]';">
SSLHandshakeException can be resolved 2 ways.
Incorporating SSL
Get the SSL (by asking the source system administrator, can also be downloaded by openssl command, or any browsers downloads the certificates)
Add the certificate into truststore (cacerts) located at JRE/lib/security
provide the truststore location in vm arguments as "-Djavax.net.ssl.trustStore="
Ignoring SSL
For this #2, please visit my other answer on another stackoverflow website: How to ingore SSL verification Ignore SSL Certificate Errors with Java
We can resolve this problem in Spring-Apache-tomcat environment by adding one single line in RequestInterceptor method -
//before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception {
// Some logic
// below statement ensures IE trusts the page formatting and will render it acc. to IE 8 standard.
response.addHeader("X-UA-Compatible", "IE=8");
return true;
}
Reference from - How to create filter and modify response header It covers how we can resolve this problem via a RequestInterceptor (Spring).
If array is static allocated:
size_t size = sizeof(arr) / sizeof(int);
if array is dynamic allocated(heap):
int *arr = malloc(sizeof(int) * size);
where variable size is a dimension of the arr.
I wrote a small command-line based Python script based on pesterfesh that does exactly this:
Another date format
select datediff(day,'20110101','20110301')
Just use the unary minus operator:
int x = 5;
...
x = -x; // Here's the mystery library function - the single character "-"
Java has two minus operators:
0 - x
), andThis compiles and works as expected.
I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.
abort()
sends the calling process the SIGABRT
signal, this is how abort()
basically works.
abort()
is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc()
will call abort()
if its internal structures are damaged by a heap overflow.
The problem is that the change event fires only when focus is moved away from the input (e.g. someone clicks off the input or tabs out of it). Try using keyup instead:
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function() {
if($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
}
});
});
Just hook up the onclick event:
<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>
I checked all the answers around the web and the best one seemed to be: (actually it isn't)
<img src="image.png?cache=none">
at first.
However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.
Solution to this problem was:
<img src="image.png?nocache=<?php echo time(); ?>">
where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.
However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.
To solve this problem, I needed to hash $_GET but since it is array here is the solution:
$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";
Edit:
Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:
echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";
filemtime() gets file modification time.
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
As I was facing this issue minutes ago, in case you are trying to open an existing project in an environment with a newer JDK, make sure you pdate the JDK version in Project Properties -> Project Facets -> Java.
This is a modified version of Tim Post's method; I used /dev/tty instead of /dev/stdout. I don't know why it doesn't work with stdout (which is a link to /proc/self/fd/1):
freopen("log.txt","w",stdout);
...
...
freopen("/dev/tty","w",stdout);
By using /dev/tty the output is redirected to the terminal from where the app was launched.
Hope this info is useful.
I have a function and stored it in a service so i can use it all over my app:
Service:
app.service('SplitArrayService', function () {
return {
SplitArray: function (array, columns) {
if (array.length <= columns) {
return [array];
};
var rowsNum = Math.ceil(array.length / columns);
var rowsArray = new Array(rowsNum);
for (var i = 0; i < rowsNum; i++) {
var columnsArray = new Array(columns);
for (j = 0; j < columns; j++) {
var index = i * columns + j;
if (index < array.length) {
columnsArray[j] = array[index];
} else {
break;
}
}
rowsArray[i] = columnsArray;
}
return rowsArray;
}
}
});
Controller:
$scope.rows = SplitArrayService.SplitArray($scope.images, 3); //im splitting an array of images into 3 columns
Markup:
<div class="col-sm-12" ng-repeat="row in imageRows">
<div class="col-sm-4" ng-repeat="image in row">
<img class="img-responsive" ng-src="{{image.src}}">
</div>
</div>
The ZIP file format does allow to store the permission bits, but Windows programs normally ignore it.
The zip
utility on Cygwin however does preserve the x bit, just like it does on Linux.
If you do not want to use Cygwin, you can take a source code and tweak it so that all *.sh files get the executable bit set.
Or write a script like explained here
For me it worked like I had images in icons
folder under src
and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
One more answer: since you said you need to validate files you are generating (writing), you might want to validate content while you are writing, instead of first writing, then reading back for validation. You can probably do that with JDK API for Xml validation, if you use SAX-based writer: if so, just link in validator by calling 'Validator.validate(source, result)', where source comes from your writer, and result is where output needs to go.
Alternatively if you use Stax for writing content (or a library that uses or can use stax), Woodstox can also directly support validation when using XMLStreamWriter. Here's a blog entry showing how that is done:
I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path
But the main issue was not here. The problem was with these 2 lines of code
strFile = Dir(strPath & "*.csv")
Which should have written as
strFile = Dir(strPath & "\*.csv")
and
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Which should have written as
With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _
Solution:
Instead of using setHeader
method I have used addHeader
.
response.addHeader("Access-Control-Allow-Origin", "*");
*
in above line will allow access to all domains, For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
For issues related to IE<=9, Please see here.
Despite its very explicit and forceful description, RETURN did not work for me inside a stored procedure (to skip further execution). I had to modify the condition logic. Happens on both SQL 2008, 2008 R2:
create proc dbo.prSess_Ins
(
@sSessID varchar( 32 )
, @idSess int out
)
as
begin
set nocount on
select @id= idSess
from tbSess
where sSessID = @sSessID
if @idSess > 0 return -- exit sproc here
begin tran
insert tbSess ( sSessID ) values ( @sSessID )
select @idSess= scope_identity( )
commit
end
had to be changed into:
if @idSess is null
begin
begin tran
insert tbSess ( sSessID ) values ( @sSessID )
select @idSess= scope_identity( )
commit
end
Discovered as a result of finding duplicated rows. Debugging PRINTs confirmed that @idSess had value greater than zero in the IF check - RETURN did not break execution!
Generic answer for future developers.
UPDATE
t1
SET
t1.column = t2.column
FROM
Table1 t1
INNER JOIN Table2 t2
ON t1.id = t2.id;
UPDATE
t1
SET
t1.colmun = t2.column
FROM
Table1 t1,
Table2 t2
WHERE
t1.ID = t2.ID;
UPDATE
Table1 t1,
Table2 t2
SET
t1.column = t2.column
WHERE
t1.ID = t2.ID;
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
Less than or equal:
User.objects.filter(userprofile__level__lte=0)
Greater than or equal:
User.objects.filter(userprofile__level__gte=0)
Likewise, lt
for less than and gt
for greater than. You can find them all in the documentation.
fact(5) = 5* fact(4) = 5 * (4 * fact(3))= 5 * 4 * (3 *fact(2))= 5 * 4 * 3 * 2 * (fact(1))
As we can see above, no fact(x) is repeated so factorial has non overlapping problems.
fib(5) = fib(4) + fib(3) = (fib(3)+fib(2)) + (fib(2)+fib(1))
As we can see above, fib(4) and fib(3) both use fib(2). similarly so many fib(x) gets repeated. that's why Fibonacci has overlapping sub-problems.
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/[email protected]">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
Is it really a function call on the action attribute? or it should be on the onSUbmit attribute, because by convention action attribute needs a page/URL.
I think you should use AJAX with that,
There are plenty PHP AJAX Frameworks to choose from
http://www.phplivex.com/example/submitting-html-forms-with-ajax
http://www.xajax-project.org/en/docs-tutorials/learn-xajax-in-10-minutes/
ETC.
Or the classic way
http://www.w3schools.com/php/php_ajax_php.asp
I hope these links help
That's a half-open interval.
[a,b]
includes the end points.(a,b)
excludes them.In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".
Half-open intervals are useful in programming because they correspond to the common idiom for looping:
for (int i = 0; i < n; ++i) { ... }
Here i is in the range [0, n).
def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])
return word
def anotherFunction():
for letter in word:
print("_",end=" ")
Actually my problem was that the command line mvn utility wouldn't see the changes for some reason. I turned on the Auto-deploy in the Deployment Scanner and there was still no difference. HOWEVER... I was twiddling around with the Eclipse environment and because I had added a JBoss server for it's Servers window I discovered I had the ability to "Add or Remove..." modules in my workspace. Once the project was added whenever I made a change to code the code change was detected by the Deployment Scanner and JBoss went thru the cycle of updating code!!! Works like a charm.
Here are the steps necessary to set this up;
First if you haven't done so add your JBoss Server to your Eclipse using File->New->Other->Server then go thru the motions of adding your JBoss AS 7 server. Being sure to locate the directory that you are using.
Once added, look down near the bottom of Eclipse to the "Servers" tab. You should see your JBoss server. Highlight it and look for "Add or Remove...". From there you should see your project.
Once added, make a small change to your code and watch JBoss go to town hot deploying for you.
var assoc_pagine = new Array();
assoc_pagine["home"]=0;
Don't use an Array
for this. Arrays are for numerically-indexed lists. Just use a plain Object
({}
).
What you are thinking of with the 'undefined'
string is probably this:
if (typeof assoc_pagine[key]!=='undefined')
This is (more or less) the same as saying
if (assoc_pagine[key]!==undefined)
However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined
value for non-existent properties.
This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined
value.
This is a more explicit, readable and IMO all-round better approach:
if (key in assoc_pagine)
Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
What about:
Create Table New_Users Select * from Old_Users Where 1=2;
and if that doesn't work, just select a row and truncate after creation:
Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;
EDIT:
I noticed your comment below about needing indexes, etc. Try:
show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;
That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:
#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);
To select a checkbox, use the "WebElement"
class.
To operate on a drop-down list, use the "Select"
class.
I have similar problem but I solved it by removing all the foreign key in my Postgresql
// Copied from MSDN, the second point of non-clustered index is not clearly mentioned in the other answers.
Clustered
Nonclustered
I concur with the Dragon Book reference; IMO, it is the definitive guide to compiler construction. Get ready for some hardcore theory, though.
If you want a book that is lighter on theory, Game Scripting Mastery might be a better book for you. If you are a total newbie at compiler theory, it provides a gentler introduction. It doesn't cover more practical parsing methods (opting for non-predictive recursive descent without discussing LL or LR parsing), and as I recall, it doesn't even discuss any sort of optimization theory. Plus, instead of compiling to machine code, it compiles to a bytecode that is supposed to run on a VM that you also write.
It's still a decent read, particularly if you can pick it up for cheap on Amazon. If you only want an easy introduction into compilers, Game Scripting Mastery is not a bad way to go. If you want to go hardcore up front, then you should settle for nothing less than the Dragon Book.
It seems that MySQL process is running hence you are unable to use the port. You can check the running MySQL process using following command:
ps auxf | grep mysql
If you get any MySQL process kill that process ID using kill -9 PID and then try to start MySQL.
My favorite:
https://inloop.github.io/sqlite-viewer/
No installation needed. Just drop the file.
You can do as the example on Mozilla docs:
document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
P.S
Of course, there will be an issue if humanity still uses your code on the first minute of year 10000 :)
This typed error-message also shows while an if-statement
comparison is done where there is an array and for example a bool or int. See for example:
... code snippet ...
if dataset == bool:
....
... code snippet ...
This clause has dataset as array and bool is euhm the "open door"... True
or False
.
In case the function is wrapped within a try-statement
you will receive with except Exception as error:
the message without its error-type:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
This answers improves on Rashmi Pandit's answer, which is in a way better than the rest because that it seems to completely resolve the exact problem detailed in the question.
The bad part is that is inefficient and not uses the IgnoreCase option consistently.
Inefficient part is because regex can be expensive to construct and execute, and in that answer it could have been constructed just once (calling Regex.IsMatch
was just constructing the regex again behind the scene). And Match
method could have been called only once and stored in a variable and then link
and name
should call Result
from that variable.
And the IgnoreCase option was only used in the Match
part but not in the Regex.IsMatch
part.
I also moved the Regex definition outside the method in order to construct it just once (I think is the sensible approach if we are storing that the assembly with the RegexOptions.Compiled
option).
private static Regex hrefRegex = new Regex("<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
var matches = hrefRegex.Match(htmlTd);
if (matches.Success)
{
link = matches.Result("${link}");
name = matches.Result("${name}");
return true;
}
else
{
link = null;
name = null;
return false;
}
}
Close the eclipse and start the server you will able to see and run the project.
in gradle.properties, you can even delete
org.gradle.jvmargs=-Xmx1536m
such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.
Actually I don't know you want to this.
try this
INSERT INTO my_table (my_column)
SELECT
(random() * 10) + 1
;
you can try this (I don't have sql server here today so I can't verify syntax, sorry)
select attributeName
from tableName
where CONVERT(varchar,attributeName,101) BETWEEN '03/01/2009' AND '03/31/2009'
and CONVERT(varchar, attributeName,108) BETWEEN '06:00:00' AND '22:00:00'
and DATEPART(day,attributeName) BETWEEN 2 AND 4
This method lets TextField to finish all processing (copy/paste/undo safe). Does not require to extend classes and allows you to decide what to do with new text after every change (to push it to logic, or turn back to previous value, or even to modify it).
// fired by every text property change
textField.textProperty().addListener(
(observable, oldValue, newValue) -> {
// Your validation rules, anything you like
// (! note 1 !) make sure that empty string (newValue.equals(""))
// or initial text is always valid
// to prevent inifinity cycle
// do whatever you want with newValue
// If newValue is not valid for your rules
((StringProperty)observable).setValue(oldValue);
// (! note 2 !) do not bind textProperty (textProperty().bind(someProperty))
// to anything in your code. TextProperty implementation
// of StringProperty in TextFieldControl
// will throw RuntimeException in this case on setValue(string) call.
// Or catch and handle this exception.
// If you want to change something in text
// When it is valid for you with some changes that can be automated.
// For example change it to upper case
((StringProperty)observable).setValue(newValue.toUpperCase());
}
);
For your case just add this logic inside. Works perfectly.
if (newValue.equals("")) return;
try {
Integer i = Integer.valueOf(newValue);
// do what you want with this i
} catch (Exception e) {
((StringProperty)observable).setValue(oldValue);
}
This is the classic "unicode issue". I believe that explaining this is beyond the scope of a StackOverflow answer to completely explain what is happening.
It is well explained here.
In very brief summary, you have passed something that is being interpreted as a string of bytes to something that needs to decode it into Unicode characters, but the default codec (ascii) is failing.
The presentation I pointed you to provides advice for avoiding this. Make your code a "unicode sandwich". In Python 2, the use of from __future__ import unicode_literals
helps.
Update: how can the code be fixed:
OK - in your variable "source" you have some bytes. It is not clear from your question how they got in there - maybe you read them from a web form? In any case, they are not encoded with ascii, but python is trying to convert them to unicode assuming that they are. You need to explicitly tell it what the encoding is. This means that you need to know what the encoding is! That is not always easy, and it depends entirely on where this string came from. You could experiment with some common encodings - for example UTF-8. You tell unicode() the encoding as a second parameter:
source = unicode(source, 'utf-8')
To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval
. However, JavaScript is such a dynamic language that you really should not have a need for that.
If the script is static, then Rocket's getScript
-suggestion is the way to go.
In case anyone's interested, here's my solution to the problem. It works completely independently of the Draggable objects, by using events on the Droppable object instead. It works quite well:
$(function() {
$(".draggable").draggable({
opacity: .4,
create: function(){$(this).data('position',$(this).position())},
cursor:'move',
start:function(){$(this).stop(true,true)}
});
$('.active').droppable({
over: function(event, ui) {
$(ui.helper).unbind("mouseup");
},
drop:function(event, ui){
snapToMiddle(ui.draggable,$(this));
},
out:function(event, ui){
$(ui.helper).mouseup(function() {
snapToStart(ui.draggable,$(this));
});
}
});
});
function snapToMiddle(dragger, target){
var topMove = target.position().top - dragger.data('position').top + (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
var leftMove= target.position().left - dragger.data('position').left + (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
dragger.animate({top:topMove,left:leftMove},{duration:600,easing:'easeOutBack'});
}
function snapToStart(dragger, target){
dragger.animate({top:0,left:0},{duration:600,easing:'easeOutBack'});
}
If you are using JavaScript to render then use escape_JavaScript("<%=render partial: partial_name, locals=>{@newval=>@oldval}%>");
Remove the RVM load script from /.bash_rc or /.zsh_rc, then use:
rm -rf /.rvm
Or:
rvm implode
this is best solution for me :)
$i=0;
foreach() if ($i < yourlimitnumber) {
$i +=1;
}
Yes, it is. Declare parameter as so:
@Sort varchar(50) = NULL
Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).
Just try $('.handle').css('left', '300px');
This question is asked in a comment by Alex under the accepted answer.
That fact does not mean vw
cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width
or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px
wide--then just set a font-size
that works for that width.
Example 1
With a flexible width container, however, it must be realized that in some way the container is still being sized off the viewport. As such, it is a matter of adjusting a vw
setting based off that percentage size difference to the viewport, which means taking into account the sizing of parent wrappers. Take this example:
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
So if the container is 50% of viewport (as here)
then factor that into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
*/
font-size: 2.5vw;
}
Assuming here the div
is a child of the body
, it is 50%
of that 100%
width, which is the viewport size in this basic case. Basically, you want to set a vw
that is going to look good to you. As you can see in my comment in the above CSS content, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container because the container is flexing with the viewport resizing. UPDATE: here's an example of two differently sized containers.
Example 2
You can help ensure viewport sizing by forcing the calculation based off that. Consider this example:
html {width: 100%;} /* Force 'html' to be viewport width */
body {width: 150%; } /* Overflow the body */
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
Here, the body is 150% of viewport, but the container is 50%
of viewport, so both parents factor into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 3.75vw
(5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
*/
font-size: 3.75vw;
}
The sizing is still based off viewport, but is in essence set up based off the container size itself.
If the sizing of the container element ended up changing dynamically its percentage relationship either via @media
breakpoints or via JavaScript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.
Take example #1 above. If the div
was switched to 25%
width by either @media
or JavaScript, then at the same time, the font-size
would need to adjust in either the media query or by JavaScript to the new calculation of 5vw * .25 = 1.25
. This would put the text size at the same size it would have been had the "width" of the original 50%
container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.
A Challenge
With the CSS3 calc()
function in use, it would become difficult to adjust dynamically, as that function does not work for font-size
purposes at this time. So you could not do a pure CSS 3 adjustment if your width is changing on calc()
. Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size
, so it may not matter.
Use Internet Explorer 8. Then Try the developer tool.. You can debug based on IE 7 also in compatibility mode
Wrapping the existing formula in IFERROR will not achieve:
the average of cells that contain non-zero, non-blank values.
I suggest trying:
=if(ArrayFormula(isnumber(K23:M23)),AVERAGEIF(K23:M23,"<>0"),"")
You have to run pip.exe from the command prompt on my computer.
I type C:/Python27/Scripts/pip2.exe install numpy
There's a note on top of the docs:
Note: The Google Web Search API has been officially deprecated as of November 1, 2010. It will continue to work as per our deprecation policy, but the number of requests you may make per day will be limited. Therefore, we encourage you to move to the new Custom Search API.
The deprecation policy says that they will continue to run the API for 3 years. So if you already have an application that uses the old API, you don't have to rush to change things just yet. If you're writing a new application, use the Custom Search API. See my answer here for how to do this in Python, but the idea's the same for any language.
Math.sqrt returns a double so you'll have to cast it to int as well
distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
In powershell you should use ${pwd}
vs $(pwd)
On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:
Content-Disposition: attachment; filename=quot.pdf;
See content-disposition on the wikipedia MIME page.
Note: jdk1.8.0_201 and jre1.8.0_201 will be changed depending on the version of Java development kit and Java
To check the installation, open CMD\Type javac\Press Enter and Type java\press enter It will show
In RStudio run
Sys.setenv(JAVA_HOME="C:\\Program Files\\Java\\jdk1.8.0_201")
Note: jdk1.8.0_201 will be changed depending on the version of Java development kit
Now you can install and load rJava package without any problem.
This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!
Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.
To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).
let filled = [];_x000D_
filled.length = 10;_x000D_
filled.fill(0);_x000D_
_x000D_
console.log(filled);
_x000D_
These preferences appear to have changed since @alex-dima's answer.
Changing settings
From menu choose: File -> Preferences -> Settings -> User/Workspace Settings. Filter default settings to search
.
You can modify the search.exclude
setting (copy from default setting to your user or workspace settings). That will apply only to searches. Note that settings from files.exclude
will be automatically applied.
If the settings don't work:
Make sure you didn't turn the search exclusion off. In the search area, expand the "files to exclude" input box and make sure that the gear icon is selected.
You might also need to Clear Editor History (See: https://github.com/Microsoft/vscode/issues/6502).
Example settings
For example, I am developing an EmberJS application which saves thousands of files under the tmp directory.
If you select WORKSPACE SETTINGS
on the right side of the search field, the search exclusion will only be applied to this particular project. And a corresponding .vscode
folder will be added to the root folder containing settings.json
.
This is my example settings:
{
// ...
"search.exclude": {
"**/.git": true,
"**/node_modules": true,
"**/bower_components": true,
"**/tmp": true
},
// ...
}
Note: Include a ** at the beginning of any search exclusion to cover the search term over any folders and sub-folders.
Picture of search before updating settings:
Before updating the settings the search results are a mess.
Picture of search after updating settings:
After updating the settings the search results are exactly what I want.
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
//rest of the code
}
finally {
if(scanner!=null)
scanner.close();
}
Or even better: use the new Try with resource statement:
try(Scanner scanner = new Scanner(System.in)){
//rest of your code
}
I wanted similar richness in colors for HTML elements, I was surprised to find that CSS now supports hsl() colors, so a full solution for me is below:
Also see How to automatically generate N "distinct" colors? for more alternatives more similar to this.
function colorByHashCode(value) {_x000D_
return "<span style='color:" + value.getHashCode().intToHSL() + "'>" + value + "</span>";_x000D_
}_x000D_
String.prototype.getHashCode = function() {_x000D_
var hash = 0;_x000D_
if (this.length == 0) return hash;_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
hash = this.charCodeAt(i) + ((hash << 5) - hash);_x000D_
hash = hash & hash; // Convert to 32bit integer_x000D_
}_x000D_
return hash;_x000D_
};_x000D_
Number.prototype.intToHSL = function() {_x000D_
var shortened = this % 360;_x000D_
return "hsl(" + shortened + ",100%,30%)";_x000D_
};_x000D_
_x000D_
document.body.innerHTML = [_x000D_
"javascript",_x000D_
"is",_x000D_
"nice",_x000D_
].map(colorByHashCode).join("<br/>");
_x000D_
span {_x000D_
font-size: 50px;_x000D_
font-weight: 800;_x000D_
}
_x000D_
In HSL its Hue, Saturation, Lightness. So the hue between 0-359 will get all colors, saturation is how rich you want the color, 100% works for me. And Lightness determines the deepness, 50% is normal, 25% is dark colors, 75% is pastel. I have 30% because it fit with my color scheme best.
If you want to do this in two steps, rather than the three of REVERSE-STUFF-REVERSE, you can have your list separator be one or two spaces. Then use RTRIM to trim the trailing spaces, and REPLACE to replace the double spaces with ','
select REPLACE(RTRIM('a b c d '),' ', ', ')
However, this is not a good idea if your original string can contain internal spaces.
Not sure about performance. Each REVERSE creates a new copy of the string, but STUFF is a third faster than REPLACE.
also see this
Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:
SELECT t1.ID, t1.Name
FROM Table1 t1
WHERE NOT EXISTS (
SELECT TOP 1 NULL
FROM Table2 t2
WHERE t1.ID = t2.ID
)
One more good point here is to use @JsonFilter
.
Some details here http://wiki.fasterxml.com/JacksonFeatureJsonFilter
These two settings worked for me to upload 1GB mp4 videos.
<system.web>
<httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
Using subList(30, 38);
will fail because max index 38 is not available in list, so its not possible.
Only way may be before asking for the sublist, you explicitly determine the max index using list size() method.
for example, check size, which returns 35, so call sublist(30, size());
OR
COPIED FROM pb2q comment
dataList = dataList.subList(30, 38 > dataList.size() ? dataList.size() : 38);
In pseudocode:
split it by colon
seconds = 3600 * HH + 60 * MM + SS
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
Pushing and popping registers are behind the scenes equivalent to this:
push reg <= same as => sub $8,%rsp # subtract 8 from rsp
mov reg,(%rsp) # store, using rsp as the address
pop reg <= same as=> mov (%rsp),reg # load, using rsp as the address
add $8,%rsp # add 8 to the rsp
Note this is x86-64 At&t syntax.
Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.
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)
ToString("X2") prints the input in Hexadecimal
Additional thoughts :
Ramdisk - setting the temp drive MySQL uses as a RAM disk, very easy to set up.
memcache - memcache server is easy to set up, use it to store the results of your queries for X amount of time.
For How do I change the overall colors (background and font)?
For MAC : goto Sublime text -> Preferences -> color scheme
using Android KTX library u can parse easily
val uri = myUriString.toUri()
I am not sure but I think there is one command using which you can copy the schema of database into new database, once you have done this you can delete the old database and after this you can again copy the database schema to the old name.
<form method='post' id='userform' action='thisform.php'> <tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
</td> </tr> </table> <input type='submit' class='buttons'> </form>
<?php
if (isset($_POST['checkboxvar']))
{
print_r($_POST['checkboxvar']);
}
?>
You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.
To echo checked options into your email you would then do this:
echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want
Please keep in mind you should always sanitize your input as needed.
For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays
I would suggest to use gradle.build file.
Add a src/androidTest/java directory for the tests (Like Chris starts to explain)
Open gradle.build file and specify there:
android {
compileSdkVersion rootProject.compileSdkVersion
buildToolsVersion rootProject.buildToolsVersion
sourceSets {
androidTest {
java.srcDirs = ['androidTest/java']
}
}
}
Press "Sync Project with Gradle file" (at the top panel). You should see now a folder "java" (inside "androidTest") is a green color.
Now You are able to create there any test files and execute they.
Try assigning a value to $aug1
before use it in if[]
statements; the error message will disappear afterwards.
This is the best and easiest code:
public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}
The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.
You can download the zip. And then create a package
in your project with org.json as name. and paste all the downloaded codes there, and have fun.
I feel this to be the best and the most easiest JSON Decoding.
Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.
If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.
Some applications will actually open up /dev/tty
to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty
(creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.
Wait and Sleep functions lock Excel and you can't do anything else until the delay finishes. On the other hand Loop delays doesn't give you an exact time to wait.
So, I've made this workaround joining a little bit of both concepts. It loops until the time is the time you want.
Private Sub Waste10Sec()
target = (Now + TimeValue("0:00:10"))
Do
DoEvents 'keeps excel running other stuff
Loop Until Now >= target
End Sub
You just need to call Waste10Sec where you need the delay
If you are not bothered about the location of the text present, then you could use Driver.PageSource property as below:
Driver.PageSource.Contains("expected message");
As an improvement to both Praveen and Tony, I use an override:
public partial class MyDatabaseEntities : DbContext
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
validationErrors.Entry.Entity.GetType().FullName,
validationError.PropertyName,
validationError.ErrorMessage);
}
}
throw; // You can also choose to handle the exception here...
}
}
}
Try this listeners=PLAINTEXT://localhost:9092 It must be helpful
Many thanks
The default kill
command accepts command names as an alternative to PID. See kill (1). An often occurring trouble is that bash
provides its own kill
which accepts job numbers, like kill %1
, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the bash
version by calling
enable -n kill
For more info see kill
and enable
entries in bash (1).
@Casperah pointed out that i'm thinking about it wrong:
TextBox
doesn't have linesThe question then is how to accomplish what i want, rather than what WinForms lets me.
There are subtle bugs in the other given variants:
textBox1.AppendText("Hello" + Environment.NewLine);
textBox1.AppendText("Hello" + "\r\n");
textBox1.Text += "Hello\r\n"
textbox1.Text += System.Environment.NewLine + "brown";
They either append or prepend a newline when one (might) not be required.
So, extension helper:
public static class WinFormsExtensions
{
public static void AppendLine(this TextBox source, string value)
{
if (source.Text.Length==0)
source.Text = value;
else
source.AppendText("\r\n"+value);
}
}
So now:
textBox1.Clear();
textBox1.AppendLine("red");
textBox1.AppendLine("green");
textBox1.AppendLine("blue");
and
textBox1.AppendLine(String.Format("Processing file {0}", filename));
Note: Any code is released into the public domain. No attribution required.
You should use LoadXml method, not Load:
xmlDoc.LoadXml(myXML);
Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
}
The best superuser role would be the root.The Syntax is:
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
})
For more details look at built-in roles.
Hope this helps !!!