The classes which you are importing have to be on the classpath. So either the users of your Applet have to have the libraries in the right place or you simply provide those libraries by including them in your jar file. For example like this: Easiest way to merge a release into one JAR file
From Windows 10 version 1607, the limitation has been removed by setting a registry key
Here's the one liner.
${empty value?'value is empty or null':'value is NOT empty or null'}
Here was my solution:
Markup:
<div id="name" disabled="disabled">
Javascript:
document.getElementById("name").disabled = true;
This the best solution for my applications - hope this helps!
$today = Carbon\Carbon::now()->format('Y-m-d').'%';
->where('created_at', 'like', $today);
Hope it will help you
Use imagesLoaded
javascript library.
Usable with plain Javascript and as a jQuery plugin.
I found this command line utility that doesn't show the GUI output but gave me what I needed: https://github.com/na-ka-na/ExcelCompare
Sample output (taken from the project's readme file):
> excel_cmp xxx.xlsx yyy.xlsx
DIFF Cell at Sheet1!A1 => 'a' v/s 'aa'
EXTRA Cell in WB1 Sheet1!B1 => 'cc'
DIFF Cell at Sheet1!D4 => '4.0' v/s '14.0'
EXTRA Cell in WB2 Sheet1!J10 => 'j'
EXTRA Cell in WB1 Sheet1!K11 => 'k'
EXTRA Cell in WB1 Sheet2!A1 => 'abc'
EXTRA Cell in WB2 Sheet3!A1 => 'haha'
----------------- DIFF -------------------
Sheets: [Sheet1]
Rows: [1, 4]
Cols: [A, D]
----------------- EXTRA WB1 -------------------
Sheets: [Sheet1, Sheet2]
Rows: [1, 11]
Cols: [B, K, A]
----------------- EXTRA WB2 -------------------
Sheets: [Sheet1, Sheet3]
Rows: [10, 1]
Cols: [J, A]
-----------------------------------------
Excel files xxx.xlsx and yyy.xlsx differ
A much better way I think would be something like this:
Service:
app.service('FruitsManager',function($q){
function getAllFruits(){
var deferred = $q.defer();
...
// somewhere here use: deferred.resolve(awesomeFruits);
...
return deferred.promise;
}
return{
getAllFruits:getAllFruits
}
});
And in the controller you can simply use:
$scope.fruits = FruitsManager.getAllFruits();
Angular will automatically put the resolved awesomeFruits
into the $scope.fruits
.
I am using laravel5.2 and we can add joins with different options, you can modify as per your requirement.
Option 1:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);//you add more joins here
})// and you add more joins here
->get();
Option 2:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')// you may add more joins
->select('users.*', 'contacts.phone', 'orders.price')
->get();
option 3:
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->leftJoin('...', '...', '...', '...')// you may add more joins
->get();
try this new DecimalFormat("#.00");
update:
double angle = 20.3034;
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(angle);
System.out.println(angleFormated); //output 20.30
Your code wasn't using the decimalformat correctly
The 0 in the pattern means an obligatory digit, the # means optional digit.
update 2: check bellow answer
If you want 0.2677
formatted as 0.27
you should use new DecimalFormat("0.00");
otherwise it will be .27
Yes, you can do this. Assuming your classes exist in the global namespace, something like this will do it:
import types
class Foo:
pass
def str_to_class(s):
if s in globals() and isinstance(globals()[s], types.ClassType):
return globals()[s]
return None
str_to_class('Foo')
==> <class __main__.Foo at 0x340808cc>
Adding to @jakentus answer, below is what worked for me:
Change the file name in the models package to Logon_model.php
(First letter upper case as @jakentus correctly said)
Change the class name as same as file name i.e.
class Logon_model extends CI_Model
Change the name in the load method too as
$this->load->model('Logon_model');
Hope this helps. Happy coding. :)
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
Simply add the following CSS to the container element (here, the div
):
div {
display: flex;
justify-content: space-between;
}
div {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}
_x000D_
<div>_x000D_
<img src="http://placehold.it/100x100" alt="" /> _x000D_
<img src="http://placehold.it/100x100" alt="" />_x000D_
<img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
Use text-align: justify;
on the container element.
Then stretch the content to take up 100% width
<div>
<img src="http://placehold.it/100x100" alt="" />
<img src="http://placehold.it/100x100" alt="" />
<img src="http://placehold.it/100x100" alt="" />
</div>
div {
text-align: justify;
}
div img {
display: inline-block;
width: 100px;
height: 100px;
}
div:after {
content: '';
display: inline-block;
width: 100%;
}
div {_x000D_
text-align: justify;_x000D_
}_x000D_
_x000D_
div img {_x000D_
display: inline-block;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
div:after {_x000D_
content: '';_x000D_
display: inline-block;_x000D_
width: 100%;_x000D_
}
_x000D_
<div>_x000D_
<img src="http://placehold.it/100x100" alt="" /> _x000D_
<img src="http://placehold.it/100x100" alt="" />_x000D_
<img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
IsisCode gives you a good solution. Another one is to position border div inside parent div. Check this example http://jsfiddle.net/A2tu9/
UPD: You can also use pseudo element :after
(:before
), in this case HTML will not be polluted with extra markup:
.my-div {
position: relative;
padding: 4px;
...
}
.my-div:after {
content: '';
position: absolute;
top: -3px;
left: -3px;
bottom: -3px;
right: -3px;
border: 1px #888 solid;
}
Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.
Old answer:
Here is angular2-cookie which is the exact implementation of Angular 1 $cookies
service (plus a removeAll()
method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.
You can inject it as a service in the components providers
array:
import {CookieService} from 'angular2-cookie/core';
@Component({
selector: 'my-very-cool-app',
template: '<h1>My Angular2 App with Cookies</h1>',
providers: [CookieService]
})
After that, define it in the consturctur as usual and start using:
export class AppComponent {
constructor(private _cookieService:CookieService){}
getCookie(key: string){
return this._cookieService.get(key);
}
}
You can get it via npm:
npm install angular2-cookie --save
Try using this tool,which is just a simple js script https://github.com/shashwatsahai/CSSExtractor/ This tool helps in getting the CSS from a specific page listing all sources for active styles and save it to a JSON with source as key and rules as value. It loads all the CSS from the href links and tells all the styles applied from them You can modify the code to save all css into a .css file. Thereby combining all your css.
You can do that via the Storyboard too:
You need to explicitly tell Java that you wish to multiply.
(x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)
Unlike written equations the compiler does not know this is what you wish to do.
This is my solution
var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
console.log("My contents is \"" + cells[i].innerHTML + "\"");
}
Instead of converting to a list, you could just iterate over the first string and create a second string by adding each of the digit characters you find to that new string.
Similarly using Bash regexp. Shall be able to snatch any key/value pair.
key="Body"
re="\"($key)\": \"([^\"]*)\""
while read -r l; do
if [[ $l =~ $re ]]; then
name="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
echo "$name=$value"
else
echo "No match"
fi
done
Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded "
. This is an illustration. Better to use some "industrial" parser :)
First you need to start karma server with
karma start
Then, you can use grep to filter a specific test or describe block:
karma run -- --grep=testDescriptionFilter
In addition to backslash, if a line ends with |
or &&
or ||
, it will be continued on the next line.
If you're using another utility that passes a single argument to grep, you can use:
'[-]X'
Array to string conversion
in latest versions of php 7.x is error, rather than notice, and prevents further code execution.
Using print
, echo
on array is not an option anymore.
Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.
Use var_dump
,print_r
, iterate through input value using foreach
or for
to output input data for names that are declared as input arrays ('name[]
')
Most common practice to catch errors is using try/catch
blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try
block.
try{ //wrap around possible cause of error or notice
if(!empty($_POST['C'])){
echo $_POST['C'];
}
}catch(Exception $e){
//handle the error message $e->getMessage();
}
Another alternative is dotnetprojects SVGImage
This allows native use of .svg files directly in xaml.
The nice part is, it is only one assembly which is about 100k. In comparision to sharpvectors which is much bigger any many files.
Usage:
...
xmlns:svg1="clr-namespace:SVGImage.SVG;assembly=DotNetProjects.SVGImage"
...
<svg1:SVGImage Name="mySVGImage" Source="/MyDemoApp;component/Resources/MyImage.svg"/>
...
That's all.
See:
Disable both direction api and geocoding api and re-enable.
it works for only 5-10 seconds and than automatically disabled itself.
it means you have only 5-10 sec to test you assignment.
Step 1: Create a new resource file in drawable and copy paste
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:color="#fff" android:width="2dp"/>
<corners android:radius="25dp"/>
<padding android:right="15dp" android:top="15dp" android:bottom="15dp" android:left="15dp"/>
</shape>
save it as ButtonUI(let's say)
Step 2: Apply the UI to the button xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="join the crew"
android:background="@drawable/ButtonUI"
android:textColor="#fff"/>
This post asks the same question, but for linux - you may find it helpful. Send a ping to each IP on a subnet
nmap is probably the best tool to use, as it can help identify host OS as well as being faster. It is available for the windows platform on the nmap.org site
just put #login-box
before <h2>Welcome</h2>
will be ok.
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
here is jsfiddle http://jsfiddle.net/SyjjW/4/
Set CORS configuration in Permissions settings for you S3 bucket
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
S3 adds CORS headers only when http request has the Origin
header.
CloudFront does not forward Origin
header by default
You need to whitelist Origin
header in Behavior settings for your CloudFront Distribution.
I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)
After installing pywin32
Steps to correctly install your module (pywin32)
First search where is your python pip is present
1a. For Example in my case location of pip - C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts
Then open your command prompt and change directory to your pip folder location.
cd C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts
C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts>pip install
pypiwin32
Restart your IDE
All done now you can use the module .
Open the svg using Inkscape.
Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/
done
all rect/circle have been converted to path
On Linux you can use clock_gettime()
:
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp
// ... do stuff ... //
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // get final time-stamp
double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
(double)(end.tv_nsec - start.tv_nsec);
// subtract time-stamps and
// multiply to get elapsed
// time in ns
seems like in Angular 1.3.12 you do not need the inner ng-repeat anymore, the outer loop returns the values of the collection is a single map entry
This will get you a list of all files that were deleted in all branches, sorted by their path:
git log --diff-filter=D --summary | grep "delete mode 100" | cut -c 21- | sort > deleted.txt
Works in msysgit (2.6.1.windows.1). Note we need "delete mode 100" as git files may have been commited as mode 100644 or 100755.
now, for dplyr
, adding a distinct counter.
df %>%
group_by(aa, bb) %>%
summarise(first=head(value,1), count=n_distinct(value))
You create groups, them summarise within groups.
If data is numeric, you can use:
first(value)
[there is also last(value)
] in place of head(value, 1)
see: http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html
Full:
> df
Source: local data frame [16 x 3]
aa bb value
1 1 1 GUT
2 1 1 PER
3 1 2 SUT
4 1 2 GUT
5 1 3 SUT
6 1 3 GUT
7 1 3 PER
8 2 1 221
9 2 1 224
10 2 1 239
11 2 2 217
12 2 2 221
13 2 2 224
14 3 1 GUT
15 3 1 HUL
16 3 1 GUT
> library(dplyr)
> df %>%
> group_by(aa, bb) %>%
> summarise(first=head(value,1), count=n_distinct(value))
Source: local data frame [6 x 4]
Groups: aa
aa bb first count
1 1 1 GUT 2
2 1 2 SUT 2
3 1 3 SUT 3
4 2 1 221 3
5 2 2 217 3
6 3 1 GUT 2
A simple pure-Python implementation would be:
import math
import re
from collections import Counter
WORD = re.compile(r"\w+")
def get_cosine(vec1, vec2):
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
denominator = math.sqrt(sum1) * math.sqrt(sum2)
if not denominator:
return 0.0
else:
return float(numerator) / denominator
def text_to_vector(text):
words = WORD.findall(text)
return Counter(words)
text1 = "This is a foo bar sentence ."
text2 = "This sentence is similar to a foo bar sentence ."
vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)
cosine = get_cosine(vector1, vector2)
print("Cosine:", cosine)
Prints:
Cosine: 0.861640436855
The cosine formula used here is described here.
This does not include weighting of the words by tf-idf, but in order to use tf-idf, you need to have a reasonably large corpus from which to estimate tfidf weights.
You can also develop it further, by using a more sophisticated way to extract words from a piece of text, stem or lemmatise it, etc.
Something is mutable only when we are able to change the values held in the memory location without changing the memory location itself.
The trick is: If you find that the memory location before and after the change are the same, it is mutable.
For example, list is mutable. How?
>> a = ['hello']
>> id(a)
139767295067632
# Now let's modify
#1
>> a[0] = "hello new"
>> a
['hello new']
Now that we have changed "a", let's see the location of a
>> id(a)
139767295067632
so it is the same as before. So we mutated a. So list is mutable.
A string is immutable. How do we prove it?
> a = "hello"
> a[0]
'h'
# Now let's modify it
> a[0] = 'n'
----------------------------------------------------------------------
we get
So we failed mutating the string. It means a string is immutable.
In you reassigning, you change the variable to point to a new location itself. Here you have not mutated the string, but mutating the variable itself. The following is what you are doing.
>> a = "hello"
>> id(a)
139767308749440
>> a ="world"
>> id(a)
139767293625808
id
before and after reassignment is different, so it this proves that you are actually not mutating, but pointing the variable to new location. Which is not mutating that string, but mutating that variable.
Sorry to break the news to ya, but there is no way to do this in IE11. I have been troubling with this for some time, but I finally had to see it as a lost course, and just navigate to the files manually.
But where are the files? That depends on a lot of things, I have found them these places on different machines:
This can be done via "run" (Windows+r) and then typing in shell:cache
or by navigating to it through the internet options in IE11 (AskLeo has a fine guide to this, I'm not affiliated in any way).
- Click on the gear icon, then Internet options.
- In the General tab, underneath “Browsing history”, click on Settings.
- In the resulting “Website Data” dialog, click on View files.
- This will open the folder we’re interested in: your Internet Explorer cache.
Make a search for "cookie" to see the cookies only
The path for cookies can be found here via regedit:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cookies
Common path (in 7 & 8)
%APPDATA%\Microsoft\Windows\Cookies
%APPDATA%\Microsoft\Windows\Cookies\Low
Common path (Win 10)
shell:cookies
shell:cookies\low
%userprofile%\AppData\Local\Microsoft\Windows\INetCookies
%userprofile%\AppData\Local\Microsoft\Windows\INetCookies\Low
package SortedSet;
import java.util.*;
public class HashMapValueSort {
public static void main(String[] args){
final Map<Integer, String> map = new HashMap<Integer,String>();
map.put(4,"Mango");
map.put(3,"Apple");
map.put(5,"Orange");
map.put(8,"Fruits");
map.put(23,"Vegetables");
map.put(1,"Zebra");
map.put(5,"Yellow");
System.out.println(map);
final HashMapValueSort sort = new HashMapValueSort();
final Set<Map.Entry<Integer, String>> entry = map.entrySet();
final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
@Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
String value1 = o1.getValue();
String value2 = o2.getValue();
return value1.compareTo(value2);
}
};
final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
sortedSet.addAll(entry);
final Map<Integer,String> sortedMap = new LinkedHashMap<Integer, String>();
for(Map.Entry<Integer, String> entry1 : sortedSet ){
sortedMap.put(entry1.getKey(),entry1.getValue());
}
System.out.println(sortedMap);
}
}
A bit late in the game but just in case it helps anyone.
If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).
The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.
I got the url above from PayPal's tech support.
Tested using a simple Hosted button and IPN. Good luck.
Checkout the tutorial from Ourcodeworld Ourcodeworld - encode and decode html entities with javascript
Most importantly, the he library example
he.encode('foo © bar ? baz ???? qux');
// ? 'foo © bar ≠ baz 𝌆 qux'
// Passing an `options` object to `encode`, to explicitly encode all symbols:
he.encode('foo © bar ? baz ???? qux', {
'encodeEverything': true
});
he.decode('foo © bar ≠ baz 𝌆 qux');
// ? 'foo © bar ? baz ???? qux'
This library would probably make your coding easier and better managed. It is popular, regularly updated and follows the HTML spec. It itself has no dependencies, as can be seen in the package.json
Main culprit for this error is logic which determines encoding when converting Stream
or byte[]
array to .NET string
.
Using StreamReader
created with 2nd constructor parameter detectEncodingFromByteOrderMarks
set to true, will determine proper encoding and create string
which does not break XmlDocument.LoadXml
method.
public string GetXmlString(string url)
{
using var stream = GetResponseStream(url);
using var reader = new StreamReader(stream, true);
return reader.ReadToEnd(); // no exception on `LoadXml`
}
Common mistake would be to just blindly use UTF8
encoding on the stream
or byte[]
. Code bellow would produce string
that looks valid when inspected in Visual Studio debugger, or copy-pasted somewhere, but it will produce the exception when used with Load
or LoadXml
if file is encoded differently then UTF8 without BOM.
public string GetXmlString(string url)
{
byte[] bytes = GetResponseByteArray(url);
return System.Text.Encoding.UTF8.GetString(bytes); // potentially exception on `LoadXml`
}
if anybody still interested, this solved the problem, using jQuery 3.3.1
jQuery('.class').each(function(i,v){
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
jQuery(v).on('change', function(){
if(!confirm('Are you sure?'))
{
var self = jQuery(this);
jQuery(this).find('option').each(function(key, value){
if(parseInt(jQuery(value).val()) === parseInt(self.data('lastSelected')))
{
jQuery(this).prop('selected', 'selected');
}
});
}
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
});
});
The exec
built-in command mirrors functions in the kernel, there are a family of them based on execve
, which is usually called from C.
exec
replaces the current program in the current process, without fork
ing a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;
We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile
, the last statement says something like:
exec appln-program
so now there is no shell to go back to. Even if appln-program
crashes, the end-user cannot get to a shell, because it is not there - the exec
replaced it.
We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh
, and everyone just put into their .login
(csh start-up file) a call to ksh
. While that worked, it left a stray csh
process running, and the logout was two stage which could get confusing. So we changed it to exec ksh
which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh
is not a login-shell).
Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4
etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.
You have obviously seen exec
used somewhere, perhaps if you showed the code that's bugging you we could justify its use.
Edit: I realised that my answer above is incomplete. There are two uses of exec
in shells like ksh
and bash
- used for opening file descriptors. Here are some examples:
exec 3< thisfile # open "thisfile" for reading on file descriptor 3
exec 4> thatfile # open "thatfile" for writing on file descriptor 4
exec 8<> tother # open "tother" for reading and writing on fd 8
exec 6>> other # open "other" for appending on file descriptor 6
exec 5<&0 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4 # copy write file descriptor 4 onto 7
exec 3<&- # close the read file descriptor 3
exec 6>&- # close the write file descriptor 6
Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec
reverts to the original meaning:
exec 3 < thisfile # oops, overwrite the current program with command "3"
There are several ways you can use these, on ksh use read -u
or print -u
, on bash
, for example:
read <&3
echo stuff >&4
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick(event)
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var target = event.target || event.srcElement; // IE
console.log(target);
console.log(target.id);
var img = document.createElement('img');
img.setAttribute('src', target.src);
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img id="muID1" src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
<img id="myID2" src="sabaLogo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
</body>
</html>
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
While the original question may not have been specific to a web service, here is a complete testWebService you can add to display a web service non-cached response plus the file version. We use file version instead of assembly version because we want to know a version, but with all assembly versions 1.0.0.0, the web site can be easily patched (signing and demand link still active!). Replace @Class@ with the name of the web api controller this service is embedded in. It's good for a go/nogo on a web service plus a quick version check.
[Route("api/testWebService")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage TestWebService()
{
HttpResponseMessage responseMessage = Request.CreateResponse(HttpStatusCode.OK);
string loc = Assembly.GetAssembly(typeof(@Class@)).Location;
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(loc);
responseMessage.Content = new StringContent($"<h2>The XXXXX web service GET test succeeded.</h2>{DateTime.Now}<br/><br/>File Version: {versionInfo.FileVersion}");
responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
Request.RegisterForDispose(responseMessage);
return responseMessage;
}
I found it also necessary to add the following to web.config under configuration to make it truly anonymous
<location path="api/testwebservice">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
You could just clone the first row that has the inputs, then get the nested inputs and update their ID to add the row number (and do the same with the first cell).
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x=document.getElementById('POITable');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the first cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
// append the new row to the table
x.appendChild( new_row );
}
Demo below
function deleteRow(row) {_x000D_
var i = row.parentNode.parentNode.rowIndex;_x000D_
document.getElementById('POITable').deleteRow(i);_x000D_
}_x000D_
_x000D_
_x000D_
function insRow() {_x000D_
console.log('hi');_x000D_
var x = document.getElementById('POITable');_x000D_
var new_row = x.rows[1].cloneNode(true);_x000D_
var len = x.rows.length;_x000D_
new_row.cells[0].innerHTML = len;_x000D_
_x000D_
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];_x000D_
inp1.id += len;_x000D_
inp1.value = '';_x000D_
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];_x000D_
inp2.id += len;_x000D_
inp2.value = '';_x000D_
x.appendChild(new_row);_x000D_
}
_x000D_
<div id="POItablediv">_x000D_
<input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/>_x000D_
<table id="POITable" border="1">_x000D_
<tr>_x000D_
<td>POI</td>_x000D_
<td>Latitude</td>_x000D_
<td>Longitude</td>_x000D_
<td>Delete?</td>_x000D_
<td>Add Rows?</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td><input size=25 type="text" id="latbox" /></td>_x000D_
<td><input size=25 type="text" id="lngbox" readonly=true/></td>_x000D_
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>_x000D_
<td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td>_x000D_
</tr>_x000D_
</table>
_x000D_
C does not have strings per se -- what you have is a char pointer pointing to some read-only memory containing the characters "blablabla\0". In order to append a character there, you need a) writable memory and b) enough space for the string in its new form. The string literal "blablabla\0" has neither.
The solutions are:
1) Use malloc()
et al. to dynamically allocate memory. (Don't forget to free()
afterwards.)
2) Use a char array.
When working with strings, consider using strn*
variants of the str*
functions -- they will help you stay within memory bounds.
Major Difference between Object and MAP with Example :
it's Order of iteration in loop, In Map it follows the order as it was set while creation whereas in OBJECT does not.
SEE: OBJECT
const obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";
obj['1'] = "day";
console.log(obj)
**OUTPUT: {1: "day", prop1: "Foo", prop2: "Bar"}**
MAP
const myMap = new Map()
// setting the values
myMap.set("foo", "value associated with 'a string'")
myMap.set("Bar", 'value associated with keyObj')
myMap.set("1", 'value associated with keyFunc')
OUTPUT:
**1. ?0: Array[2]
1. 0: "foo"
2. 1: "value associated with 'a string'"
2. ?1: Array[2]
1. 0: "Bar"
2. 1: "value associated with keyObj"
3. ?2: Array[2]
1. 0: "1"
2. 1: "value associated with keyFunc"**
You may also find this command useful:
mkdir dirname && cd $_
where dirname is the name of the directory you want to create
Add #include "afxwin.h"
in your source file. It will solve your issue.
We can do this by setting out variable of System class in the following way
System.setOut(new PrintStream(new FileOutputStream("Path to output file"))). Also You need to close or flush 'out'(System.out.close() or System.out.flush()) variable so that you don't end up missing some output.
Source : http://xmodulo.com/how-to-save-console-output-to-file-in-eclipse.html
The cunningly-named urlencode() and urldecode().
However, you shouldn't need to use urldecode()
on variables that appear in $_POST
and $_GET
.
It depends on the property type that you are parsing.
If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:
(long) jsonObj.get("id") // with id = 5, cast `5` to long
After getting the long,you could cast again to int, resulting in:
(int) (long) jsonObj.get("id")
If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();
Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long
The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.
If not using Java Generics, the best way to deal with these runtime exceptions that I use is:
if(jsonObj.get("id") == null) {
// do something here
}
int id;
try{
id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
// handle here
}
You could also remove that first if and add the exception to the catch. Hope this helps.
What I do for abstract classes and interfaces is the following: I write a test, that uses the object as it is concrete. But the variable of type X (X is the abstract class) is not set in the test. This test-class is not added to the test-suite, but subclasses of it, that have a setup-method that set the variable to a concrete implementation of X. That way I don't duplicate the test-code. The subclasses of the not used test can add more test-methods if needed.
You can do this:
<select class='form-control'
(change)="ChangingValue($event)" [value]='46'>
<option value='47'>47</option>
<option value='46'>46</option>
<option value='45'>45</option>
</select>
// Note: You can set the value of select only from options tag. In the above example, you cannot set the value of select to anything other than 45, 46, 47.
For me, it got worked when I ran the npm install command inside the project folder. Ex: I have shoppingmenu app and I ran the npm install command inside that folder.
This is for bootstrap v4 compiled via grunt or some other task runner
You would need to change $table-hover-bg
to set the highlight on hover
$table-cell-padding: .75rem !default;
$table-sm-cell-padding: .3rem !default;
$table-bg: transparent !default;
$table-accent-bg: rgba(0,0,0,.05) !default;
$table-hover-bg: rgba(0,0,0,.075) !default;
$table-active-bg: $table-hover-bg !default;
$table-border-width: $border-width !default;
$table-border-color: $gray-lighter !default;
From the title I'm guessing you only need one result per unique row? If this is the case, take a look at the GROUP BY clause (or SELECT DISTINCT).
Let me to recommend you a jQuery plugin for nice modal alers. It doesn't requires jquery UI.
Demo: http://www.webmasters.by/images/articles/jquery.alerts/index.html
Here's a simpler one that takes dst in to account
CREATE FUNCTION [dbo].[UtcToLocal]
(
@p_utcDatetime DATETIME
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), @p_utcDatetime), GETDATE())
END
no control over the dialog box, if you had control over the dialog box you could write obtrusive javascript code. (Its is not a good idea to use alert for anything except debugging)
Try %*s
and %-*s
and prefix each string with the column width:
>>> print "Location: %-*s Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10 Revision: 1
>>> print "District: %-*s Date: %s" % (20,"Tower","May 16, 2012")
District: Tower Date: May 16, 2012
Expanding on Greg Kindel's second answer, you can write a function to eliminate some of the boilerplate:
var fmt = {
join: function() {
return Array.prototype.slice.call(arguments).join(' ');
},
log: function() {
console.log(this.join(...arguments));
}
}
Usage:
var age = 7;
var years = 5;
var sentence = fmt.join('I am now', age, 'years old!');
fmt.log('In', years, 'years I will be', age + years, 'years old!');
this line should work for your 3 examples:
sed -r 's#\?(page)=([^&]*)&#/\1/\2#g' a.txt
-r
to save some escaping .test with your example (a.txt):
kent$ echo "?page=one&
?page=two&
?page=three&"|sed -r 's#\?(page)=([^&]*)&#/\1/\2#g'
/page/one
/page/two
/page/three
A little slower, but readable I think:
>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]
watch -n 5 'ls -l
Will Runls -l
command after every 5s
Every 5.0s: ls -l Fri Nov 17 16:28:25 2017
total 169548
-rw-rw-r-- 1 sachin sachin 4292 Oct 18 12:16 About_us_Admission.doc
-rw-rw-r-- 1 sachin sachin 865 Oct 13 15:26 About_us_At_glance.doc
-rw-rw-r-- 1 sachin sachin 1816 Oct 13 16:11 About_us_Principle.doc
-rw-rw-r-- 1 sachin sachin 1775 Oct 13 15:59 About_us_Vission_mission.doc
-rw-rw-r-- 1 sachin sachin 1970 Oct 13 16:41 Academic_Middle_school.doc
-rw-rw-r-- 1 sachin sachin 772 Oct 16 16:07 academics_High_School.doc
-rw-rw-r-- 1 sachin sachin 648 Oct 16 13:34 academics_pre_primary.doc
-rw-rw-r-- 1 sachin sachin 708 Oct 16 13:39 academics_primary.doc
-rwxrwxr-x 1 sachin sachin 8816 Nov 1 12:10 a.out
-rw-rw-r-- 1 sachin sachin 23956 Oct 23 18:14 Ass1.c++
-rw-rw-r-- 1 sachin sachin 342 Oct 23 22:13 Ass2.doc
drwxrwxr-x 2 sachin sachin 4096 Oct 19 10:45 Backtracking
drwxrwxr-x 3 sachin sachin 4096 Sep 23 20:09 BeautifulSoup
drwxrwxr-x 2 sachin sachin 4096 Nov 2 00:18 CL_1
drwxrwxr-x 2 sachin sachin 4096 Oct 23 20:16 Code
drwxr-xr-x 2 sachin sachin 4096 Nov 15 12:05 Desktop
-rw-rw-r-- 1 sachin sachin 0 Oct 13 23:12 doc
drwxr-xr-x 4 sachin sachin 4096 Nov 6 21:18 Documents
drwxr-xr-x 27 sachin sachin 12288 Nov 17 13:23 Downloads
-rw-r--r-- 1 sachin sachin 8980 Sep 19 23:58 examples.desktop
if you got actuall time in mind GETDATE()
would be the function what you looking for
This might be optimal
public static string GetPropertyName<TResult>(Expression<Func<TResult>> expr)
{
var memberAccess = expr.Body as MemberExpression;
var propertyInfo = memberAccess?.Member as PropertyInfo;
var propertyName = propertyInfo?.Name;
return propertyName;
}
Based off Michael's answer, I have created my own version of this using jQuery. I think it is a cleaner/shorter version of most answers here and it seems to get the job done.
I am doing the same thing as most of the people here by using a span to write the input text into then getting the width. Then I am setting the width when the actions keyup
and blur
are called.
Here is a working codepen. This codepen shows how this can be used with multiple input fields.
HTML Structure:
<input type="text" class="plain-field" placeholder="Full Name">
<span style="display: none;"></span>
jQuery:
function resizeInputs($text) {
var text = $text.val().replace(/\s+/g, ' '),
placeholder = $text.attr('placeholder'),
span = $text.next('span');
span.text(placeholder);
var width = span.width();
if(text !== '') {
span.text(text);
var width = span.width();
}
$text.css('width', width + 5);
};
The function above gets the inputs value, trims the extra spaces and sets the text into the span to get the width. If there is no text, it instead gets the placeholder and enters that into the span instead. Once it enters the text into the span it then sets the width of the input. The + 5
on the width is because without that the input gets cut off a tiny bit in the Edge Browser.
$('.plain-field').each(function() {
var $text = $(this);
resizeInputs($text);
});
$('.plain-field').on('keyup blur', function() {
var $text = $(this);
resizeInputs($text);
});
$('.plain-field').on('blur', function() {
var $text = $(this).val().replace(/\s+/g, ' ');
$(this).val($text);
});
If this could be improved please let me know as this is the cleanest solution I could come up with.
You have several options
integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)
public boolean isPalindrom(String text) {
StringBuffer stringBuffer = new StringBuffer(text);
return stringBuffer.reverse().toString().equals(text);
}
Starting with SQL Server 2012, you could use TRY_PARSE or TRY_CONVERT.
SELECT TRY_PARSE(MyVarcharCol as int)
SELECT TRY_CONVERT(int, MyVarcharCol)
Php Version: 5.6
Symfony version: 2.3
Guzzle: 5.0
I had an experience recently about sending json with Guzzle. I use Symfony 2.3 so my guzzle version can be a little older.
I will also show how to use debug mode and you can see the request before sending it,
When i made the request as shown below got the successfull response;
use GuzzleHttp\Client;
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
"Content-Type" => "application/json"
];
$body = json_encode($requestBody);
$client = new Client();
$client->setDefaultOption('headers', $headers);
$client->setDefaultOption('verify', false);
$client->setDefaultOption('debug', true);
$response = $client->post($endPoint, array('body'=> $body));
dump($response->getBody()->getContents());
I think your date data should look like 2013-08-14.
<?php
$yrdata= strtotime('2013-08-14');
echo date('M-Y', $yrdata);
?>
// Output is Aug-2013
Note: The title of this question used to be something like "How to printf in python?"
Since people may come here looking for it based on the title, Python also supports printf-style substitution:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
And, you can handily multiply string values:
>>> print "." * 10
..........
Similar to @radiak's response, but with jQuery (see this API document and comment on how to change the selectedIndex
).
$('#mySelectParent').find("select").prop("selectedIndex",-1);
The benefits to this approach are:
#mySelectParent
in the example)Assume that you have an array of classes to being added, you can use ES6 spread syntax:
let classes = ['first', 'second', 'third'];
elem.classList.add(...classes);
In the first step, it will work fine as the value of a
will be 1 and that of b
will be 2 but as 2+1 will be returned and in the next step the value of b
will be the return value from step 1 i.e 3
and so b.x
will be undefined...and undefined + anyNumber will be NaN and that is why you are getting that result.
arr.reduce(function(a,b){return a + b.x},0);
All saved Authentication Data for all projects is deleted.
You will have to re-enter credentials to reconnect.
Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:
Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:
<configuration>
<system.serviceModel>
<services>
<service name="com.aschneider.examples.wcf.services.EchoService">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/EchoService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors></serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:
<configuration>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IEchoService"/>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address = "net.pipe://localhost/EchoService"
binding = "netNamedPipeBinding"
bindingConfiguration = "NetNamedPipeBinding_IEchoService"
contract = "EchoServiceReference.IEchoService"
name = "NetNamedPipeBinding_IEchoService"/>
</client>
</system.serviceModel>
</configuration>
The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).
Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...
I was having the same problem, but then after a bit of research I tried
brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python
in terminal
A warning message will pop-up saying that python 3.7.0
. is already installed but it's not linked
so type the command brew link python
and hit enter and hope things work right for you
The only way I can think of for short texts like "MENU" is to put every single letter in a span and justify them in a container afterwards. Like this:
<div class="menu-burger">
<span></span>
<span></span>
<span></span>
<div>
<span>M</span>
<span>E</span>
<span>N</span>
<span>U</span>
</div>
</div>
And then the CSS:
.menu-burger {
width: 50px;
height: 50px;
padding: 5px;
}
...
.menu-burger > div {
display: flex;
justify-content: space-between;
}
Apache Spark does not support native CSV output on disk.
You have four available solutions though:
You can convert your Dataframe into an RDD :
def convertToReadableString(r : Row) = ???
df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)
What I usually do if I want to append all the partitions into a big CSV is
cat filePath/part* > mycsvfile.csv
Some will use coalesce(1,false)
to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.
Note that df.rdd
will return an RDD[Row]
.
With Spark <2, you can use databricks spark-csv library:
Spark 1.4+:
df.write.format("com.databricks.spark.csv").save(filepath)
Spark 1.3:
df.save(filepath,"com.databricks.spark.csv")
With Spark 2.x the spark-csv
package is not needed as it's included in Spark.
df.write.format("csv").save(filepath)
You can convert to local Pandas data frame and use to_csv
method (PySpark only).
Note: Solutions 1, 2 and 3 will result in CSV format files (part-*
) generated by the underlying Hadoop API that Spark calls when you invoke save
. You will have one part-
file per partition.
I have two Project in one Solution with Same Controller Name. I Removed second Project Reference in first Project and Issue is Resolved
You can use window.btoa
and window.atob
...
const encoded = window.btoa('Alireza Dezfoolian'); // encode a string
const decoded = window.atob(encoded); // decode the string
Probably using the way which MDN is can do your job the best... Also accepting unicode... using these two simple functions:
// ucs-2 string to base64 encoded ascii
function utoa(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
// base64 encoded ascii to ucs-2 string
function atou(str) {
return decodeURIComponent(escape(window.atob(str)));
}
// Usage:
utoa('? à la mode'); // 4pyTIMOgIGxhIG1vZGU=
atou('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
utoa('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
atou('SSDimaEgVW5pY29kZSE='); // "I ? Unicode!"
Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.
You either need to catch it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
Or declare that your method can throw an InterruptedException
:
public static void main(String[]args) throws InterruptedException
Related
Use COALESCE
to avoid that outcome.
SELECT COALESCE(SUM(column),0)
FROM table
WHERE ...
To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0
More Information:
Given three tables (one with all numbers, one with all nulls, and one with a mixture):
MySQL 5.5.32 Schema Setup:
CREATE TABLE foo
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);
CREATE TABLE bar
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);
CREATE TABLE baz
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);
Query 1:
SELECT 'foo' as table_name,
'mixed null/non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM foo
UNION ALL
SELECT 'bar' as table_name,
'all non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM bar
UNION ALL
SELECT 'baz' as table_name,
'all null' as description,
0 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM baz
| TABLE_NAME | DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
| foo | mixed null/non-null | 21 | 21 |
| bar | all non-null | 21 | 21 |
| baz | all null | 0 | 0 |
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
You can use getFragmentManager().popBackStack()
in basic Fragment
to go back.
If you are using cpp11 (enable with the -std=c++0x
flag if needed), then you can simply initialize the vector like this:
// static std::vector<std::string> v;
v = {"haha", "hehe"};
This will disable/enable the options when you select/remove them, respectively.
$("#theSelect").change(function(){
var value = $(this).val();
if (value === '') return;
var theDiv = $(".is" + value);
var option = $("option[value='" + value + "']", this);
option.attr("disabled","disabled");
theDiv.slideDown().removeClass("hidden");
theDiv.find('a').data("option",option);
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
$(this).data("option").removeAttr('disabled');
});
Why don't you try the fadeIn() instead of using a show() with delay(). I think what you are trying to do can be done with this. Here is the jQuery code for fadeIn and FadeOut() which also has inbuilt method for delaying the process.
$(document).ready(function(){
$('element').click(function(){
//effects take place in 3000ms
$('element_to_hide').fadeOut(3000);
$('element_to_show').fadeIn(3000);
});
}
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
InputStream is=getResources().openRawResource(R.raw.name);
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer data=new StringBuffer();
String line=reader.readLine();
while(line!=null)
{
data.append(line+"\n");
}
tvDetails.seTtext(data.toString());
There are so many ways :)
1st Way:
string[] folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
string jsonString = JsonConvert.SerializeObject(folders);
2nd Way:
string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(d => d.Name).ToArray();
3rd Way:
string[] folders =
new DirectoryInfo(yourPath).GetDirectories().Select(delegate(DirectoryInfo di)
{
return di.Name;
}).ToArray();
I am not new to stackoverflow, just never had an account and usually came here for answers. I can't comment or vote up an answer yet. BUT wanted to say that the code from Michael Bacon above works really well. I am new to Python but not to programming. I have been reading Python Crash Course and there are a few things I wanted to do to break up the reading cover to cover approach. One utility that has uses from an ETL or even data quality perspective would be to capture the row count of a file independently from any ETL. The file has X number of rows, you import into SQL or Hadoop and you end up with X number of rows. You can validate at the lowest level the row count of a raw data file.
I have been playing with his code and doing some testing and this code is very efficient so far. I have created several different CSV files, various sizes, and row counts. You can see my code below and my comments provide the times and details. The code Michael Bacon above provided runs about 6 times faster than the normal Python method of just looping the lines.
Hope this helps someone.
import time
from itertools import (takewhile,repeat)
def readfilesimple(myfile):
# watch me whip
linecounter = 0
with open(myfile,'r') as file_object:
# watch me nae nae
for lines in file_object:
linecounter += 1
return linecounter
def readfileadvanced(myfile):
# watch me whip
f = open(myfile, 'rb')
# watch me nae nae
bufgen = takewhile(lambda x: x, (f.raw.read(1024 * 1024) for _ in repeat(None)))
return sum(buf.count(b'\n') for buf in bufgen if buf)
#return linecounter
# ************************************
# Main
# ************************************
#start the clock
start_time = time.time()
# 6.7 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfilesimple("c:/junk/book1.csv")
# 0.67 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfileadvanced("c:/junk/book1.csv")
# 25.9 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")
# 5.7 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")
# 292.92 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")
# 57 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")
#stop the clock
elapsed_time = time.time() - start_time
print("\nCode Execution: " + str(elapsed_time) + " seconds\n")
print("File contains: " + str(mycount) + " lines of text.")
The easiest way to do is so...
You set the name and value.
<input type="checkbox" name="selectedProducts" value="@item.ProductId" />@item.Name
Then on submitting grab the values of checkboxes and save in an int array. then the appropriate LinQ Function. That's it..
[HttpPost]
public ActionResult Checkbox(int[] selectedObjects)
{
var selected = from x in selectedObjects
from y in db
where y.ObjectId == x
select y;
return View(selected);
}
A different approach, i.e: You could just do it 'the Angular way' and use ngModel
and skip document.getElementById('loginInput').value = '123';
altogether. Instead:
<input type="text" [(ngModel)]="username"/>
<input type="text" [(ngModel)]="password"/>
and in your component you give these values:
username: 'whatever'
password: 'whatever'
this will preset the username and password upon navigating to page.
If we get this type of error just use the command:
npm i @anglar/core,
npm i @angular/common,
npm i @angular/http,
npm i @angular/router
After installing this also showing error just remove few words then again add that word its working.
In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.
If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO
Using events, and the properties of the tab control you can enable/disable what you want when you want. I used one bool that is available to all methods in the mdi child form class where the tabControl is being used.
Remember the selecting event fires every time any tab is clicked. For large numbers of tabs a "CASE" might be easier to use than a bunch of ifs.
public partial class Form2 : Form
{
bool formComplete = false;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
formComplete = true;
tabControl1.SelectTab(1);
}
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages[1])
{
tabControl1.Enabled = false;
if (formComplete)
{
MessageBox.Show("You will be taken to next tab");
tabControl1.SelectTab(1);
}
else
{
MessageBox.Show("Try completing form first");
tabControl1.SelectTab(0);
}
tabControl1.Enabled = true;
}
}
}
This is because with {{}}
the angular compiler considers both the text node and it's parent as there is a possibility of merging of 2 {{}}
nodes. Hence there are additional linkers that add to the load time. Of course for a few such occurrences the difference is immaterial, however when you are using this inside a repeater of large number of items, it will cause an impact in slower runtime environment.
func viewDidLoad(){
saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
self.saveActionButton.setTitle("Done", for: .normal)
self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
self.saveActionButton.layer.borderWidth = 1
self.saveActionButton.center.y = self.view.frame.size.height - 80
self.view.addSubview(saveActionButton)
}
func doneAction(){
print("Write your own logic")
}
You can use your exception message by:-
public class MyNullPointException extends NullPointerException {
private ExceptionCodes exceptionCodesCode;
public MyNullPointException(ExceptionCodes code) {
this.exceptionCodesCode=code;
}
@Override
public String getMessage() {
return exceptionCodesCode.getCode();
}
public class enum ExceptionCodes {
COULD_NOT_SAVE_RECORD ("cityId:001(could.not.save.record)"),
NULL_POINT_EXCEPTION_RECORD ("cityId:002(null.point.exception.record)"),
COULD_NOT_DELETE_RECORD ("cityId:003(could.not.delete.record)");
private String code;
private ExceptionCodes(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
Alternatively, db.rawQuery(sql, selectionArgs) exists.
Cursor c = db.rawQuery(select, null);
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
If you are looking for UML sequence diagrams, you might be interested in pkf-umlsd, which is based on TiKZ. Nice demos can be found here.
How do I set up the basic authorization?
All you need to do is use -u, --user USER[:PASSWORD]
. Behind the scenes curl
builds the Authorization
header with base64 encoded credentials for you.
Example:
curl -u username:password -i -H 'Accept:application/json' http://example.com
Another alternative is to use the ufunc.at. This method applies in-place a desired operation at specified indices. We can get the bin position for each datapoint using the searchsorted method. Then we can use at to increment by 1 the position of histogram at the index given by bin_indexes, every time we encounter an index at bin_indexes.
np.random.seed(1)
data = np.random.random(100) * 100
bins = np.linspace(0, 100, 10)
histogram = np.zeros_like(bins)
bin_indexes = np.searchsorted(bins, data)
np.add.at(histogram, bin_indexes, 1)
Assuming you use Python 2.7 (not 3):
print "I have", card.price
(as mentioned above).
print "I have %s" % card.price
(using string formatting)
print " ".join(map(str, ["I have", card.price]))
(by joining lists)
There are a lot of ways to do the same, actually. I would prefer the second one.
In base you can use ave
to get max
per group and compare this with pt
and get a logical vector to subset the data.frame
.
group[group$pt == ave(group$pt, group$Subject, FUN=max),]
# Subject pt Event
#3 1 5 2
#7 2 17 2
#9 3 5 2
Or compare it already in the function.
group[as.logical(ave(group$pt, group$Subject, FUN=function(x) x==max(x))),]
#group[ave(group$pt, group$Subject, FUN=function(x) x==max(x))==1,] #Variant
# Subject pt Event
#3 1 5 2
#7 2 17 2
#9 3 5 2
At a minimum, change this:
function BlockID() {
var IDs = new Array();
images['s'] = "Images/Block_01.png";
images['g'] = "Images/Block_02.png";
images['C'] = "Images/Block_03.png";
images['d'] = "Images/Block_04.png";
return IDs;
}
To this:
function BlockID() {
var IDs = new Object();
IDs['s'] = "Images/Block_01.png";
IDs['g'] = "Images/Block_02.png";
IDs['C'] = "Images/Block_03.png";
IDs['d'] = "Images/Block_04.png";
return IDs;
}
There are a couple fixes to point out. First, images
is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images
to IDs
. Second, you want to return an Object
, not an Array
. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array();
to var IDs = new Object();
.
After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:
function BlockID() {
return {
"s":"Images/Block_01.png"
,"g":"Images/Block_02.png"
,"C":"Images/Block_03.png"
,"d":"Images/Block_04.png"
};
}
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/colorAccent" />
<corners
android:bottomLeftRadius="500dp"
android:bottomRightRadius="500dp"
android:topLeftRadius="500dp"
android:topRightRadius="500dp" />
</shape>
Now, in which element you want to use this shape just add:
android:background="@drawable/custom_round_ui_shape"
Create a new XML in drawable named "custom_round_ui_shape"
I think your port is probably open, but you don't have anything that listens on it.
The Apple Mac OS X operating system has SSH installed by default but the SSH daemon is not enabled. This means you can’t login remotely or do remote copies until you enable it.
To enable it, go to ‘System Preferences’. Under ‘Internet & Networking’ there is a ‘Sharing’ icon. Run that. In the list that appears, check the ‘Remote Login’ option. In OS X Yosemite and up, there is no longer an 'Internet & Networking' menu; it was moved to Accounts. The Sharing menu now has its own icon on the main System Preferences menu. (thx @AstroCB)
This starts the SSH daemon immediately and you can remotely login using your username. The ‘Sharing’ window shows at the bottom the name and IP address to use. You can also find this out using ‘whoami’ and ‘ifconfig’ from the Terminal application.
These instructions are copied from Enable SSH in Mac OS X, but I wanted to make sure they won't go away and to provide quick access.
Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.
Splitting by comma doesn't work all the time for instance if you have csv file like
"Name" , "Job" , "Address"
"Pratiyush, Singh" , "Teacher" , "Berlin, Germany"
So, I would recommend using the Apache Commons CSV API:
Reader in = new FileReader("input1.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
System.out.println(record.get(0));
}
Speed was important for my needs, so I tested three answers to this question.
Code from those three answers was modified as needed for my specific case.
I then compared the speed of each method.
Coding wise:
import numpy as np
import time
import random
import sys
from operator import itemgetter
from heapq import nlargest
''' Fake Data Setup '''
a1 = list(range(1000000))
random.shuffle(a1)
a1 = np.array(a1)
''' ################################################ '''
''' NPE's Answer Modified A Bit For My Case '''
t0 = time.time()
indices = np.flip(np.argsort(a1))[:5]
results = []
for index in indices:
results.append((index, a1[index]))
t1 = time.time()
print("NPE's Answer:")
print(results)
print(t1 - t0)
print()
''' Fred Foos Answer Modified A Bit For My Case'''
t0 = time.time()
indices = np.argpartition(a1, -6)[-5:]
results = []
for index in indices:
results.append((a1[index], index))
results.sort(reverse=True)
results = [(b, a) for a, b in results]
t1 = time.time()
print("Fred Foo's Answer:")
print(results)
print(t1 - t0)
print()
''' off99555's Answer - No Modification Needed For My Needs '''
t0 = time.time()
result = nlargest(5, enumerate(a1), itemgetter(1))
t1 = time.time()
print("off99555's Answer:")
print(result)
print(t1 - t0)
NPE's Answer:
[(631934, 999999), (788104, 999998), (413003, 999997), (536514, 999996), (81029, 999995)]
0.1349949836730957
Fred Foo's Answer:
[(631934, 999999), (788104, 999998), (413003, 999997), (536514, 999996), (81029, 999995)]
0.011161565780639648
off99555's Answer:
[(631934, 999999), (788104, 999998), (413003, 999997), (536514, 999996), (81029, 999995)]
0.439760684967041
Escape the percent sign \%
to make it part of your comparison value.
use a negative character class:
[^,;]+
Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.
jQuery(document).ready(function(jQuery) {
var topMenu = jQuery("#top-menu"),
offset = 40,
topMenuHeight = topMenu.outerHeight()+offset,
// All list items
menuItems = topMenu.find('a[href*="#"]'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#')),
item = jQuery(id);
//console.log(item)
if (item.length) { return item; }
});
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#'));
offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
jQuery(window).scroll(function(){
// Get container scroll position
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
menuItems.parent().removeClass("active");
if(id){
menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
}
})
})
Basically i replaced
menuItems = topMenu.find("a"),
by
menuItems = topMenu.find('a[href*="#"]'),
To match all links with anchor somewhere, and changed all that what was necessary to make it work with this
See it in action on jsfiddle
Another one line command I used is:
[ -e file ] && rm file
This happened to me just now, after shutting down and restarting the computer. Eventually I realised that the architecture had somehow been changed to ARM from x64.
Since there's no other way to deal with this horrible design, I wrote a generic component that uses the withRouter
HOC approach. The example below is wrapping a button
element, but you can change to any clickable element you need:
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
const NavButton = (props) => (
<Button onClick={() => props.history.push(props.to)}>
{props.children}
</Button>
);
NavButton.propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired
}),
to: PropTypes.string.isRequired
};
export default withRouter(NavButton);
Usage:
<NavButton to="/somewhere">Click me</NavButton>
This is and old question, but now on PHP 7.1 you can define constant visibility.
EXAMPLE
<?php
class Foo {
// As of PHP 7.1.0
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR . PHP_EOL;
echo Foo::BAZ . PHP_EOL;
?>
Output of the above example in PHP 7.1:
bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …
Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.
More info here
You can use setenv.bat or .sh to pass the environment variables to the Tomcat.
Create CATALINA_BASE/bin/setenv.bat or .sh file and put the following line in it, and then start the Tomcat.
On Windows:
set APP_MASTER_PASSWORD=foo
On Unix like systems:
export APP_MASTER_PASSWORD=foo
The VH
unit can be used to fill the background of the viewport, aka the browser window.
(height:100vh;)
html{
height:100%;
}
.body {
background: url(image.jpg) no-repeat center top;
background-size: cover;
height:100vh;
}
works
$('a[href*=#]').each(function () {
$(this).attr('href', $(this).attr('href').replace('#', '#_'));
$(this).on( "click", function() {
var hashname = $(this).attr('href').replace('#_', '');
if($(this).attr('href') == "#_") {
$('html, body').animate({ scrollTop: 0 }, 300);
}
else {
var target = $('a[name="' + hashname + '"], #' + hashname),
targetOffset = target.offset().top;
if(targetOffset >= 1) {
$('html, body').animate({ scrollTop: targetOffset-60 }, 300);
}
}
});
});
In Bash this is easy. Just tie them together with &&
:
command1 && command2 && command3
You can also use the nested if construct:
if command1
then
if command2
then
do_something
else
exit
fi
else
exit
fi
I would like to add the following point.
You can also make it a const &
and const &&
So,
struct s{
void val1() const {
// *this is const here. Hence this function cannot modify any member of *this
}
void val2() const & {
// *this is const& here
}
void val3() const && {
// The object calling this function should be const rvalue only.
}
void val4() && {
// The object calling this function should be rvalue reference only.
}
};
int main(){
s a;
a.val1(); //okay
a.val2(); //okay
// a.val3() not okay, a is not rvalue will be okay if called like
std::move(a).val3(); // okay, move makes it a rvalue
}
Feel free to improve the answer. I am no expert
Shahar's answer was really helpful, but I found it quite tedious to do this all myself, so I made a nifty little Python program:
import re
import urllib2
import string
url1 = raw_input("Please enter a URL from Tunein Radio: ");
open_file = urllib2.urlopen(url1);
raw_file = open_file.read();
API_key = re.findall(r"StreamUrl\":\"(.*?),",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
use_key = urllib2.urlopen(str(API_key[0]));
key_content = use_key.read();
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
total = total + 1
i = 0
print "I found " + str(total) + " streams.";
for element in raw_stream_url:
print "Stream #" + str(i + 1);
print "Stream stats:";
print "Bandwidth: " + str(bandwidth[i]) + " kilobytes per second."
print "Reliability: " + str(reliability[i]) + "%"
print "HasPlaylist: " + str(isPlaylist[i]) + "."
print "Stream codec: " + str(codec[i]) + "."
print "This audio stream is " + tipe[i].lower() + "."
print "Pure streaming URL: " + str(raw_stream_url[i]) + ".";
i = i + 1
raw_input("Press enter to close TMUS.")
It's basically Shahar's solution automated.
The return
statement sets the exit code of the function, much the same as exit
will do for the entire script.
The exit code for the last command is always available in the $?
variable.
function fun1(){
return 34
}
function fun2(){
local res=$(fun1)
echo $? # <-- Always echos 0 since the 'local' command passes.
res=$(fun1)
echo $? #<-- Outputs 34
}
numpy.append
always copies the array before appending the new values. Your code is equivalent to the following:
import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)
Perhaps you mean to do this?
import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])
Alternatively
with Pool() as pool:
pool.map(fits.open, [name + '.fits' for name in datainput])
Note that the answers that suggest using unbind()
are now out of date as that method has been deprecated and will be removed in future versions of jQuery.
As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.
Instead, you should now use off()
:
$(window).off('scroll');
This is a very different style of programming, but I always try to rewrite things that looked like
bar = None
if foo():
bar = "Baz"
if bar is None:
bar = "Quux"
into just:
if foo():
bar = "Baz"
else:
bar = "Quux"
That is to say, I try hard to avoid a situation where some code paths define variables but others don't. In my code, there is never a path which causes an ambiguity of the set of defined variables (In fact, I usually take it a step further and make sure that the types are the same regardless of code path). It may just be a matter of personal taste, but I find this pattern, though a little less obvious when I'm writing it, much easier to understand when I'm later reading it.
recommend using DI approach from other answers instead of this approach
You should be able to use the class directly
new DatePipe().transform(myDate, 'yyyy-MM-dd');
For instance
var raw = new Date(2015, 1, 12);
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
expect(formatted).toEqual('2015-02-12');
Login into your linux. Fire following commands. Be careful, as editing sudoer is a risky proposition.
$ sudo visudo
Once vi editor opens make the following changes:
Comment out Defaults requiretty
# Defaults requiretty
Go to the end of the file and add
jenkins ALL=(ALL) NOPASSWD: ALL
This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.
You may want to add logic to sort your monthly data after it's all been copied
Public Sub MoveData(MonthNumber As Integer, SheetName As String)
Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range
Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
If Format(cell.Value, "MM") = MonthNumber Then
copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
End If
Next cell
End Sub
Sub copyRowTo(rng As Range, ws As Worksheet)
Dim newRange As Range
Set newRange = ws.Range("A1")
If newRange.Offset(1).Value <> "" Then
Set newRange = newRange.End(xlDown).Offset(1)
Else
Set newRange = newRange.Offset(1)
End If
rng.Copy
newRange.PasteSpecial (xlPasteAll)
End Sub
Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/
package com.mkyong.core;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
package com.mkyong.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
function inArray(elem,array)
{
var len = array.length;
for(var i = 0 ; i < len;i++)
{
if(array[i] == elem){return i;}
}
return -1;
}
Returns array index if found, or -1 if not found
In Java version 8+ can (advised to) use java.time library. ISO 8601 sets standard way to write dates: YYYY-MM-DD
and java.time.Instant
uses it, so (for UTC
):
import java.time.Instant;
int myYear = Integer.parseInt(Instant.now().toString().substring(0,4));
P.S. just in case (and shorted for getting String
, not int
), using Calendar
looks better and can be made zone-aware.
The solution involved putting the gtest source directory as a subdirectory of your project. I've included the working CMakeLists.txt below if it is helpful to anyone.
cmake_minimum_required(VERSION 2.6)
project(basic_test)
################################
# GTest
################################
ADD_SUBDIRECTORY (gtest-1.6.0)
enable_testing()
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})
################################
# Unit Tests
################################
# Add test cpp file
add_executable( runUnitTests testgtest.cpp )
# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests gtest gtest_main)
add_test( runUnitTests runUnitTests )
Why not just:
int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
String before = s.substring(0, plusIndex);
// Use before
}
It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:
Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");
If you're going to use split
(either the built-in version or Guava) you don't need to check whether it contains +
first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:
// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];
Note that writing String[] parts
is preferred over String parts[]
- it's much more idiomatic Java code.
I like Guffa's answer and since I can't comment I will provide the answer Udil's question here.
I needed something similar but I wanted certein logic in my token, I wanted to:
Now points 1-3 are fixed length so it was easy, here is my code:
Here is my code to generate the token:
public string GenerateToken(string reason, MyUser user)
{
byte[] _time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] _key = Guid.Parse(user.SecurityStamp).ToByteArray();
byte[] _Id = GetBytes(user.Id.ToString());
byte[] _reason = GetBytes(reason);
byte[] data = new byte[_time.Length + _key.Length + _reason.Length+_Id.Length];
System.Buffer.BlockCopy(_time, 0, data, 0, _time.Length);
System.Buffer.BlockCopy(_key , 0, data, _time.Length, _key.Length);
System.Buffer.BlockCopy(_reason, 0, data, _time.Length + _key.Length, _reason.Length);
System.Buffer.BlockCopy(_Id, 0, data, _time.Length + _key.Length + _reason.Length, _Id.Length);
return Convert.ToBase64String(data.ToArray());
}
Here is my Code to take the generated token string and validate it:
public TokenValidation ValidateToken(string reason, MyUser user, string token)
{
var result = new TokenValidation();
byte[] data = Convert.FromBase64String(token);
byte[] _time = data.Take(8).ToArray();
byte[] _key = data.Skip(8).Take(16).ToArray();
byte[] _reason = data.Skip(24).Take(2).ToArray();
byte[] _Id = data.Skip(26).ToArray();
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(_time, 0));
if (when < DateTime.UtcNow.AddHours(-24))
{
result.Errors.Add( TokenValidationStatus.Expired);
}
Guid gKey = new Guid(_key);
if (gKey.ToString() != user.SecurityStamp)
{
result.Errors.Add(TokenValidationStatus.WrongGuid);
}
if (reason != GetString(_reason))
{
result.Errors.Add(TokenValidationStatus.WrongPurpose);
}
if (user.Id.ToString() != GetString(_Id))
{
result.Errors.Add(TokenValidationStatus.WrongUser);
}
return result;
}
private static string GetString(byte[] reason) => Encoding.ASCII.GetString(reason);
private static byte[] GetBytes(string reason) => Encoding.ASCII.GetBytes(reason);
The TokenValidation class looks like this:
public class TokenValidation
{
public bool Validated { get { return Errors.Count == 0; } }
public readonly List<TokenValidationStatus> Errors = new List<TokenValidationStatus>();
}
public enum TokenValidationStatus
{
Expired,
WrongUser,
WrongPurpose,
WrongGuid
}
Now I have an easy way to validate a token, no Need to Keep it in a list for 24 hours or so. Here is my Good-Case Unit test:
private const string ResetPasswordTokenPurpose = "RP";
private const string ConfirmEmailTokenPurpose = "EC";//change here change bit length for reason section (2 per char)
[TestMethod]
public void GenerateTokenTest()
{
MyUser user = CreateTestUser("name");
user.Id = 123;
user.SecurityStamp = Guid.NewGuid().ToString();
var token = sit.GenerateToken(ConfirmEmailTokenPurpose, user);
var validation = sit.ValidateToken(ConfirmEmailTokenPurpose, user, token);
Assert.IsTrue(validation.Validated,"Token validated for user 123");
}
One can adapt the code for other business cases easely.
Happy Coding
Walter
<div class="equal row-fluid">
<div class="span2"></div>
<div class="span2"></div>
<div class="span2"></div>
<div class="span2"></div>
<div class="span2"></div>
</div>
.equal .span2 {
width: 20%;
}
text doesn't work with len function.
ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For more information, see Using Large-Value Data Types.
CAST(Round(MySum * 20.0 /100, 0) AS INT)
FYI
MySum * 20 /100, I get 11
This is because when all 3 operands are INTs, SQL Server will do perform integer maths, from left to right, truncating all intermediate results.
58 * 20 / 100 => 1160 / 100 => 11 (truncated from 11.6)
Also for the record ROUND(m,n) returns the result to n decimal places, not n significant figures.
Logs are set in your settings.py
file. A new, default project, looks like this:
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
By default, these don't create log files. If you want those, you need to add a filename
parameter to your handlers
'applogfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': os.path.join(DJANGO_ROOT, 'APPNAME.log'),
'maxBytes': 1024*1024*15, # 15MB
'backupCount': 10,
},
This will set up a rotating log that can get 15 MB in size and keep 10 historical versions.
In the loggers
section from above, you need to add applogfile
to the handlers
for your application
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'APPNAME': {
'handlers': ['applogfile',],
'level': 'DEBUG',
},
}
This example will put your logs in your Django root in a file named APPNAME.log
public static final long SECOND_IN_MILLIS = 1000;
public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
You could cast int but I would recommend using long.
text-align: center
will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0;
(you will probably also have to give the span a display: block
property)
If you're using a table view to display Settings and other options (like the built-in Settings app does), then you can set your Table View Content to Static Cells under the Attributes Inspector. Also, to do this, you must embedded your Table View in a UITableViewController instance.
The jQueryUI provides a extension to animate
function that allows you to animate css class.
edit: Example here
There are also methods to add/remove/toggle class which you might also be interested in.
The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:
@echo off
setlocal enabledelayedexpansion enableextensions
set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof
:file_name_from_path <resultVar> <pathVar>
(
set "%~1=%~nx2"
exit /b
)
:eof
endlocal
Now the :file_name_from_path
function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.
Well, for a link, there must be a link tag around. what you can also do is that make a css class for the button and assign that class to the link tag. like,
#btn {_x000D_
background: url(https://image.flaticon.com/icons/png/128/149/149668.png) no-repeat 0 0;_x000D_
display: block;_x000D_
width: 128px;_x000D_
height: 128px;_x000D_
border: none;_x000D_
outline: none;_x000D_
}
_x000D_
<a href="btnlink.html" id="btn"></a>
_x000D_
I was getting the same error on MacOS with sudo and without it.
I have solved it with:
boot2docker start
$(boot2docker shellinit)
P.S.: Thanks to Alan. I found out that this approach is recommended in their official documentation.
P.S.2: Sometimes boot2docker init
can be required before running two commands (thank you Aaron).
Just to point out, HTML5 per se is not "far from ready"; it is actually pretty much finished, "considered by the Working Group to fulfill the relevant requirements of its charter and any accompanying requirements documents." There will be some things to iron out, and the core spec has some accompanying addon bits, but the majority of it is actually ready to use right away, with much of it stable in latest browsers.
Mr. Curious was curious about this as well. In addition to the #>> '{}'
operator, in 9.6+ one can get the value of a jsonb string with the ->>
operator:
select to_jsonb('Some "text"'::TEXT)->>0;
?column?
-------------
Some "text"
(1 row)
If one has a json value, then the solution is to cast into jsonb first:
select to_json('Some "text"'::TEXT)::jsonb->>0;
?column?
-------------
Some "text"
(1 row)
Use an array of valid dates format, check docs:
string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);
if(isValidFormat)
{
string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
// maybe throw an Exception
}
Another way is to handle the Runnable itself:
Runnable r = new Runnable {
public void run() {
if (booleanCancelMember != false) {
//do what you need
}
}
}
One possibility that I haven't seen widely discussed is that there may be a problem resolving the hostname on the host machine itself. If there is no entry for $(hostname) in /etc/hosts, the Oracle listener gets confused and wont come up.
That turned out to be my problem, and adding the hostname and ip address in /etc/hosts resolved the problem.
If you're looking for a Windows GUI, check out DigiCert. I just used this and it was fairly simple.
Under the SSL tab, I first Imported the Certificate. Then once I selected the Certificate I was able to export as a PFX, both with and without a keyfile.
1- Comment out bind 127.0.0.1
2- set requirepass yourpassword
then check if the firewall blocked your port
iptables -L -n
service iptables stop
TL;DR
Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command MySQL got confused.
Examine your command. If you use a programming language to create your command, use
echo
,console.log()
, or its equivalent to show the entire command so you can see it.Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.
Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).
Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.
As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.
Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.
For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):
This sentence contains syntax error a.
Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.
It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.
Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…
MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:
UPDATE my_table WHERE id=101 SET name='foo'
That command yields the following error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1
MySQL is telling us that everything seemed fine up to the word WHERE
, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE
at that point.
Messages that say ...near '' at line...
simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.
Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:
$result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
If you write this this in two lines
$query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
$result = $mysqli->query($query);
then you can add echo $query;
or var_dump($query)
to see that the query actually says
UPDATE userSET name='foo' WHERE id=101
Often you'll see your error immediately and be able to fix it.
MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.
I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE
command. The very first thing on the page is the command's grammar (this is true for every command):
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [
and ]
are optional; vertical bars |
indicate alternatives; and ellipses ...
denote either an omission for brevity, or that the preceding clause may be repeated.
We already know that the parser believed everything in our command was okay prior to the WHERE
keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference
must be followed by the SET
keyword: whereas in our command it was actually followed by the WHERE
keyword. This explains why the parser reports that a problem was encountered at that point.
Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.
I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:
UPDATE my_table SET where='foo'
Again, the parser does not expect to encounter WHERE
at this point and so will raise a similar syntax error—but you hadn't intended for that where
to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.
[ deletia ]The identifier quote character is the backtick (“
`
”):mysql> SELECT * FROM `select` WHERE `select`.id > 100;
If the
ANSI_QUOTES
SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:mysql> CREATE TABLE "test" (col INT); ERROR 1064: You have an error in your SQL syntax... mysql> SET sql_mode='ANSI_QUOTES'; mysql> CREATE TABLE "test" (col INT); Query OK, 0 rows affected (0.00 sec)
Try http://www.jsonschema2pojo.org
Or the jsonschema2pojo plug-in for Maven:
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.0.2</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory>
<targetPackage>com.myproject.jsonschemas</targetPackage>
<sourceType>json</sourceType>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
The <sourceType>json</sourceType>
covers the case where the sources are json (like the OP). If you have actual json schemas, remove this line.
Updated in 2014: Two things have happened since Dec '09 when this question was asked:
The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules
I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.
Hope this helps!
Search for setTextAppearance
or also setTextTypeface
. There is similar question on stackoverflow: How to change a TextView's style at runtime
The best I've seen is Zend Guard.
To run jar, first u have to create
executable jar
then
java -jar xyz.jar
command will work
Use:
myarray.index "valuetoFind"
That will return you the index of the element you want or nil if your array doesn't contain the value.
Not like the @staticmethod
but class variables are static method of class and are shared with all the instances.
Now you can access it like
instance = MyClass()
print(instance.i)
or
print(MyClass.i)
you have to assign the value to these variables
I was trying
class MyClass:
i: str
and assigning the value in one method call, in that case it will not work and will throw an error
i is not attribute of MyClass
I had the same problem when my network config was incorrect and DNS was not resolving. In other words the issue could arise when there is no Network Access.
You cannot use a constant literal for a default parameter for the same reason you cannot use one as a parameter to the function call. Reference values must have an address, constant references values need not (ie they can be r-values or constant literals).
int* foo (int& i )
{
return &i;
}
foo(0); // compiler error.
const int* bar ( const int& i )
{
return &i;
}
bar(0); // ok.
Ensure that you're default value has an address and you're fine.
int null_object = 0;
int Write(int &state = null_object, bool sequence = true)
{
if( &state == &null_object )
{
// called with default paramter
return sequence? 1: rand();
}
else
{
// called with user parameter
state += sequence? 1: rand();
return state;
}
}
I've used this pattern a few times where I had a parameter that could be a variable or null. The regular approach is to have the user pass in a pointer this is case. They pass in a NULL pointer if they don't want you to fill in the value. I like to null object approach. It makes the callers life easier without terribly complicating the callee code.
By using itemStateChanged(ItemListener)
you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
//do something...
} else {//checkbox has been deselected
//do something...
};
}
});
Java Swing itemStateChanged docu should help too. By using isSelected()
method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}
In case anyone needs a (nearly) ready-to-use PHP function, the following is based on this answer:
/**
* Remove a column from a table.
*
* @param string $tableName The table to remove the column from.
* @param string $columnName The column to remove from the table.
*/
public function DropTableColumn($tableName, $columnName)
{
// --
// Determine all columns except the one to remove.
$columnNames = array();
$statement = $pdo->prepare("PRAGMA table_info($tableName);");
$statement->execute(array());
$rows = $statement->fetchAll(PDO::FETCH_OBJ);
$hasColumn = false;
foreach ($rows as $row)
{
if(strtolower($row->name) !== strtolower($columnName))
{
array_push($columnNames, $row->name);
}
else
{
$hasColumn = true;
}
}
// Column does not exist in table, no need to do anything.
if ( !$hasColumn ) return;
// --
// Actually execute the SQL.
$columns = implode('`,`', $columnNames);
$statement = $pdo->exec(
"CREATE TABLE `t1_backup` AS SELECT `$columns` FROM `$tableName`;
DROP TABLE `$tableName`;
ALTER TABLE `t1_backup` RENAME TO `$tableName`;");
}
In contrast to other answers, the SQL used in this approach seems to preserve the data types of the columns, whereas something like the accepted answer seems to result in all columns to be of type TEXT
.
Update 1:
The SQL used has the drawback that autoincrement
columns are not preserved.
I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.
import pandas as pd
import numpy as np
df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])
newdf = df.loc[df['a'].str.contains('foo') == True]
Works with or without .loc
.
I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True
or False
. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.
I found this today, it is from 2003. It finds a process by name, you don't even need the pid.
\#include windows.h
\#include tlhelp32.h
\#include iostream.h
int FIND_PROC_BY_NAME(const char *);
int main(int argc, char *argv[])
{
// Check whether a process is currently running, or not
char szName[100]="notepad.exe"; // Name of process to find
int isRunning;
isRunning=FIND_PROC_BY_NAME(szName);
// Note: isRunning=0 means process not found, =1 means yes, it is found in memor
return isRunning;
}
int FIND_PROC_BY_NAME(const char *szToFind)
// Created: 12/29/2000 (RK)
// Last modified: 6/16/2003 (RK)
// Please report any problems or bugs to [email protected]
// The latest version of this routine can be found at:
// http://www.neurophys.wisc.edu/ravi/software/killproc/
// Check whether the process "szToFind" is currently running in memory
// This works for Win/95/98/ME and also Win/NT/2000/XP
// The process name is case-insensitive, i.e. "notepad.exe" and "NOTEPAD.EXE"
// will both work (for szToFind)
// Return codes are as follows:
// 0 = Process was not found
// 1 = Process was found
// 605 = Unable to search for process
// 606 = Unable to identify system type
// 607 = Unsupported OS
// 632 = Process name is invalid
// Change history:
// 3/10/2002 - Fixed memory leak in some cases (hSnapShot and
// and hSnapShotm were not being closed sometimes)
// 6/13/2003 - Removed iFound (was not being used, as pointed out
// by John Emmas)
{
BOOL bResult,bResultm;
DWORD aiPID[1000],iCb=1000,iNumProc,iV2000=0;
DWORD iCbneeded,i;
char szName[MAX_PATH],szToFindUpper[MAX_PATH];
HANDLE hProc,hSnapShot,hSnapShotm;
OSVERSIONINFO osvi;
HINSTANCE hInstLib;
int iLen,iLenP,indx;
HMODULE hMod;
PROCESSENTRY32 procentry;
MODULEENTRY32 modentry;
// PSAPI Function Pointers.
BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * );
BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *,
DWORD, LPDWORD );
DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE,
LPTSTR, DWORD );
// ToolHelp Function Pointers.
HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32) ;
BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32) ;
// Transfer Process name into "szToFindUpper" and
// convert it to upper case
iLenP=strlen(szToFind);
if(iLenP<1 || iLenP>MAX_PATH) return 632;
for(indx=0;indx<iLenP;indx++)
szToFindUpper[indx]=toupper(szToFind[indx]);
szToFindUpper[iLenP]=0;
// First check what version of Windows we're in
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
bResult=GetVersionEx(&osvi);
if(!bResult) // Unable to identify system version
return 606;
// At Present we only support Win/NT/2000 or Win/9x/ME
if((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) &&
(osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS))
return 607;
if(osvi.dwPlatformId==VER_PLATFORM_WIN32_NT)
{
// Win/NT or 2000 or XP
// Load library and get the procedures explicitly. We do
// this so that we don't have to worry about modules using
// this code failing to load under Windows 95, because
// it can't resolve references to the PSAPI.DLL.
hInstLib = LoadLibraryA("PSAPI.DLL");
if(hInstLib == NULL)
return 605;
// Get procedure addresses.
lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))
GetProcAddress( hInstLib, "EnumProcesses" ) ;
lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *,
DWORD, LPDWORD)) GetProcAddress( hInstLib,
"EnumProcessModules" ) ;
lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE,
LPTSTR, DWORD )) GetProcAddress( hInstLib,
"GetModuleBaseNameA" ) ;
if( lpfEnumProcesses == NULL ||
lpfEnumProcessModules == NULL ||
lpfGetModuleBaseName == NULL)
{
FreeLibrary(hInstLib);
return 605;
}
bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded);
if(!bResult)
{
// Unable to get process list, EnumProcesses failed
FreeLibrary(hInstLib);
return 605;
}
// How many processes are there?
iNumProc=iCbneeded/sizeof(DWORD);
// Get and match the name of each process
for(i=0;i<iNumProc;i++)
{
// Get the (module) name for this process
strcpy(szName,"Unknown");
// First, get a handle to the process
hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,
aiPID[i]);
// Now, get the process name
if(hProc)
{
if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) )
{
iLen=lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH);
}
}
CloseHandle(hProc);
// Match regardless of lower or upper case
if(strcmp(_strupr(szName),szToFindUpper)==0)
{
// Process found
FreeLibrary(hInstLib);
return 1;
}
}
}
if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS)
{
// Win/95 or 98 or ME
hInstLib = LoadLibraryA("Kernel32.DLL");
if( hInstLib == NULL )
return FALSE ;
// Get procedure addresses.
// We are linking to these functions of Kernel32
// explicitly, because otherwise a module using
// this code would fail to load under Windows NT,
// which does not have the Toolhelp32
// functions in the Kernel 32.
lpfCreateToolhelp32Snapshot=
(HANDLE(WINAPI *)(DWORD,DWORD))
GetProcAddress( hInstLib,
"CreateToolhelp32Snapshot" ) ;
lpfProcess32First=
(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
GetProcAddress( hInstLib, "Process32First" ) ;
lpfProcess32Next=
(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
GetProcAddress( hInstLib, "Process32Next" ) ;
lpfModule32First=
(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
GetProcAddress( hInstLib, "Module32First" ) ;
lpfModule32Next=
(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
GetProcAddress( hInstLib, "Module32Next" ) ;
if( lpfProcess32Next == NULL ||
lpfProcess32First == NULL ||
lpfModule32Next == NULL ||
lpfModule32First == NULL ||
lpfCreateToolhelp32Snapshot == NULL )
{
FreeLibrary(hInstLib);
return 605;
}
// The Process32.. and Module32.. routines return names in all uppercase
// Get a handle to a Toolhelp snapshot of all the systems processes.
hSnapShot = lpfCreateToolhelp32Snapshot(
TH32CS_SNAPPROCESS, 0 ) ;
if( hSnapShot == INVALID_HANDLE_VALUE )
{
FreeLibrary(hInstLib);
return 605;
}
// Get the first process' information.
procentry.dwSize = sizeof(PROCESSENTRY32);
bResult=lpfProcess32First(hSnapShot,&procentry);
// While there are processes, keep looping and checking.
while(bResult)
{
// Get a handle to a Toolhelp snapshot of this process.
hSnapShotm = lpfCreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, procentry.th32ProcessID) ;
if( hSnapShotm == INVALID_HANDLE_VALUE )
{
CloseHandle(hSnapShot);
FreeLibrary(hInstLib);
return 605;
}
// Get the module list for this process
modentry.dwSize=sizeof(MODULEENTRY32);
bResultm=lpfModule32First(hSnapShotm,&modentry);
// While there are modules, keep looping and checking
while(bResultm)
{
if(strcmp(modentry.szModule,szToFindUpper)==0)
{
// Process found
CloseHandle(hSnapShotm);
CloseHandle(hSnapShot);
FreeLibrary(hInstLib);
return 1;
}
else
{ // Look for next modules for this process
modentry.dwSize=sizeof(MODULEENTRY32);
bResultm=lpfModule32Next(hSnapShotm,&modentry);
}
}
//Keep looking
CloseHandle(hSnapShotm);
procentry.dwSize = sizeof(PROCESSENTRY32);
bResult = lpfProcess32Next(hSnapShot,&procentry);
}
CloseHandle(hSnapShot);
}
FreeLibrary(hInstLib);
return 0;
}
Finally, Anaconda3-2020.07 is out and its core is Python 3.8!
You can now download Anaconda packed with Python 3.8 goodness at:
From the documentation:
You cannot use ORDER BY or LIMIT in a multiple-table DELETE.
Use function for multilevel loops - this is good way:
function find_dup () {
for (;;) {
for(;;) {
if (done) return;
}
}
}
you can use plt.matshow()
instead of plt.imshow()
or you can use seaborn module's heatmap
(see documentation) to plot the confusion matrix
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3],
[3,31,0,0,0,0,0,0,0,0,0],
[0,4,41,0,0,0,0,0,0,0,1],
[0,1,0,30,0,6,0,0,0,0,1],
[0,0,0,0,38,10,0,0,0,0,0],
[0,0,0,3,1,39,0,0,0,0,4],
[0,2,2,0,4,1,31,0,0,0,2],
[0,1,0,0,0,0,0,36,0,2,0],
[0,0,0,0,0,0,1,5,37,5,1],
[3,0,0,0,0,0,0,0,0,39,0],
[0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)
I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:
int num = 6;
num.ToString().ToCharArray()[0];
I had loads of trouble with this too. I have data and labels in separate arrays then I reinitialise the chart data. I added the line.destroy(); as suggested above which has done the trick
var ctx = document.getElementById("canvas").getContext("2d");_x000D_
if(window.myLine){_x000D_
window.myLine.destroy();_x000D_
}_x000D_
window.myLine = new Chart(ctx).Line(lineChartData, {_x000D_
etc_x000D_
etc
_x000D_
The parent of the row is not the object you think, this is what I understand from the error.
Try detecting the parent of the row first, then you can be sure what to write into getElementById
part of the parent.
I know this is an old question, but it seems to me that none of these answers seem to answer the question being asked so hopefully this will help someone in the future.
Yes you can always show 2 decimal places, but unfortunately it can't be done with the element attributes alone, you have to use JavaScript.
I should point out this isn't ideal for large numbers as it will always force the trailing zeros, so the user will have to move the cursor back instead of deleting characters to set a value greater than 9.99
//Use keyup to capture user input & mouse up to catch when user is changing the value with the arrows_x000D_
$('.trailing-decimal-input').on('keyup mouseup', function (e) {_x000D_
_x000D_
// on keyup check for backspace & delete, to allow user to clear the input as required_x000D_
var key = e.keyCode || e.charCode;_x000D_
if (key == 8 || key == 46) {_x000D_
return false;_x000D_
};_x000D_
_x000D_
// get the current input value_x000D_
let correctValue = $(this).val().toString();_x000D_
_x000D_
//if there is no decimal places add trailing zeros_x000D_
if (correctValue.indexOf('.') === -1) {_x000D_
correctValue += '.00';_x000D_
}_x000D_
_x000D_
else {_x000D_
_x000D_
//if there is only one number after the decimal add a trailing zero_x000D_
if (correctValue.toString().split(".")[1].length === 1) {_x000D_
correctValue += '0'_x000D_
}_x000D_
_x000D_
//if there is more than 2 decimal places round backdown to 2_x000D_
if (correctValue.toString().split(".")[1].length > 2) {_x000D_
correctValue = parseFloat($(this).val()).toFixed(2).toString();_x000D_
}_x000D_
}_x000D_
_x000D_
//update the value of the input with our conditions_x000D_
$(this).val(correctValue);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="my-number-input" class="form-control trailing-decimal-input" type="number" min="0.01" step="0.01" value="0.00" />
_x000D_
Target= "_blank"
This does it in html, give it a try in C#
Another interesting usecase for split in Hive is when, for example, a column ipname
in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:
SELECT split(ipname,'[\.]')[0] FROM tablename;
You can do it manually, by comparing with greater than or equal and less than or equal.
select * from table_name where created_at_column >= lower_date and created_at_column <= upper_date;
In our example, we need to retrieve data from a particular day to day. We will compare from the beginning of the day to the latest second in another day.
select * from table_name where created_at_column >= '2018-09-01 00:00:00' and created_at_column <= '2018-09-05 23:59:59';
Links and inputs are very different things, used for very different purposes. Looks to me like you need a button for the cancel:
<button>Cancel</button>
Or maybe an input:
<input type="button" value="Cancel"/>
In my case it was simply an error in the web.config.
I had:
<endpoint address="http://localhost/WebService/WebOnlineService.asmx"
It should have been:
<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"
The port number (:10593) was missing from the address.
First, disabling the index during the deletion would be helpful.
Try with a MERGE INTO statement :
1) create a temp table with IDs and an additional column from TABLE1 and test with the following
MERGE INTO table1 src
USING (SELECT id,col1
FROM test_merge_delete) tgt
ON (src.id = tgt.id)
WHEN MATCHED THEN
UPDATE
SET src.col1 = tgt.col1
DELETE
WHERE src.id = tgt.id
The line should read either:
0 0-23/2 * * * /home/username/test.sh
or
0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh
I had the same problem. You can list the regex matches in a new tab, every match in new line in PSPad Editor, which is very similar as Notepad++.
Hit Ctrl + F to search, check the regexp opion, put the regexp and click on List.
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.