Yes, there's a way to do this without the plugin! But it is not as clean and elegant as using the mentioned plugin. Here it is.
Assuming it's Rails 3 (I don't know if it's different in previous versions),
keep this in your model:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
and in the view, instead of leaving
@instance.errors.full_messages
as it would be when we use the scaffold generator, put:
@instance.errors.first[1]
And you will get just the message you specified in the model, without the attribute name.
Explanation:
#returns an hash of messages, one element foreach field error, in this particular case would be just one element in the hash:
@instance.errors # => {:song_rep_xyz=>"can't be empty"}
#this returns the first element of the hash as an array like [:key,"value"]
@instance.errors.first # => [:song_rep_xyz, "can't be empty"]
#by doing the following, you are telling ruby to take just the second element of that array, which is the message.
@instance.errors.first[1]
So far we are just displaying only one message, always for the first error. If you wanna display all errors you can loop in the hash and show the values.
Hope that helped.
Use scipy's Rotation.from_rotvec()
. The argument is the rotation vector (a unit vector) multiplied by the rotation angle in rads.
from scipy.spatial.transform import Rotation
from numpy.linalg import norm
v = [3, 5, 0]
axis = [4, 4, 1]
theta = 1.2
axis = axis / norm(axis) # normalize the rotation vector first
rot = Rotation.from_rotvec(theta * axis)
new_v = rot.apply(v)
print(new_v) # results in [2.74911638 4.77180932 1.91629719]
There are several more ways to use Rotation
based on what data you have about the rotation:
from_quat
Initialized from quaternions.
from_dcm
Initialized from direction cosine matrices.
from_euler
Initialized from Euler angles.
Off-topic note: One line code is not necessarily better code as implied by some users.
Just use the ShapeableImageView
provided by the Material Components Library.
Somethig like:
<com.google.android.material.imageview.ShapeableImageView
app:shapeAppearanceOverlay="@style/roundedImageViewRounded"
app:strokeColor="@color/....."
app:strokeWidth="1dp"
...
/>
with:
<style name="roundedImageViewRounded">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>
Note: it requires at least the version 1.2.0-alpha03
.
There's better support for this now through conda-env
. You can, for example, now do:
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"
It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml
file.
If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml
), then run the command: conda env update -f environment.yml
.
It's more likely that you would want to create a new environment:
conda env create -f environment.yml
(changed as supposed in the comments)
Boost has something to help: the Boost.Iterator library.
More precisely this page: boost::iterator_adaptor.
What's very interesting is the Tutorial Example which shows a complete implementation, from scratch, for a custom type.
template <class Value> class node_iter : public boost::iterator_adaptor< node_iter<Value> // Derived , Value* // Base , boost::use_default // Value , boost::forward_traversal_tag // CategoryOrTraversal > { private: struct enabler {}; // a private type avoids misuse public: node_iter() : node_iter::iterator_adaptor_(0) {} explicit node_iter(Value* p) : node_iter::iterator_adaptor_(p) {} // iterator convertible to const_iterator, not vice-versa template <class OtherValue> node_iter( node_iter<OtherValue> const& other , typename boost::enable_if< boost::is_convertible<OtherValue*,Value*> , enabler >::type = enabler() ) : node_iter::iterator_adaptor_(other.base()) {} private: friend class boost::iterator_core_access; void increment() { this->base_reference() = this->base()->next(); } };
The main point, as has been cited already, is to use a single template implementation and typedef
it.
sed "s/^[ \t]*//" -i youfile
Warning: this will overwrite the original file.
What about the HelpViewerKeywordIndex... helps (a bit) with what is as I see it 2010's greatest flaw, the new help viewer.
cd /the/lib/dir/of/your/perl/installation
perldoc $(find . -name perllocal.pod)
Windows users just do a Windows Explorer search to find it.
Ubuntu 18.04 LTS
These are the steps which worked for me. Many, many thanks to William Desportes for providing the automatic updates on their Ubuntu PPA.
Step 1 (from William Desportes post)
$ sudo add-apt-repository ppa:phpmyadmin/ppa
Step 2
$ sudo apt-get --with-new-pkgs upgrade
Step 3
$ sudo service mysql restart
If you have issues restarting mysql, you can also restart with the following sequence
$ sudo service mysql stop;
$ sudo service mysql start;
It depends on what exactly you want to accomplish. Let's assume you have this structure:
<p style="width:400px;">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet.
</p>
If you want the space between the single lines to be bigger, you should increase
line-height
If you want the space at the end to be bigger, you should increase
margin-bottom
If you want the space at the end to be bigger, but have the background fill the space (or the border around the space) use
padding-bottom
Of course, there are also the corresponding values for space on the top:
padding-top
margin-top
Some examples:
<p style="line-height: 30px; width: 300px; border: 1px solid black;">
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
</p>
<p style="margin-bottom: 30px; width: 300px; border: 1px solid black;">
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
</p>
<p style="padding-bottom: 30px; width: 300px; border: 1px solid black;">
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
</p>
here you can see this code in action: http://jsfiddle.net/ramsesoriginal/H7qxd/
Of course you should put your styles in a separate stylesheet, the inline code was just to show the effect.
here you have a little schematic demonstration of what which value affects:
line-height
content +
| padding-bottom
<----------------+ +
content | border-bottom
| +
| |
+-------------+<------------------+ | margin-bottom
| +
+===================+ <-------------------+ |
|
+-------------------------+ <------------------------+
\bdbo\..*fn
I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform
(although I only knew car
and Platform
at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.
Here's the regex I used to find it:
\bcar\..*Platform
var tasks = [];_x000D_
var descs = [];_x000D_
_x000D_
// Get the modal_x000D_
var modal = document.getElementById('myModal');_x000D_
_x000D_
// Get the button that opens the modal_x000D_
var btn = document.getElementById("myBtn");_x000D_
_x000D_
// Get the <span> element that closes the modal_x000D_
var span = document.getElementsByClassName("close")[0];_x000D_
_x000D_
// When the user clicks the button, open the modal _x000D_
btn.onclick = function() {_x000D_
modal.style.display = "block";_x000D_
}_x000D_
_x000D_
// When the user clicks on <span> (x), close the modal_x000D_
span.onclick = function() {_x000D_
modal.style.display = "none";_x000D_
}_x000D_
_x000D_
// When the user clicks anywhere outside of the modal, close it_x000D_
window.onclick = function(event) {_x000D_
if (event.target == modal) {_x000D_
modal.style.display = "none";_x000D_
}_x000D_
}_x000D_
var rowCount = 1;_x000D_
_x000D_
function addTasks() {_x000D_
var temp = 'style .fa fa-trash';_x000D_
tasks.push(document.getElementById("taskname").value);_x000D_
descs.push(document.getElementById("taskdesc").value);_x000D_
var table = document.getElementById("tasksTable");_x000D_
var row = table.insertRow(rowCount);_x000D_
var cell1 = row.insertCell(0);_x000D_
var cell2 = row.insertCell(1);_x000D_
var cell3 = row.insertCell(2);_x000D_
var cell4 = row.insertCell(3);_x000D_
cell1.innerHTML = tasks[rowCount - 1];_x000D_
cell2.innerHTML = descs[rowCount - 1];_x000D_
cell3.innerHTML = getDate();_x000D_
cell4.innerHTML = '<td class="fa fa-trash"></td>';_x000D_
rowCount++;_x000D_
modal.style.display = "none";_x000D_
}_x000D_
_x000D_
_x000D_
function getDate() {_x000D_
var today = new Date();_x000D_
var dd = today.getDate();_x000D_
var mm = today.getMonth() + 1; //January is 0!_x000D_
_x000D_
var yyyy = today.getFullYear();_x000D_
_x000D_
if (dd < 10) {_x000D_
dd = '0' + dd;_x000D_
}_x000D_
if (mm < 10) {_x000D_
mm = '0' + mm;_x000D_
}_x000D_
var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);_x000D_
return today;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<!-- Trigger/Open The Modal -->_x000D_
<div style="background-color:#0F0F8C ;height:45px">_x000D_
<h2 style="color: white">LOGO</h2>_x000D_
</div>_x000D_
<div>_x000D_
<button id="myBtn"> + Add Task  </button>_x000D_
</div>_x000D_
<div>_x000D_
<table id="tasksTable">_x000D_
<thead>_x000D_
<tr style="background-color:rgba(201, 196, 196, 0.86)">_x000D_
<th style="width: 150px;">Name</th>_x000D_
<th style="width: 250px;">Desc</th>_x000D_
<th style="width: 120px">Date</th>_x000D_
<th style="width: 120px class=fa fa-trash"></th>_x000D_
</tr>_x000D_
_x000D_
</thead>_x000D_
<tbody></tbody>_x000D_
</table>_x000D_
</div>_x000D_
<!-- The Modal -->_x000D_
<div id="myModal" class="modal">_x000D_
_x000D_
<!-- Modal content -->_x000D_
<div class="modal-content">_x000D_
_x000D_
<div class="modal-header">_x000D_
_x000D_
<span class="close">×</span>_x000D_
<h3> Add Task</h3>_x000D_
</div>_x000D_
_x000D_
<div class="modal-body">_x000D_
<table style="padding: 28px 50px">_x000D_
<tr>_x000D_
<td style="width:150px">Name:</td>_x000D_
<td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Desc:_x000D_
</td>_x000D_
<td>_x000D_
<textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="modal-footer">_x000D_
<button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>_x000D_
<br>_x000D_
<br>_x000D_
<br>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DATAGRIDVIEW_TO_EXCEL((DataGridView1)) ' PARAMETER: YOUR DATAGRIDVIEW
End Sub
Private Sub DATAGRIDVIEW_TO_EXCEL(ByVal DGV As DataGridView)
Try
Dim DTB = New DataTable, RWS As Integer, CLS As Integer
For CLS = 0 To DGV.ColumnCount - 1 ' COLUMNS OF DTB
DTB.Columns.Add(DGV.Columns(CLS).Name.ToString)
Next
Dim DRW As DataRow
For RWS = 0 To DGV.Rows.Count - 1 ' FILL DTB WITH DATAGRIDVIEW
DRW = DTB.NewRow
For CLS = 0 To DGV.ColumnCount - 1
Try
DRW(DTB.Columns(CLS).ColumnName.ToString) = DGV.Rows(RWS).Cells(CLS).Value.ToString
Catch ex As Exception
End Try
Next
DTB.Rows.Add(DRW)
Next
DTB.AcceptChanges()
Dim DST As New DataSet
DST.Tables.Add(DTB)
Dim FLE As String = "" ' PATH AND FILE NAME WHERE THE XML WIL BE CREATED (EXEMPLE: C:\REPS\XML.xml)
DTB.WriteXml(FLE)
Dim EXL As String = "" ' PATH OF/ EXCEL.EXE IN YOUR MICROSOFT OFFICE
Shell(Chr(34) & EXL & Chr(34) & " " & Chr(34) & FLE & Chr(34), vbNormalFocus) ' OPEN XML WITH EXCEL
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Try this,
1. If you want to skip a particular iteration, use continue.
2. If you want to break out of the immediate loop use break
3 If there are 2 loop, outer and inner.... and you want to break out of both the loop from
the inner loop, use break with label.
eg:
continue
for(int i=0 ; i<5 ; i++){
if (i==2){
continue;
}
}
eg:
break
for(int i=0 ; i<5 ; i++){
if (i==2){
break;
}
}
eg:
break with label
lab1: for(int j=0 ; j<5 ; j++){
for(int i=0 ; i<5 ; i++){
if (i==2){
break lab1;
}
}
}
No there's not and developers still don't know why google doesn't pay attention to this request!
As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!
Below code gives a basic idea. This is not best solution though.
public static String splitJoin(String sourceStr, String delim,boolean trim,boolean ignoreEmpty){
return join(Arrays.asList(sourceStr.split(delim)), delim, ignoreEmpty);
}
public static String join(List<?> list, String delim, boolean ignoreEmpty) {
int len = list.size();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(list.get(0).toString());
for (int i = 1; i < len; i++) {
if (ignoreEmpty && !StringUtils.isBlank(list.get(i).toString())) {
sb.append(delim);
sb.append(list.get(i).toString().trim());
}
}
return sb.toString();
}
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
DO $$
DECLARE tableId integer;
BEGIN
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id INTO tableId;
INSERT INTO Table2 (val) VALUES (tableId);
END $$;
Tested with psql (10.3, server 9.6.8)
Try this: http://jsbin.com/axaler/3/edit
$(function(){
$(window).scroll(function(){
var aTop = $('.ad').height();
if($(this).scrollTop()>=aTop){
alert('header just passed.');
// instead of alert you can use to show your ad
// something like $('#footAd').slideup();
}
});
});
How about an extension method that doesn't use regex.
If you do stick to one of the Regex options at least use RegexOptions.Compiled
in the static variable.
public static string ToDigitsOnly(this string input)
{
return new String(input.Where(char.IsDigit).ToArray());
}
This builds on Usman Zafar's answer converted to a method group.
# -*- coding: utf-8 -*-
import json
# Make it work for Python 2+3 and with Unicode
import io
try:
to_unicode = unicode
except NameError:
to_unicode = str
# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],
'a string': 'bla',
'another dict': {'foo': 'bar',
'key': 'value',
'the answer': 42}}
# Write JSON file
with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
# Read JSON file
with open('data.json') as data_file:
data_loaded = json.load(data_file)
print(data == data_loaded)
Explanation of the parameters of json.dump
:
indent
: Use 4 spaces to indent each entry, e.g. when a new dict is started (otherwise all will be in one line),sort_keys
: sort the keys of dictionaries. This is useful if you want to compare json files with a diff tool / put them under version control.separators
: To prevent Python from adding trailing whitespacesHave a look at my utility package mpu
for a super simple and easy to remember one:
import mpu.io
data = mpu.io.read('example.json')
mpu.io.write('example.json', data)
{
"a list":[
1,
42,
3.141,
1337,
"help",
"€"
],
"a string":"bla",
"another dict":{
"foo":"bar",
"key":"value",
"the answer":42
}
}
.json
For your application, the following might be important:
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
I just ran into this problem. For me the issue was with:
readfile("$archive_file_name");
It was resulting in a out of memory error.
Allowed memory size of 134217728 bytes exhausted (tried to allocate 292982784 bytes)
I was able to correct the problem by replacing readfile() with the following:
$handle = fopen($zipPath, "rb");
while (!feof($handle)){
echo fread($handle, 8192);
}
fclose($handle);
Not sure if this is your same issue or not seeing that your file is only 1.2 MB. Maybe this will help someone else with a similar problem.
I found this question because having trouble with configparser.ConfigParser().read(fp)
when opening files with UTF8 BOM header.
For those who are looking for a solution to remove the header so that ConfigPhaser could open the config file instead of reporting an error of:
File contains no section headers
, please open the file like the following:
configparser.ConfigParser().read(config_file_path, encoding="utf-8-sig")
This could save you tons of effort by making the remove of the BOM header of the file unnecessary.
(I know this sounds unrelated, but hopefully this could help people struggling like me.)
It may be useful to you to simply increase the number of results that get displayed
In the mongo shell >
DBQuery.shellBatchSize = 3000
and then you can select all the results out of the terminal in one go and paste into a text file.
It is what I am going to do :)
Using Postman for Chrome, selecting CODE you get this... And works
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
CURLOPT_RETURNTRANSFER => true,_x000D_
CURLOPT_ENCODING => "",_x000D_
CURLOPT_MAXREDIRS => 10,_x000D_
CURLOPT_TIMEOUT => 30,_x000D_
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
CURLOPT_POSTFIELDS => "{\n \"customer\" : \"con\",\n \"customerID\" : \"5108\",\n \"customerEmail\" : \"[email protected]\",\n \"Phone\" : \"34600000000\",\n \"Active\" : false,\n \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
CURLOPT_HTTPHEADER => array(_x000D_
"cache-control: no-cache",_x000D_
"content-type: application/json",_x000D_
"x-api-key: whateveriyouneedinyourheader"_x000D_
),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply nothing to run.
The project is most likely generated via CMAKE and included in your Visual Studio solution. Set any of the projects that do generate a .exe as the startup project (by right-clicking on the project and selecting "set as startup project") and you will most likely will be able to start those from within Visual Studio.
To answer your question. I would say it's fairly common for applications to replace spaces in values that will be used in URLs. The reason for this is ussually to avoid the more difficult to read percent (URI) encoding that occurs.
Check out this wikipedia article about Percent-encoding.
The problem is the way you are using it in code. Just try the below code
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource =
new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
this.Background = myBrush;
}
}
You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx
PHP8: (latest version)
sudo apt-get install php8.0-xml
PHP7:
sudo apt-get install php7.1-xml
You can also do:
sudo apt-get install php-dom
and apt-get
will show you where it is.
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
I think it's possible in Java 9:
animalMap.entrySet().stream()
.forEach(
pair -> Optional.ofNullable(pair.getValue())
.ifPresentOrElse(v -> myMap.put(pair.getKey(), v), v -> myList.add(pair.getKey())))
);
Need the ifPresentOrElse for it to work though. (I think a for loop looks better.)
Create Procedure [dbo].[test]
@Name varchar(100),
@ID int Output
As
Begin
SELECT @ID = UserID from tbl_UserMaster where Name = @Name
Return;
END
Declare @ID int
EXECUTE [dbo].[test] 'Abhishek',@ID OUTPUT
PRINT @ID
In C++ using the regex library
The answer would go about like this:
[0-9]?([0-9]*[.])?[0-9]+
Notice that I don't take the sign symbol, if you wanted it with the sign symbol it would go about this:
[+-]?([0-9]*[.])?[0-9]+
This also separates a regular number or a decimal number.
using https://bitbucket.org/YYYY/XX.git
you shoud delete username@
#include<stdio.h>
#include<string.h>
#define filename "somefile.txt"
int main()
{
FILE *fp;
int count[26] = {0}, i, c;
char ch;
char alpha[27] = "abcdefghijklmnopqrstuwxyz";
fp = fopen(filename,"r");
if(fp == NULL)
printf("file not found\n");
while( (ch = fgetc(fp)) != EOF) {
c = 0;
while(alpha[c] != '\0') {
if(alpha[c] == ch) {
count[c]++;
}
c++;
}
}
for(i = 0; i<26;i++) {
printf("character %c occured %d number of times\n",alpha[i], count[i]);
}
return 0;
}
The following works for me and tested on Ubuntu 14.04. It is a one liner that does not require any user input.
sudo useradd -p $(openssl passwd -1 $PASS) $USERNAME
Taken from @Tralemonkey
Somehow all these solutions didn't work for me. There is clearly an IE bug in flex-direction:column
.
I only got it working after removing flex-direction
:
flex-wrap: wrap;
align-items: center;
align-content: center;
3 steps:
Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);
Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;
Use the code to download stream:
URL u = null;
InputStream is = null;
try {
u = new URL(url);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
int size = huc.getContentLength();
if(huc != null) {
String fileName = "FILE.mp4";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len1 = 0;
if(is != null) {
while ((len1 = is.read(buffer)) > 0) {
fos.write(buffer,0, len1);
}
}
if(fos != null) {
fos.close();
}
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null) {
is.close();
}
} catch (IOException ioe) {
// just going to ignore this one
}
}
That's all, most of stuff you'll find on the web!!!
Apart from the similarities i.e. Task.Run() being a shorthand for Task.Factory.StartNew(), there is a minute difference between their behaviour in case of sync and async delegates.
Suppose there are following two methods:
public async Task<int> GetIntAsync()
{
return Task.FromResult(1);
}
public int GetInt()
{
return 1;
}
Now consider the following code.
var sync1 = Task.Run(() => GetInt());
var sync2 = Task.Factory.StartNew(() => GetInt());
Here both sync1 and sync2 are of type Task<int>
However, difference comes in case of async methods.
var async1 = Task.Run(() => GetIntAsync());
var async2 = Task.Factory.StartNew(() => GetIntAsync());
In this scenario, async1 is of type Task<int>
, however async2 is of type Task<Task<int>>
Test this
var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
Another method in one line (substitute your actual path/ports if needed).
Example: Assume a generic registry:2.0 start up, the running registry container has a log file that holds images and tag names. I extrapolate the data like this:
grep -r -o "vars\.name=.* vars.reference=.*" /var/lib/docker/containers/* | cut -c 167-225 | sed 's/ver.*$//' | sed 's/vars\.name=//' | sed 's/ vars\.reference=/:/' | sort -u
You may need to tweak the cut values to get the output desired.
When your program has more open descriptors than the open files ulimit (ulimit -a will list this), the kernel will refuse to open any more file descriptors. Make sure you don't have any file descriptor leaks - for example, by running it for a while, then stopping and seeing if any extra fds are still open when it's idle - and if it's still a problem, change the nofile ulimit for your user in /etc/security/limits.conf
The java.sql.Timestamp class has no format. Its toString method generates a String with a format.
Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.
First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.
Instant instant = mySqlDate.toInstant() ;
Lose the fraction of a second you don't want.
instant = instant.truncatedTo( ChronoUnit.Seconds );
Assign the time zone to adjust from UTC used by Instant.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generate a String close to your desired output. Replace its T
in the middle with a SPACE.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
To add to Preston's answer, here's the complete list of the HttpContent
derived classes available in the standard library:
Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/
There's also a supposed ObjectContent
but I was unable to find it in ASP.NET Core
.
Of course, you could skip the whole HttpContent
thing all together with Microsoft.AspNet.WebApi.Client
extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:
var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
Title = "New Article Title",
Body = "New Article Body"
});
you can do try lodash
Example code for json object:
var user = {'user':'barney','age':36};
user["newKey"] = true;
console.log(user);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
for json array elements
Example code:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
users.map(i=>{i["newKey"] = true});
console.log(users);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
try
{
..
..
..
}
catch(Exception ex)
{
..
..
..
}
the Exception ex means all the exceptions.
If you don't want to use a DateTime or TimeSpan, and just want to store the time of day, you could just store the seconds since midnight in an Int32, or (if you don't even want seconds) the minutes since midnight would fit into an Int16. It would be trivial to write the few methods required to access the Hour, Minute and Second from such a value.
The only reason I can think of to avoid DateTime/TimeSpan would be if the size of the structure is critical.
(Of course, if you use a simple scheme like the above wrapped in a class, then it would also be trivial to replace the storage with a TimeSpan in future if you suddenly realise that would give you an advantage)
if( $("#field > div.field-item").text().indexOf('someText') >= 0)
Some browsers will include whitespace, others won't. >=
is appropriate here. Otherwise equality is double equals ==
One of my favorite lib: Apache Commons.
The EnumUtils can do that easily.
Following an example to validate an Enum with that library:
public enum MyEnum {
DIV("div"), DEPT("dept"), CLASS("class");
private final String val;
MyEnum(String val) {
this.val = val;
}
public String getVal() {
return val;
}
}
MyEnum strTypeEnum = null;
// test if String str is compatible with the enum
// e.g. if you pass str = "div", it will return false. If you pass "DIV", it will return true.
if( EnumUtils.isValidEnum(MyEnum.class, str) ){
strTypeEnum = MyEnum.valueOf(str);
}
Peachpie
https://github.com/iolevel/peachpie
Peachpie is PHP 7 compiler based on Roslyn by Microsoft and drawing from popular Phalanger. It allows PHP to be executed within the .NET/.NETCore by compiling the PHP code to pure MSIL.
Phalanger
http://wiki.php-compiler.net/Phalanger_Wiki
https://github.com/devsense/phalanger
Phalanger is a project which was started at Charles University in Prague and was supported by Microsoft. It compiles source code written in the PHP scripting language into CIL (Common Intermediate Language) byte-code. It handles the beginning of a compiling process which is completed by the JIT compiler component of the .NET Framework. It does not address native code generation nor optimization. Its purpose is to compile PHP scripts into .NET assemblies, logical units containing CIL code and meta-data.
Bambalam
https://github.com/xZero707/Bamcompile/
Bambalam PHP EXE Compiler/Embedder is a free command line tool to convert PHP applications to standalone Windows .exe applications. The exe files produced are totally standalone, no need for php dlls etc. The php code is encoded using the Turck MMCache Encode library so it's a perfect solution if you want to distribute your application while protecting your source code. The converter is also suitable for producing .exe files for windowed PHP applications (created using for example the WinBinder library). It's also good for making stand-alone PHP Socket servers/clients (using the php_sockets.dll extension). It's NOT really a compiler in the sense that it doesn't produce native machine code from PHP sources, but it works!
ZZEE PHPExe
ZZEE PHPExe compiles PHP, HTML, Javascript, Flash and other web files into Windows GUI exes. You can rapidly develop Windows GUI applications by employing the familiar PHP web paradigm. You can use the same code for online and Windows applications with little or no modification. It is a Commercial product.
phc-win
http://wiki.swiftlytilting.com/Phc-win
The PHP extension bcompiler is used to compile PHP script code into PHP bytecode. This bytecode can be included just like any php file as long as the bcompiler extension is loaded. Once all the bytecode files have been created, a modified Embeder is used to pack all of the project files into the program exe.
Requires
ExeOutput
Commercial
WinBinder
WinBinder is an open source extension to PHP, the script programming language. It allows PHP programmers to easily build native Windows applications, producing quick and rewarding results with minimum effort. Even short scripts with a few dozen lines can generate a useful program, thanks to the power and flexibility of PHP.
PHPDesktop
https://github.com/cztomczak/phpdesktop
PHP Desktop is an open source project founded by Czarek Tomczak in 2012 to provide a way for developing native desktop applications using web technologies such as PHP, HTML5, JavaScript & SQLite. This project is more than just a PHP to EXE compiler, it embeds a web-browser (Internet Explorer or Chrome embedded), a Mongoose web-server and a PHP interpreter. The development workflow you are used to remains the same, the step of turning an existing website into a desktop application is basically a matter of copying it to "www/" directory. Using SQLite database is optional, you could embed mysql/postgresql database in application's installer.
PHP Nightrain
https://github.com/kjellberg/nightrain
Using PHP Nightrain you will be able to deploy and run HTML, CSS, JavaScript and PHP web applications as a native desktop application on Windows, Mac and the Linux operating systems. Popular PHP Frameworks (e.g. CakePHP, Laravel, Drupal, etc…) are well supported!
phc-win "fork"
https://github.com/RDashINC/phc-win
A more-or-less forked version of phc-win, it uses the same techniques as phc-win but supports almost all modern PHP versions. (5.3, 5.4, 5.5, 5.6, etc) It also can use Enigma VB to combine the php5ts.dll with your exe, aswell as UPX compress it. Lastly, it has win32std and winbinder compilied statically into PHP.
EDIT
Another option is to use
http://www.appcelerator.com/products/titanium-cross-platform-application-development/
an online compiler that can build executables for a number of different platforms, from a number of different languages including PHP
TideSDK
TideSDK is actually the renamed Titanium Desktop project. Titanium remained focused on mobile, and abandoned the desktop version, which was taken over by some people who have open sourced it and dubbed it TideSDK.
Generally, TideSDK uses HTML, CSS and JS to render applications, but it supports scripted languages like PHP, as a plug-in module, as well as other scripting languages like Python and Ruby.
Just add [mysqld]
as first line in the /etc/mysql/my.cnf
file.
[mysqld]
default-time-zone = "+08:00"
Afterwards, remember to restart your MySQL Service.
sudo mysqld stop
sudo mysqld start
The plugin developed by @dubrox is very lightweight and works almost identical to jQuery UI. My requirement was to have the ability to restrict the number of dates selected.
Intuitively, the maxPicks
property seems to have been provided for this purpose, but it doesn't work unfortunately.
For those of you looking for this fix, here it is:
First up, you need to patch jquery.ui.multidatespicker.js
. I have submitted a pull request on github. You can use that until dubrox merges it with the master or comes up with a fix of his own.
Usage is really straightforward. The below code causes the date picker to not select any dates once the specified number of dates (maxPicks
) has been already selected. If you unselect any previously selected date, it will let you select again until you reach the limit once again.
$("#mydatefield").multiDatesPicker({maxPicks: 3});
If a caching system correctly implements no-store, then you wouldn't need no-cache. But not all do. Additionally, some browsers implement no-cache like it was no-store. Thus, while not strictly required, it's probably safest to include both.
If you wanted to use this without completely destroying your SVN repository, you can tell 'find' to ignore all hidden files by doing:
find . \( ! -regex '.*/\..*' \) -type f -print0 | xargs -0 sed -i 's/subdomainA.example.com/subdomainB.example.com/g'
There is also rather dirty trick for this:
virtual const ULONG Write(ULONG &&State = 0, bool sequence = true);
In this case you have to call it with std::move
:
ULONG val = 0;
Write(std::move(val));
It is only some funny workaround, I totally do not recommend it using in real code!
If you just do gcc program.c -o program -mno-cygwin it will compile just fine and you won't need to add cygwin1.dll to your path and you can just go ahead and distribute your executable to a computer which doesn't have cygwin installed and it will still run. Hope this helps
Well, you could swap your 0
's for NA
and then use one of those solutions, but for sake of a difference, you could notice that a number will only have a finite logarithm if it is greater than 0
, so that rowSums
of the log
will only be finite if there are no zeros in a row.
dfr[is.finite(rowSums(log(dfr[-1]))),]
I have that kind of spring setup working
an abstract class with an autowired field
public abstract class AbstractJobRoute extends RouteBuilder {
@Autowired
private GlobalSettingsService settingsService;
and several children defined with @Component
annotation.
You will get the following error message too when you provide undefined or so to an operator which expects an Observable, eg. takeUntil.
TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable
You might be an admin doing a one-off push directly into refs/changes/<change_number>
.
For example, once a commit without Change-Id landed into Subversion, you pull it out of Subversion using git-svn, and you'd like to archive it as a Gerrit patchset into a Gerrit change.
If so, you can go to project settings page (http://[installation-path]/#/admin/projects/[project-id]) and temporarily change "Require Change-Id in commit message" value to False.
Don't forget to afterwards change it back to Inherit or True!
format(int(bits, 2), '0' + str(len(bits) / 4) + 'x')
The proper way to initialize a multidimensional array in C or C++ is
int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};
You can use this same trick to initialize even higher-dimensional arrays if you want.
Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!
I had the same problem my OS is windows 8 and I am using Tomcat 8, I just edited the setclasspath.bat file in bin folder and set JAVA_HOME and JRE_HOME like this...
@echo off
...
...
set "JRE_HOME=%ProgramFiles%\Java\jre8"
set "JAVA_HOME=%ProgramFiles%\Java\jdk1.7.0_03"
...
...
and it works fine for me now......
I know this is an old thread but thought I should mention that the extern
keyword. I've recently ran into this issue and solved as follows
Helper.h
namespace DX
{
extern inline void ThrowIfFailed(HRESULT hr);
}
Helper.cpp
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
std::stringstream ss;
ss << "#" << hr;
throw std::exception(ss.str().c_str());
}
}
}
Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)
In this case its better to use asynctask, which runs on a different thread and return result back to the ui thread on completion.
Windows:
system("cls");
Unix:
system("clear");
You could instead, insert newline chars until everything gets scrolled, take a look here.
With that, you achieve portability easily.
You could try this:
{% if not profile.user.first_name.value %}
<p> -- </p>
{% else %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}
This way, you're essentially checking to see if the form field first_name
has any value associated with it. See {{ field.value }}
in Looping over the form's fields in Django Documentation.
I'm using Django 3.0.
I've always used:
unique = (arr) => arr.filter((item, i, s) => s.lastIndexOf(item) == i);
But recently I had to get unique values for:
["1", 1, "2", 2, "3", 3]
And my old standby didn't cut it, so I came up with this:
uunique = (arr) => Object.keys(Object.assign({}, ...arr.map(a=>({[a]:true}))));
Here's an example of how to convert DATETIME
to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))
Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')
Documentation: UNIX_TIMESTAMP
, FROM_UNIXTIME
npm start --mode production
npm start --mode development
With process.env.NODE_ENV = 'production'
I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:
function toLocalIsoString(date, includeSeconds) {
function pad(n) { return n < 10 ? '0' + n : n }
var localIsoString = date.getFullYear() + '-'
+ pad(date.getMonth() + 1) + '-'
+ pad(date.getDate()) + 'T'
+ pad(date.getHours()) + ':'
+ pad(date.getMinutes()) + ':'
+ pad(date.getSeconds());
if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
return localIsoString;
};
The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:
function getOffsetFromUTC() {
var offset = new Date().getTimezoneOffset();
return ((offset < 0 ? '+' : '-')
+ pad(Math.abs(offset / 60), 2)
+ ':'
+ pad(Math.abs(offset % 60), 2))
};
toLocalIsoString
uses pad
. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:
// Pad a number to length using padChar
function pad(number, length, padChar) {
if (typeof length === 'undefined') length = 2;
if (typeof padChar === 'undefined') padChar = '0';
var str = "" + number;
while (str.length < length) {
str = padChar + str;
}
return str;
}
A minimalistic example to quickly test the TTS system:
private TextToSpeech textToSpeechSystem;
@Override
protected void onStart() {
super.onStart();
textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
String textToSay = "Hello world, this is a test message!";
textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
If you don't use localized messages textToSpeechSystem.setLanguage(..)
is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough
Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech
The problem was that the wrong hamcrest.Matcher
, not hamcrest.MatcherAssert
, class was being used. That was being pulled in from a junit-4.8 dependency one of my dependencies was specifying.
To see what dependencies (and versions) are included from what source while testing, run:
mvn dependency:tree -Dscope=test
You can have access of the machine name using Environment.MachineName.
One way is to track where each index goes to by sorting the identity [0,1,2,..n]
This works for any number of lists.
Then move each item to its position. Using splices is best.
list1 = [3,2,4,1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']
index = list(range(len(list1)))
print(index)
'[0, 1, 2, 3, 4]'
index.sort(key = list1.__getitem__)
print(index)
'[3, 4, 1, 0, 2]'
list1[:] = [list1[i] for i in index]
list2[:] = [list2[i] for i in index]
print(list1)
print(list2)
'[1, 1, 2, 3, 4]'
"['one', 'one2', 'two', 'three', 'four']"
Note we could have iterated the lists without even sorting them:
list1_iter = (list1[i] for i in index)
I would use two separate 'container' div as below:
<div class="container">
/* normal*/
</div>
<div class="container-fluid">
/*full width container*/
</div>
Bare in mind that container-fluid does not follow your breakpoints and it is a full width container.
Here's a quick way to do it, won't require anything besides sys
.. though functionality is limited:
flag = "--flag" in sys.argv[1:]
[1:]
is in case if the full file name is --flag
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
from names) n2
on (n2.author_id = n1.author_id)
Where true
used distinct
if more inner join, because more join group performance is slow
You can put up all your JS like this, so it doesn't execute before your HTML is ready
$(document).ready(function() {
// some code here
});
Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload
Using windows authentication:
String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01;integratedSecurity=true";
Using SQL authentication:
String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01";
Try the iso8601 module; it does exactly this.
There are several other options mentioned on the WorkingWithTime page on the python.org wiki.
public class Application extends SpringBootServletInitializer {}
just extends the SpringBootServletInitializer. It will works in your AWS/tomcat
Naming convention for collection
In order to name a collection few precautions to be taken :
Things to keep in mind while creating a database name are :
For more information. Please check the below link : http://www.tutorial-points.com/2016/03/schema-design-and-naming-conventions-in.html
If you want to remove all the files in the %TEMP%
folder you could just do this:
del %TEMP%\*.* /f /s /q
That will remove everything, any file with any extension (*.*
) and do the same for all sub-folders (/s
), without prompting you for anything (/q
), it will just do it, including read only files (/f
).
Hope this helps.
In angular 4+ we can use innerHTML
property instead of ng-bind-html
.
In my case, it's working and I am using angular 5.
<div class="chart-body" [innerHTML]="htmlContent"></div>
In.ts file
let htmlContent = 'This is the `<b>Bold</b>` text.';
I have got similar issue which data retrieved from .xlsx file. Unfortunately, I could not find the proper answer here. I handled it on my own with dplyr as below which might help others:
#install.packages("xlsx")
library(xlsx)
extracted_df <- read.xlsx("test.xlsx", sheetName='Sheet1', stringsAsFactors=FALSE)
# Replace all NAs in a data frame with "G" character
extracted_df[is.na(extracted_df)] <- "G"
However, I could not handle it with the readxl
package which does not have similar parameter to the stringsAsFactors
. For the reason, I have moved to the xlsx
package.
I went through all answers, but doesn't satisfied my exact needed answer, so here is an example that I wrote and perfectly works, even user clicks the Don't ask again checkbox.
Create a method that will be called when you want to ask for runtime permission like readContacts()
or you can also have openCamera()
as shown below:
private void readContacts() {
if (!askContactsPermission()) {
return;
} else {
queryContacts();
} }
Now we need to make askContactsPermission()
, you can also name it as askCameraPermission()
or whatever permission you are going to ask.
private boolean askContactsPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(parentLayout, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
}).show();
} else if (contactPermissionNotGiven) {
openPermissionSettingDialog();
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
contactPermissionNotGiven = true;
}
return false;
}
Before writing this function make sure you have defined the below instance variable as shown:
private View parentLayout;
private boolean contactPermissionNotGiven;;
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
Now final step to override the onRequestPermissionsResult
method as shown below:
/**
* Callback received when a permissions request has been completed.
*/
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
queryContacts();
}
}
}
Here we are done with the RunTime permissions, the addon is the openPermissionSettingDialog()
which simply open the Setting screen if user have permanently disable the permission by clicking Don't ask again checkbox. below is the method:
private void openPermissionSettingDialog() {
String message = getString(R.string.message_permission_disabled);
AlertDialog alertDialog =
new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
.setMessage(message)
.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
dialog.cancel();
}
}).show();
alertDialog.setCanceledOnTouchOutside(true);
}
What we missed ?
1. Defining the used strings in strings.xml
<string name="permission_rationale">"Contacts permissions are needed to display Contacts."</string>_x000D_
<string name="message_permission_disabled">You have disabled the permissions permanently,_x000D_
To enable the permissions please go to Settings -> Permissions and enable the required Permissions,_x000D_
pressing OK you will be navigated to Settings screen</string>
_x000D_
Initializing the parentLayout
variable inside onCreate
method
parentLayout = findViewById(R.id.content);
Defining the required permission in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
_x000D_
The queryContacts
method, based on your need or the runtime permission you can call your method before which the permission
was needed. in my case I simply use the loader to fetch the contact as shown below:
private void queryContacts() {
getLoaderManager().initLoader(0, null, this);}
This works great happy coding :)
you have to declare current date into variables like this
$(function() {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate)
});
})
Use (keyup.enter)
.
Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter
pseudo-event.
Double quotes around the filename in the header is the standard per MDN web docs. Omitting the quotes creates multiple opportunities for problems arising from characters in the filename.
To get the ASCII code of a character, you can use the ord()
function.
Here is an example code:
value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)
Output:
Your value here: qwerty
[113, 119, 101, 114, 116, 121]
you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name
import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')
sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')
Thanks, Reto, for the detailed explanation!
In case this is of any help to anyone, I had to change the code proposed by Reto Meier to make it work with the SDK for Android 1.5
@Override
protected void onResume() {
super.onResume();
// Setup the initial values
mListPreference.setSummary("Current value is " + mListPreference.getEntry().toString());
// Set up a listener whenever a key changes
...
}
The same change applies for the callback function onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
Cheers,
Chris
create Procedure [dbo].[TextFinder]
(@Text varchar(500),@Type varchar(2)=NULL)
AS
BEGIN
SELECT DISTINCT o.name AS ObjectName,
CASE o.xtype
WHEN 'C' THEN 'CHECK constraint'
WHEN 'D' THEN 'Default or DEFAULT constraint'
WHEN 'F' THEN 'FOREIGN KEY constraint'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY or UNIQUE constraint'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'`enter code here`
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
ELSE o.xtype
END AS ObjectType,
ISNULL( p.Name, '[db]') AS Location
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
LEFT JOIN sysobjects p ON o.Parent_obj=p.id
WHERE c.text LIKE '%' + @Text + '%' and
o.xtype = case when @Type IS NULL then o.xtype else @Type end
ORDER BY Location, ObjectName
END
I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.
There should be the problem, when you generate the <form>
. I bet the variables $name
, $price
are NULL
or empty string when you echo
them into the value
of the <input>
field. Empty input fields are not sent by the browser, so $_POST
will not have their keys.
Anyway, you can check that with isset()
.
Test variables with the following:
if(isset($_POST['key'])) ? $variable=$_POST['key'] : $variable=NULL
You better set it to NULL
, because
NULL value represents a variable with no value.
Key in 1 + G and it will take you to the beginning of the file. Converserly, G will take you to the end of the file.
UPDATE
While these methods work, newer versions of VS Code uses the Ctrl+] shortcut to indent a block of code once, and Ctrl+[ to remove indentation.
This method detects the indentation in a file and indents accordingly.You can change the size of indentation by clicking on the Select Indentation setting in the bottom right of VS Code (looks something like "Spaces: 2"), selecting "Indent using Spaces" from the drop-down menu and then selecting by how many spaces you would like to indent.
If I understand you right, we talk about a text file attachment. Thats unfortunate because if it was the email's message body, you could always use "\r\n", referring to http://www.faqs.org/rfcs/rfc822.html
But as it's an attachment, you must live with system differences. If I were in your shoes, I would choose one of those options:
a) only support windows clients by using "\r\n" as line end.
b) provide two attachment files, one with linux format and one with windows format.
c) I don't know if the attachment is to be read by people or machines, but if it is people I would consider attaching an HTML file instead of plain text. more portable and much prettier, too :)
BUILD_NUMBER
is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.
See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.
This is a solution with extensive error reporting.
It would take an UTF-8 encoded byte array (where byte array is represented as array of numbers and each number is an integer between 0 and 255 inclusive) and will produce a JavaScript string of Unicode characters.
function getNextByte(value, startByteIndex, startBitsStr,
additional, index)
{
if (index >= value.length) {
var startByte = value[startByteIndex];
throw new Error("Invalid UTF-8 sequence. Byte " + startByteIndex
+ " with value " + startByte + " (" + String.fromCharCode(startByte)
+ "; binary: " + toBinary(startByte)
+ ") starts with " + startBitsStr + " in binary and thus requires "
+ additional + " bytes after it, but we only have "
+ (value.length - startByteIndex) + ".");
}
var byteValue = value[index];
checkNextByteFormat(value, startByteIndex, startBitsStr, additional, index);
return byteValue;
}
function checkNextByteFormat(value, startByteIndex, startBitsStr,
additional, index)
{
if ((value[index] & 0xC0) != 0x80) {
var startByte = value[startByteIndex];
var wrongByte = value[index];
throw new Error("Invalid UTF-8 byte sequence. Byte " + startByteIndex
+ " with value " + startByte + " (" +String.fromCharCode(startByte)
+ "; binary: " + toBinary(startByte) + ") starts with "
+ startBitsStr + " in binary and thus requires " + additional
+ " additional bytes, each of which shouls start with 10 in binary."
+ " However byte " + (index - startByteIndex)
+ " after it with value " + wrongByte + " ("
+ String.fromCharCode(wrongByte) + "; binary: " + toBinary(wrongByte)
+") does not start with 10 in binary.");
}
}
function fromUtf8 (str) {
var value = [];
var destIndex = 0;
for (var index = 0; index < str.length; index++) {
var code = str.charCodeAt(index);
if (code <= 0x7F) {
value[destIndex++] = code;
} else if (code <= 0x7FF) {
value[destIndex++] = ((code >> 6 ) & 0x1F) | 0xC0;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0xFFFF) {
value[destIndex++] = ((code >> 12) & 0x0F) | 0xE0;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0x1FFFFF) {
value[destIndex++] = ((code >> 18) & 0x07) | 0xF0;
value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0x03FFFFFF) {
value[destIndex++] = ((code >> 24) & 0x03) | 0xF0;
value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0x7FFFFFFF) {
value[destIndex++] = ((code >> 30) & 0x01) | 0xFC;
value[destIndex++] = ((code >> 24) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else {
throw new Error("Unsupported Unicode character \""
+ str.charAt(index) + "\" with code " + code + " (binary: "
+ toBinary(code) + ") at index " + index
+ ". Cannot represent it as UTF-8 byte sequence.");
}
}
return value;
}
ast.literal_eval()
only considers a small subset of Python's syntax to be valid:
The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and
None
.
Passing __import__('os').system('rm -rf /a-path-you-really-care-about')
into ast.literal_eval()
will raise an error, but eval()
will happily delete your files.
Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval()
. It safely does what you want and nothing more.
OK, we may get confused when we hear about null
and undefined
, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null
is 'object'
while typeof undefined
is 'undefined'
.
typeof null; //"object"
typeof undefined; //"undefined";
But if you check them with ==
as below, you see they are both falsy:
null==undefined; //true
Also you can assign null
to an object property or to a primitive, while undefined
can simply be achieved by not assigning to anything.
I create a quick image to show the differences for you at a glance.
After my investigation, I came up to this solution:
//writing the below line into the top of my style.css file
@import url('https://fonts.googleapis.com/css?family=Assistant:200,300,400,600,700,800&subset=hebrew');
MUST OBSERVE:
We must need to write the font-weight
correctly of this font. For example: font-weight:900;
will not work as we have not included 900
like 200,300,400,600,700,800
into the URL address while importing from Google with the above link. We can add or include 900
to the above URL, but that will work only if the above Google Font has this option while embedding.
To expand a bit on what Brad is saying: many transport mechanisms for email and Usenet and other ways of moving data are not "8 bit clean", which means that characters outside the standard ascii character set might be mangled in transit - for instance, 0x0D might be seen as a carriage return, and turned into a carriage return and line feed. Base 64 maps all the binary characters into several standard ascii letters and numbers and punctuation so they won't be mangled this way.
Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\
. One of these must be true:
Version
value in that key should be 3.5.30729.01SP
value in the same key should be 1In C# (taken from the first comment), you could do something along these lines:
const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();
A simple way of reading variables from a text file using the standard library:
# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
for line in conf:
if ":" in line:
name, value = line.split(":")
var[name] = str(value).rstrip()
globals().update(var)
Most of solutions use static width here. But it can be sometimes wrong for some reasons.
Example: I had table with many columns. Most of them are narrow (static width). But the main column should be as wide as possible (depends on screen size).
HTML:
<table style="width: 100%">
<tr>
<td style="width: 60px;">narrow</td>
<td>
<span class="cutwrap" data-cutwrap="dynamic column can have really long text which can be wrapped on two rows, but we just need not wrapped texts using as much space as possible">
dynamic column can have really long text which can be wrapped on two rows
but we just need not wrapped texts using as much space as possible
</span>
</td>
</tr>
</table>
CSS:
.cutwrap {
position: relative;
overflow: hidden;
display: block;
width: 100%;
height: 18px;
white-space: normal;
color: transparent !important;
}
.cutwrap::selection {
color: transparent !important;
}
.cutwrap:before {
content: attr(data-cutwrap);
position: absolute;
left: 0;
right: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #333;
}
/* different styles for links */
a.cutwrap:before {
text-decoration: underline;
color: #05c;
}
Xcode 8.2.1 • Swift 3.0.2
Locale.availableIdentifiers
Locale.isoRegionCodes
Locale.isoCurrencyCodes
Locale.isoLanguageCodes
Locale.commonISOCurrencyCodes
Locale.current.regionCode // "US"
Locale.current.languageCode // "en"
Locale.current.currencyCode // "USD"
Locale.current.currencySymbol // "$"
Locale.current.groupingSeparator // ","
Locale.current.decimalSeparator // "."
Locale.current.usesMetricSystem // false
Locale.windowsLocaleCode(fromIdentifier: "pt_BR") // 1,046
Locale.identifier(fromWindowsLocaleCode: 1046) ?? "" // "pt_BR"
Locale.windowsLocaleCode(fromIdentifier: Locale.current.identifier) // 1,033 Note: I am in Brasil but I use "en_US" format with all my devices
Locale.windowsLocaleCode(fromIdentifier: "en_US") // 1,033
Locale.identifier(fromWindowsLocaleCode: 1033) ?? "" // "en_US"
Locale(identifier: "en_US_POSIX").localizedString(forLanguageCode: "pt") // "Portuguese"
Locale(identifier: "en_US_POSIX").localizedString(forRegionCode: "br") // "Brazil"
Locale(identifier: "en_US_POSIX").localizedString(forIdentifier: "pt_BR") // "Portuguese (Brazil)"
TimeZone.current.localizedName(for: .standard, locale: .current) ?? "" // "Brasilia Standard Time"
TimeZone.current.localizedName(for: .shortStandard, locale: .current) ?? "" // "GMT-3
TimeZone.current.localizedName(for: .daylightSaving, locale: .current) ?? "" // "Brasilia Summer Time"
TimeZone.current.localizedName(for: .shortDaylightSaving, locale: .current) ?? "" // "GMT-2"
TimeZone.current.localizedName(for: .generic, locale: .current) ?? "" // "Brasilia Time"
TimeZone.current.localizedName(for: .shortGeneric, locale: .current) ?? "" // "Sao Paulo Time"
var timeZone: String {
return TimeZone.current.localizedName(for: TimeZone.current.isDaylightSavingTime() ?
.daylightSaving :
.standard,
locale: .current) ?? "" }
timeZone // "Brasilia Summer Time"
Public Declare Function GetUserName Lib "advapi32.dll"
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
....
Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String
strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))
Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?
For those coming from another language like me, maybe with a simple loop it's easier to understand and use it:
mylist = ["foo", "bar", "baz", "bar"]
newlist = enumerate(mylist)
for index, item in newlist:
if item == "bar":
print(index, item)
I am thankful for So what exactly does enumerate do?. That helped me to understand.
I need to point out here that you're incorrectly adding middleware to the application. The app.use
calls should not be done within the app.get
request handler, but outside of it. Simply call them directly after createServer
, or take a look at the other examples in the docs.
The secret you pass to express.session
should be a string constant, or perhaps something taken from a configuration file. Don't feed it something the client might know, that's actually dangerous. It's a secret only the server should know about.
If you want to store the email address in the session, simply do something along the lines of:
req.session.email = req.param('email');
With that out of the way...
If I understand correctly, what you're trying to do is handle one or more HTTP requests and keep track of a session, then later on open a Socket.IO connection from which you need the session data as well.
What's tricky about this problem is that Socket.IO's means of making the magic work on any http.Server
is by hijacking the request
event. Thus, Express' (or rather Connect's) session middleware is never called on the Socket.IO connection.
I believe you can make this work, though, with some trickery.
You can get to Connect's session data; you simply need to get a reference to the session store. The easiest way to do that is to create the store yourself before calling express.session
:
// A MemoryStore is the default, but you probably want something
// more robust for production use.
var store = new express.session.MemoryStore;
app.use(express.session({ secret: 'whatever', store: store }));
Every session store has a get(sid, callback)
method. The sid
parameter, or session ID, is stored in a cookie on the client. The default name of that cookie is connect.sid
. (But you can give it any name by specifying a key
option in your express.session
call.)
Then, you need to access that cookie on the Socket.IO connection. Unfortunately, Socket.IO doesn't seem to give you access to the http.ServerRequest
. A simple work around would be to fetch the cookie in the browser, and send it over the Socket.IO connection.
Code on the server would then look something like the following:
var io = require('socket.io'),
express = require('express');
var app = express.createServer(),
socket = io.listen(app),
store = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ secret: 'something', store: store }));
app.get('/', function(req, res) {
var old = req.session.email;
req.session.email = req.param('email');
res.header('Content-Type', 'text/plain');
res.send("Email was '" + old + "', now is '" + req.session.email + "'.");
});
socket.on('connection', function(client) {
// We declare that the first message contains the SID.
// This is where we handle the first message.
client.once('message', function(sid) {
store.get(sid, function(err, session) {
if (err || !session) {
// Do some error handling, bail.
return;
}
// Any messages following are your chat messages.
client.on('message', function(message) {
if (message.email === session.email) {
socket.broadcast(message.text);
}
});
});
});
});
app.listen(4000);
This assumes you only want to read an existing session. You cannot actually create or delete sessions, because Socket.IO connections may not have a HTTP response to send the Set-Cookie
header in (think WebSockets).
If you want to edit sessions, that may work with some session stores. A CookieStore wouldn't work for example, because it also needs to send a Set-Cookie
header, which it can't. But for other stores, you could try calling the set(sid, data, callback)
method and see what happens.
The behavior of defaultdict
can be easily mimicked using dict.setdefault
instead of d[key]
in every call.
In other words, the code:
from collections import defaultdict
d = defaultdict(list)
print(d['key']) # empty list []
d['key'].append(1) # adding constant 1 to the list
print(d['key']) # list containing the constant [1]
is equivalent to:
d = dict()
print(d.setdefault('key', list())) # empty list []
d.setdefault('key', list()).append(1) # adding constant 1 to the list
print(d.setdefault('key', list())) # list containing the constant [1]
The only difference is that, using defaultdict
, the list constructor is called only once, and using dict.setdefault
the list constructor is called more often (but the code may be rewriten to avoid this, if really needed).
Some may argue there is a performance consideration, but this topic is a minefield. This post shows there isn't a big performance gain in using defaultdict, for example.
IMO, defaultdict is a collection that adds more confusion than benefits to the code. Useless for me, but others may think different.
The problem is insufficient memory to load context.
Try to set VM options:
-da -Xmx2048m -Xms1024m -XX:MaxPermSize=2048m
perhaps not the most elegant way to solve this
select Activity,
SUM(Amount) as "Total_Amount",
2009 AS INCOME_YEAR
from Activities, Incomes
where Activities.UnitName = ? AND
Incomes.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;
UNION
select Activity,
SUM(Amount) as "Total_Amount",
2008 AS INCOME_YEAR
from Activities, Incomes2008
where Activities.UnitName = ? AND
Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;
I tried using mrperfect's answer and i had a couple glitches. With a couple small changes, I was able to get it to work for me. I just changed it so that it would only do it once. Once you exit dropdown, it would go back to the regular method of dropdowns.
function down() {
var pos = $(this).offset(); // remember position
$(this).css("position", "absolute");
$(this).offset(pos); // reset position
$(this).attr("size", "15"); // open dropdown
$(this).unbind("focus", down);
}
function up() {
$(this).css("position", "static");
$(this).attr("size", "1"); // close dropdown
$(this).unbind("change", up);
}
function openDropdown(elementId) {
$('#' + elementId).focus(down).blur(up).focus();
}
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Try this:
Edit or create the file :nodesource.list
sudo gedit /etc/apt/sources.list.d/nodesource.list
Insert this text:
deb https://deb.nodesource.com/node_10.x bionic main
deb-src https://deb.nodesource.com/node_10.x bionic main
Run these commands:
curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
sudo sh -c "echo deb https://deb.nodesource.com/node_10.x cosmic main /etc/apt/sources.list.d/nodesource.list"
sudo apt-get update
sudo apt-get install nodejs
this code will work with OI File Manager :
File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
Uri uri = Uri.fromFile(root);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(uri);
startActivityForResult(intent, 1);
you can get OI File manager here : http://www.openintents.org/en/filemanager
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.
\xXX is for chars < 127, and \uXXXX for Unicode, so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist.
For example,
<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>
You can use the datetime
module for working with dates and times in Python. The strftime
method allows you to produce string representation of dates and times with a format you specify.
>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'July 23, 2010'
>>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
'10:36AM on July 23, 2010'
This did it for me: (10 years later)
git log [--remotes] --no-walk --decorate
Since there is no stored information on branch creation times, what this does is display the first commit of each branch (--no-walk
), which includes the date of the commit. Use --remotes
for the remote branches, or omit it for local branches.
Since I do at least one commit in a branch before creating another one, this permitted me trace back a few months of branch creations (and feature dev-start) for documentation purposes.
source: AnoE on stackexchange
Apart from cool solutions above I'd mention also about supervisord and monit tools which allow to start process, monitor its presence and start it if it died. With 'monit' you can also run some active checks like check if process responds for http request
Notify.js is a wrapper around the new webkit notifications. It works pretty well.
http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/
Easiest way I know of is to use "child_process" package which comes packaged with node.
Then you can do something like:
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);
Then all you have to do is make sure that you import sys
in your python script, and then you can access arg1
using sys.argv[1]
, arg2
using sys.argv[2]
, and so on.
To send data back to node just do the following in the python script:
print(dataToSendBack)
sys.stdout.flush()
And then node can listen for data using:
pythonProcess.stdout.on('data', (data) => {
// Do something with the data returned from python script
});
Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.
Hope this was clear. Let me know if something needs clarification.
You can use this for color without alpha:
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
or this with alpha:
String hexColor = String.format("#%08X", (0xFFFFFFFF & intColor));
You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.
I added some images to drawable resourses, and one of my images was named as "super.jpg", which turn out to be a cause.
Renaming the image and after that syncronization the project with gradle files fixed the error.
Add below lib inside gradle file
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
Create class HomeActivityTest inside androidTest directory and before running the test add flurry_api_key and sender_id string inside string resource file and change the value for failure and success case.
@RunWith(AndroidJUnit4.class)
public class HomeActivityTest
{
private static final String SENDER_ID = "abc";
private static final String RELEASE_FLURRY_API_KEY = "xyz";
@Test
public void gcmRegistrationId_isCorrect() throws Exception
{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
Assert.assertEquals(SENDER_ID, appContext.getString(R.string.sender_id));
}
@Test
public void flurryApiKey_isCorrect() throws Exception
{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
Assert.assertEquals(RELEASE_FLURRY_API_KEY, appContext.getString(R.string.flurry_api_key));
}
}
In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :
example :
import tensorflow as tf
input_x = tf.placeholder(tf.int32,[None,None])
word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))
embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)
with tf.Session() as tt:
tt.run(tf.global_variables_initializer())
a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
print(b)
And if my array is :
example_array = [[1,2,3],[1,2]]
Then i will get error :
ValueError: setting an array element with a sequence.
but if i do padding then :
example_array = [[1,2,3],[1,2,0]]
Now it's working.
it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.
btnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
}
}
Try Logic Friday 1
It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.
The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.
Your expression simplifies to C
.
Do you mean something like this?
In [39]: df2.pivot_table(values='X', rows='Y', cols='Z',
aggfunc=lambda x: len(x.unique()))
Out[39]:
Z Z1 Z2 Z3
Y
Y1 1 1 NaN
Y2 NaN NaN 1
Note that using len
assumes you don't have NA
s in your DataFrame. You can do x.value_counts().count()
or len(x.dropna().unique())
otherwise.
Like this.
.divContainer input[type="text"] {
width:150px;
}
.divContainer input[type="radio"] {
width:20px;
}
Storing with json or serialized array is the best solution for now. With some situations (trimming " ' characters) json might be getting trouble but serialize should be great choice.
Note: If you change serialized data manually, you need to be careful about character count.
Double number = new Double("5.25");
Double tDouble =
new BigDecimal(number).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
this will return it will return 5.3
I'd like to add one more thing. In LINQ to SQL if your DB is properly built and your tables are related through foreign key constraints, then you do not need to do a join at all.
Using LINQPad I created the following LINQ query:
//Querying from both the CustomerInfo table and OrderInfo table
from cust in CustomerInfo
where cust.CustomerID == 123456
select new {cust, cust.OrderInfo}
Which was translated to the (slightly truncated) query below
-- Region Parameters
DECLARE @p0 Int = 123456
-- EndRegion
SELECT [t0].[CustomerID], [t0].[AlternateCustomerID], [t1].[OrderID], [t1].[OnlineOrderID], (
SELECT COUNT(*)
FROM [OrderInfo] AS [t2]
WHERE [t2].[CustomerID] = [t0].[CustomerID]
) AS [value]
FROM [CustomerInfo] AS [t0]
LEFT OUTER JOIN [OrderInfo] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE [t0].[CustomerID] = @p0
ORDER BY [t0].[CustomerID], [t1].[OrderID]
Notice the LEFT OUTER JOIN
above.
Python code:
import sys
# main
param_1= sys.argv[1]
param_2= sys.argv[2]
param_3= sys.argv[3]
print 'Params=', param_1, param_2, param_3
Invocation:
$python myfile.py var1 var2 var3
Output:
Params= var1 var2 var3
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
Semicolon should be at the end of the class definition rather than after the name:
class WordGame
{
};
Unless you're using spaces in there, you should be able to use | wc -w
on the first line.
wc
is "Word Count", which simply counts the words in the input file. If you send only one line, it'll tell you the amount of columns.
If you can't use JodaTime, you can do the following:
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want.
I was getting this error and switched the queries to async (await (...).ToListAsync()). All good now.
the line below shows you haven't set an DataAttribute like required on AgreementNumber
<input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" />
you need
[Required]
public String AgreementNumber{get;set;}
Guava has a method to do this for you: double[] Doubles.toArray(Collection<Double>)
This isn't necessarily going to be any faster than just looping through the Collection
and adding each Double
object to the array, but it's a lot less for you to write.
this is how you can parse iCal files with javascript
function calParse(str) {
function parse() {
var obj = {};
while(str.length) {
var p = str.shift().split(":");
var k = p.shift(), p = p.join();
switch(k) {
case "BEGIN":
obj[p] = parse();
break;
case "END":
return obj;
default:
obj[k] = p;
}
}
return obj;
}
str = str.replace(/\n /g, " ").split("\n");
return parse().VCALENDAR;
}
example =
'BEGIN:VCALENDAR\n'+
'VERSION:2.0\n'+
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'+
'BEGIN:VEVENT\n'+
'DTSTART:19970714T170000Z\n'+
'DTEND:19970715T035959Z\n'+
'SUMMARY:Bastille Day Party\n'+
'END:VEVENT\n'+
'END:VCALENDAR\n'
cal = calParse(example);
alert(cal.VEVENT.SUMMARY);
This is the reason behind this error:
It will look for how the database that you are using generates ids. For MySql or HSQSL, there are increment fields that automatically increment. In Postgres or Oracle, they use sequence tables. Since you didn't specify a sequence table name, it will look for a sequence table named hibernate_sequence and use it for default. So you probably don't have such a sequence table in your database and now you get that error.
One option would be using Electron with JavaScript, HTML, and CSS for UI and build a .NET Core console application that will self-host a web API for back-end logic. Electron will start the console application in the background that will expose a service on localhost:xxxx.
This way you can implement all back-end logic using .NET to be accessible through HTTP requests from JavaScript.
Take a look at this post, it explains how to build a cross-platform desktop application with Electron and .NET Core and check code on GitHub.
NOTE: For a concise and efficient solution, please see Marc-André Lafortune's answer below.
This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.
Warning! Solutions using flatten will not preserve Array keys or values!
Building on @John Topley's popular answer, let's try:
a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]
This throws an error:
ArgumentError: odd number of arguments for Hash
from (irb):10:in `[]'
from (irb):10
The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.
If you want to use Array keys or values, you can use map:
h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"
This preserves the Array key:
h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}
Method to convert a List<List>
to List
:
listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());
See this example:
public class Example {
public static void main(String[] args) {
List<List<String>> listOfLists = Collections.singletonList(Arrays.asList("a", "b", "v"));
List<String> list = listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());
System.out.println("listOfLists => " + listOfLists);
System.out.println("list => " + list);
}
}
It prints:
listOfLists => [[a, b, c]]
list => [a, b, c]
In Python this can be done using List Comprehension.
list_of_lists = [['Roopa','Roopi','Tabu', 'Soudipta'],[180.0, 1231, 2112, 3112], [130], [158.2], [220.2]]
flatten = [val for sublist in list_of_lists for val in sublist]
print(flatten)
['Roopa', 'Roopi', 'Tabu', 'Soudipta', 180.0, 1231, 2112, 3112, 130, 158.2, 220.2]
As far as I understand, you create a Movie class:
class Movie
{
private:
std::string _title;
std::string _director;
int _year;
int _rating;
std::vector<std::string> actors;
};
and having such class, you create a vector instance:
std::vector<Movie*> movies;
so, you can add any movie to your movies collection. Since you are creating a vector of pointers to movies, do not forget to free the resources allocated by your movie instances OR you could use some smart pointer to deallocate the movies automatically:
std::vector<shared_ptr<Movie>> movies;
I guess in the context of neural network terminology:
In order to define iteration (a.k.a steps), you first need to know about batch size:
Batch size: You probably wouldn't like to process the entire training instances all at one forward pass as it is inefficient and needs a huge deal of memory. So what is commonly done is splitting up training instances into subsets (i.e., batches), performing one pass over the selected subset (i.e., batch), and then optimizing the network through backpropagation. The number of training instances within a subset (i.e., batch) is called batch_size.
Iteration: (a.k.a training steps) You know that your network has to go over all training instances in one pass in order to complete one epoch. But wait! when you are splitting up your training instances into batches, that means you can only process one batch (a subset of training instances) in one forward pass, so what about the other batches? This is where the term Iteration comes into play:
Definition: The number of forward passes (The number of batches that you have created) that your network has to do in order to complete one epoch (i.e., going over all training instances) is called Iteration.
For example, when you have 10000 training instances and you want to do batching with size of 10; you have to do 10000/10 = 1000 iterations to complete 1 epoch.
Hope this could answer your question!
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
A slightly shorter solution, that only moves the item to the end, not anywhere is this:
l += [l.pop(0)]
For example:
>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]
AngularJs lets you to use filters inside template or inside Controller, Directive etc..
in template you can use this syntax
{{ variable | MyFilter: ... : ... }}
and inside controller you can use injecting the $filter service
angular.module('MyModule').controller('MyCtrl',function($scope, $filter){
$filter('MyFilter')(arg1, arg2);
})
If you need more with Demo example here is a link
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
Try this
<input type="text"/>
It will display same in all cross browser like mozilla , chrome and internet explorer.
<style>
input{
border:2px solid #FF0000;
}
</style>
Dont add style inline because its not good practise, use class to add style for your input box.
Edit (2017-10-12):
@MechaLynx and @Kevin-Weber note that unescape()
is deprecated from non-browser environments and does not exist in TypeScript. decodeURIComponent
is a drop-in replacement. For broader compatibility, use the below instead:
decodeURIComponent(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
> 'http://example.com'
Original answer:
unescape(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
> 'http://example.com'
You can offload all the work to JSON.parse
VBA functions treat the function name itself as a sort of variable. So instead of using a "return
" statement, you would just say:
test = 1
Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test
, and whatever the value is when you reach the end of the function will be the value returned.
You can use the following SQL to compare both date and time -
Select * From temp where mydate > STR_TO_DATE('2009-06-29 04:00:44', '%Y-%m-%d %H:%i:%s');
Attached mysql output when I used same SQL on same kind of table and field that you mentioned in the problem-
It should work perfect.
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
You can load a local Javascript file (in the tree below your file:/
source page) using the source tag:
<script src="my_data.js"></script>
If you encode your input into Javascript, like in this case:
mydata.js:
$xsl_text = "<xsl:stylesheet version="1.0" + ....
(this is easier for json) then you have your 'data' in a Javascript global variable to use as you wish.
You can use the -B
option.
-B, --block-size=SIZE use SIZE-byte blocks
All together,
df -BG
Check out Boost.Units: link text
It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?
quantity<force> F = 2.0*newton;
quantity<length> dx = 2.0*meter;
quantity<energy> E = F * dx;
std::cout << "Energy = " << E << endl;
would actually output "Energy = 4 J" which is correct.
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
Assuming that your current primary key constraint is called pk_history, you can replace the following lines:
ALTER TABLE history ADD PRIMARY KEY (id)
ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name
with these:
ALTER TABLE history DROP CONSTRAINT pk_history
ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
If you don't know what the name of the PK is, you can find it with the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'history'
In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS
in docker
setting (on the right side of the task bar, right click on docker
, select setting
)
We can pass string value to main method as argument without using commandline argument concept in java through Netbean
package MainClass;
import java.util.Scanner;
public class CmdLineArgDemo {
static{
Scanner readData = new Scanner(System.in);
System.out.println("Enter any string :");
String str = readData.nextLine();
String [] str1 = str.split(" ");
// System.out.println(str1.length);
CmdLineArgDemo.main(str1);
}
public static void main(String [] args){
for(int i = 0 ; i<args.length;i++) {
System.out.print(args[i]+" ");
}
}
}
Enter any string :
Coders invent Digital World
Coders invent Digital World
bootstrap.js is using jquery library so you need to add jquery library before bootstrap js.
so please add it jquery library like
Note : Please maintain order of js file. html page use top to bottom approach for compilation
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
import pandas as pd
# given
df1 = pd.DataFrame({'Name':['John','Mike','Smith','Wale','Marry','Tom','Menda','Bolt','Yuswa',],
'Age':[23,45,12,34,27,44,28,39,40]})
df2 = pd.DataFrame({'Name':['John','Smith','Wale','Tom','Menda','Yuswa',],
'Age':[23,12,34,44,28,40]})
# find elements in df1 that are not in df2
df_1notin2 = df1[~(df1['Name'].isin(df2['Name']) & df1['Age'].isin(df2['Age']))].reset_index(drop=True)
# output:
print('df1\n', df1)
print('df2\n', df2)
print('df_1notin2\n', df_1notin2)
# df1
# Age Name
# 0 23 John
# 1 45 Mike
# 2 12 Smith
# 3 34 Wale
# 4 27 Marry
# 5 44 Tom
# 6 28 Menda
# 7 39 Bolt
# 8 40 Yuswa
# df2
# Age Name
# 0 23 John
# 1 12 Smith
# 2 34 Wale
# 3 44 Tom
# 4 28 Menda
# 5 40 Yuswa
# df_1notin2
# Age Name
# 0 45 Mike
# 1 27 Marry
# 2 39 Bolt
quite late to the party but %-d
works on my end.
datetime.now().strftime('%B %-d, %Y')
produces something like "November 5, 2014"
cheers :)
Usually, if you have big python objects it's quite hard to format them. I personally prefer using some tools for that.
Here is python-beautifier - www.cleancss.com/python-beautify that instantly turns your data into customizable style.
srcset
Most current browsers today support the srcset
attribute, which allows specifying different images to different users. For example, you can use it for 1x and 2x pixel density, and the browser will select the correct file.
In this case, if you specify an SVG in the srcset
and the browser doesn't support it, it'll fallback on the src
.
<img src="logo.png" srcset="logo.svg" alt="My logo">
This method has several benefits over other solutions:
srcset
should know how to handle it so that it only downloads the file it needs.What SSL private key should be sent along with the client certificate?
None of them :)
One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth
). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.
Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.
Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure
Use TLS 1.0 and above; and use Server Name Indication.
You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:
openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
-cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem
You can also use -CAfile
to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.
If you want to add a new record in the form
newRecord = [4L, 1L, u'DDD', 1689544L, datetime.datetime(2010, 9, 21, 21, 45), u'jhhjjh']
to messageName
where messageName
in the form X_somemessage
can, but does not have to be in your dictionary, then do it this way:
myDict.setdefault(messageName, []).append(newRecord)
This way it will be appended to an existing messageName
or a new list will be created for a new messageName
.
I couldn't find a way to inject and use the $routeParams
service (which I would assume would be a better solution) I tried this thinking it might work:
angular.module('myApp', []).
config(function ($routeProvider, $routeParams) {
$routeProvider.when('/:primaryNav/:secondaryNav', {
templateUrl: 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html'
});
});
Which yielded this error:
Unknown provider: $routeParams from myApp
If something like that isn't possible you can change your templateUrl
to point to a partial HTML file that just has ng-include
and then set the URL in your controller using $routeParam
s like this:
angular.module('myApp', []).
config(function ($routeProvider) {
$routeProvider.when('/:primaryNav/:secondaryNav', {
templateUrl: 'resources/angular/templates/nav/urlRouter.html',
controller: 'RouteController'
});
});
function RouteController($scope, $routeParams) {
$scope.templateUrl = 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html';
}
With this as your urlRouter.html
<div ng-include src="templateUrl"></div>
Thw following should work:
.main #main_content {
padding: 5px;
margin: 0px;
overflow: auto;
width: 100%; //for some explorer browsers to trigger hasLayout
}
You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.
If this is the case, you should take a look at the setTimeZone method of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.
A simple example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
String timestamp = formatter.format(cal.getTime());
Actually, to query the team_name
, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.
from urllib2 import urlopen
import json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)
for i in json_obj['team']:
print i['team_name']
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
System images are pre-installed Android operating systems, and are only used by emulators. If you use your real Android device for debugging, you no longer need them, so you can remove them all.
The cleanest way to remove them is using SDK Manager. Open up SDK Manager and uncheck those system images and then apply.
Also feel free to remove other components (e.g. old SDK levels) that are of no use.
string stringToDecrypt = CypherText.Replace(" ", "+");
int len = stringToDecrypt.Length;
byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
Change secret_string += str(chr(char + 7429146))
To secret_string += chr(ord(char) + 7429146)
ord()
converts the character to its Unicode integer equivalent. chr()
then converts this integer into its Unicode character equivalent.
Also, 7429146 is too big of a number, it should be less than 1114111
I found a great code for you:
HTML
<form class="form-wrapper cf">
<input type="text" placeholder="Search here..." required>
<button type="submit">Search</button>
</form>
CSS
/*Clearing Floats*/
.cf:before, .cf:after {
content:"";
display:table;
}
.cf:after {
clear:both;
}
.cf {
zoom:1;
}
/* Form wrapper styling */
.form-wrapper {
width: 450px;
padding: 15px;
margin: 150px auto 50px auto;
background: #444;
background: rgba(0,0,0,.2);
border-radius: 10px;
box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}
/* Form text input */
.form-wrapper input {
width: 330px;
height: 20px;
padding: 10px 5px;
float: left;
font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
border: 0;
background: #eee;
border-radius: 3px 0 0 3px;
}
.form-wrapper input:focus {
outline: 0;
background: #fff;
box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}
.form-wrapper input::-webkit-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-moz-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-ms-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
/* Form submit button */
.form-wrapper button {
overflow: visible;
position: relative;
float: right;
border: 0;
padding: 0;
cursor: pointer;
height: 40px;
width: 110px;
font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
color: #fff;
text-transform: uppercase;
background: #d83c3c;
border-radius: 0 3px 3px 0;
text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}
.form-wrapper button:hover {
background: #e54040;
}
.form-wrapper button:active,
.form-wrapper button:focus {
background: #c42f2f;
outline: 0;
}
.form-wrapper button:before { /* left arrow */
content: '';
position: absolute;
border-width: 8px 8px 8px 0;
border-style: solid solid solid none;
border-color: transparent #d83c3c transparent;
top: 12px;
left: -6px;
}
.form-wrapper button:hover:before {
border-right-color: #e54040;
}
.form-wrapper button:focus:before,
.form-wrapper button:active:before {
border-right-color: #c42f2f;
}
.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
border: 0;
padding: 0;
}
with Apache PDFBox it goes like this:
PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println("Text:" + text);
}
document.close();
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.
If you want to remove the default value constraint, you can do:
ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;
I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!
As other answers already say, Python can keep from releasing memory to the OS even if it's no longer in use by Python code (so gc.collect()
doesn't free anything) especially in a long-running program. Anyway if you're on Linux you can try to release memory by invoking directly the libc function malloc_trim
(man page).
Something like:
import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)
You can use stri_detect_fixed function from stringi
package
stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
[1] TRUE FALSE
Mockito allows mocking abstract classes by means of the @Mock
annotation:
public abstract class My {
public abstract boolean myAbstractMethod();
public void myNonAbstractMethod() {
// ...
}
}
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@Mock(answer = Answers.CALLS_REAL_METHODS)
private My my;
@Test
private void shouldPass() {
BDDMockito.given(my.myAbstractMethod()).willReturn(true);
my.myNonAbstractMethod();
// ...
}
}
The disadvantage is that it cannot be used if you need constructor parameters.
You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar
environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");
spring.factories of spring-cloud-commons-2.1.0.RC2.jar
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor
You can't have optional arguments that default to a certain value in Java. The nearest thing to what you are talking about is java varargs whereby you can pass an arbitrary number of arguments (of the same type) to a method.
It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.
I recently encountered this problem while working on a contract project(deemed classified). The system in which I had to run the code did not have internet access, for security purposes of course, and so installing dependencies, using composer and npm, was becoming huge pain.
After much deliberation with my colleague, we decided to just wing it and copy paste our dependencies rather than doing composer install or npm install.
This led us to NOT add vendors and npm_modules in gitignore. This is when I encountered this problem.
Changed but not updated:
modified: vendor/plugins/open_flash_chart_2 (modified content, untracked content)
I googled this a bit and found this helpful thread on SO. Not being too much of a pro in Git, and being a little intoxicated while working on it, I just searched for all the submodules in the vendors folder
find . -name ".git"
This gave me some 4-5 dependencies that had git on them. I removed all these .git folders and voila, it worked. I knows it's hack, and not a very geeky one anyways. O Gods of SO, please forgive me! Next time I promise to read up on gitlinks and obey O mighty Linus Tovalds.
Try this:
num = input("Please input your number: ")
num = float("%0.2f" % (num))
print(num)
I believe this is a lot simpler. For 1 decimal place use %0.1f
. For 2 decimal places use %0.2f
and so on.
Or, if you want to reduce it all to 2 lines:
num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)
For External Tables, Hive stores the data in the LOCATION specified during creation of the table(generally not in warehouse directory). If the external table is dropped, then the table metadata is deleted but not the data.
For Internal tables, Hive stores data into its warehouse directory. If the table is dropped then both the table metadata and the data will be deleted.
Difference between Internal & External tables :
For External Tables -
External table stores files on the HDFS server but tables are not linked to the source file completely.
If you delete an external table the file still remains on the HDFS server.
As an example if you create an external table called “table_test” in HIVE using HIVE-QL and link the table to file “file”, then deleting “table_test” from HIVE will not delete “file” from HDFS.
External table files are accessible to anyone who has access to HDFS file structure and therefore security needs to be managed at the HDFS file/folder level.
Meta data is maintained on master node, and deleting an external table from HIVE only deletes the metadata not the data/file.
For Internal Tables-
- Stored in a directory based on settings in
hive.metastore.warehouse.dir
, by default internal tables are stored in the following directory “/user/hive/warehouse” you can change it by updating the location in the config file .- Deleting the table deletes the metadata and data from master-node and HDFS respectively.
- Internal table file security is controlled solely via HIVE. Security needs to be managed within HIVE, probably at the schema level (depends on organization).
Hive may have internal or external tables, this is a choice that affects how data is loaded, controlled, and managed.
Use EXTERNAL tables when:
Use INTERNAL tables when:
Source :
add html = true to the tooltip options
$({selector}).tooltip({html: true});
Update
it's not relevant for jQuery ui tooltip property - it's true in bootstrap ui tooltip - my bad!