Alternately, it could also be done as:
<?php
include("ckeditor/ckeditor.php");
$CKeditor = new CKeditor();
$CKeditor->BasePath = 'ckeditor/';
$CKeditor->editor('editor1');
?>
Note that the last line is having 'editor1' as name, it could be changed as per your requirement.
For ajax requests,
for(k in CKEDITOR.instances){
var instance = CKEDITOR.instances[k];
instance.destroy()
}
CKEDITOR.replaceAll();
this snipped removes all instances from document. Then creates new instances.
I spent a while trying to figure this one out and here is what I did. I've broken it down very simply as that is what I needed.
Directly below your ckeditor text area, enter the upload file like this >>>>
<form action="welcomeeditupload.asp" method="post" name="deletechecked">
<div align="center">
<br />
<br />
<label></label>
<textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"><%=(rslegschedule.Fields.Item("welcomevar").Value)%></textarea>
<script type="text/javascript">
//<![CDATA[
CKEDITOR.replace( 'editor1',
{
filebrowserUploadUrl : 'updateimagedone.asp'
});
//]]>
</script>
<br />
<br />
<br />
<input type="submit" value="Update">
</div>
</form>
'and then add your upload file, here is mine which is written in ASP. If you're using PHP, etc. simply replace the ASP with your upload script but make sure the page outputs the same thing.
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
if Request("CKEditorFuncNum")=1 then
Set Upload = Server.CreateObject("Persits.Upload")
Upload.OverwriteFiles = False
Upload.SetMaxSize 5000000, True
Upload.CodePage = 65001
On Error Resume Next
Upload.Save "d:\hosting\belaullach\senate\legislation"
Dim picture
For Each File in Upload.Files
Ext = UCase(Right(File.Path, 3))
If Ext <> "JPG" Then
If Ext <> "BMP" Then
Response.Write "File " & File.Path & " is not a .jpg or .bmp file." & "<BR>"
Response.write "You can only upload .jpg or .bmp files." & "<BR>" & "<BR>"
End if
Else
File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
f1=File.fileName
End If
Next
End if
fnm="/senate/legislation/"&f1
imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
'imgop="callFunction('1','"&fnm&"',"");"
Response.write imgop
%>
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
</script>
Let try this..
Update :
To set data :
Create instance First::
var editor = CKEDITOR.instances['editor1'];
Then,
editor.setData('your data');
or
editor.insertHtml('your html data');
or
editor.insertText('your text data');
And Retrieve data from your editor::
editor.getData();
If change the particular para HTML data in CKEditor.
var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');
These are the possible ways that I know in CKEditor
If you use Drupal AND the module called "WYSIWYG" with the CKEditor library, then the following workaround could be a solution. For me it works like a charm. I use CKEditor 4.4.5 and WYSIWYG 2.2 in Drupal 7.33. I found this workaround here: https://www.drupal.org/node/1956778.
Here it is: I create a custom module and put the following code in the ".module" file:
<?php
/**
* Implements hook_wysiwyg_editor_settings_alter().
*/
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
if ($context['profile']->editor == 'ckeditor') {
$settings['allowedContent'] = TRUE;
}
}
?>
I hope this help other Drupal users.
MAKE THIS YOUR config.js file code
CKEDITOR.editorConfig = function( config ) {
// config.enterMode = 2; //disabled <p> completely
config.enterMode = CKEDITOR.ENTER_BR; // pressing the ENTER KEY input <br/>
config.shiftEnterMode = CKEDITOR.ENTER_P; //pressing the SHIFT + ENTER KEYS input <p>
config.autoParagraph = false; // stops automatic insertion of <p> on focus
};
To get data of ckeditor, you need to get ckeditor instance
HTML code:
<textarea class="form-control" id="reply_mail_msg" name="message" rows="3" data-form-field="Message" placeholder="" autofocus="" style="display: none;"></textarea>
Javascript:
var ck_ed = CKEDITOR.instances.reply_mail_msg.getData();
If you don't want to have to buy CKFinder, like I didn't want to buy CKFinder, then I wrote a very reliable uploader for CKEditor 4. It consists of a second form, placed immediately above your textarea form, and utilizes the iframe hack, which, in spite of its name, is seamless and unobtrusive.
After the image is successfully uploaded, it will appear in your CKEditor window, along with whatever content is already there.
editor.php (the form page):
<?php
set_time_limit ( 3600 )
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Content Editor</title>
<link href="jquery-ui-1.10.2/themes/vader/ui.dialog.css" rel="stylesheet" media="screen" id="dialog_ui" />
<link href="jquery-ui-1.10.2/themes/vader/jquery-ui.css" rel="stylesheet" media="screen" id="dialog_ui" />
<script src="jquery-ui-1.10.2/jquery-1.9.1.js"></script>
<script src="jquery-ui-1.10.2/jquery.form.js"></script>
<script src="jquery-ui-1.10.2/ui/jquery-ui.js"></script>
<script src="ckeditor/ckeditor.js"></script>
<script src="ckeditor/config.js"></script>
<script src="ckeditor/adapters/jquery.js"></script>
<script src="ckeditor/plugin2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#editor').ckeditor({ height: 400, width:600});
});
function placePic(){
function ImageExist(url){
var img = new Image();
img.src = url;
return img.height != 0;
}
var filename = document.forms['uploader']['uploadedfile'].value;
document.forms['uploader']['filename'].value = filename;
var url = 'http://www.mydomain.com/external/images/cms/'+filename;
document.getElementById('uploader').submit();
var string = CKEDITOR.instances.editor.getData();
var t = setInterval(function(){
var exists = ImageExist(url);
if(exists === true){
if(document.getElementById('loader')){
document.getElementById('loader').parentNode.removeChild(document.getElementById('loader'));
}
CKEDITOR.instances.editor.setData(string + "<img src=\""+url+"\" />");
clearInterval(t);
}
else{
if(! document.getElementById("loader")){
var loader = document.createElement("div");
loader.setAttribute("id","loader");
loader.setAttribute("style","position:absolute;margin:-300px auto 0px 240px;width:113px;height:63px;text-align:center;z-index:10;");
document.getElementById('formBox').appendChild(loader);
var loaderGif = document.createElement("img");
loaderGif.setAttribute("id","loaderGif");
loaderGif.setAttribute("style","width:113px;height:63px;text-align:center;");
loaderGif.src = "external/images/cms/2dumbfish.gif";
document.getElementById('loader').appendChild(loaderGif);
}
}
},100);
}
function loadContent(){
if(document.forms['editorform']['site'].value !== "" && document.forms['editorform']['page'].value !== ""){
var site = document.forms['editorform']['site'].value;
var page = document.forms['editorform']['page'].value;
var url = site+"/"+page+".html";
$.ajax({
type: "GET",
url: url,
dataType: 'html',
success: function (html) {
CKEDITOR.instances.editor.setData(html);
}
});
}
}
</script>
<style>
button{
width: 93px;
height: 28px;
border:none;
padding: 0 4px 8px 0;
font-weight:bold
}
#formBox{
width:50%;
margin:10px auto 0px auto;
font-family:Tahoma, Geneva, sans-serif;
font-size:12px;
}
#field{
position:absolute;
top:10px;
margin-left:300px;
margin-bottom:20px;
}
#target{
position:absolute;
top:100px;
left:100px;
width:400px;
height:100px;
display:none;
}
.textField{
padding-left: 1px;
border-style: solid;
border-color: black;
border-width: 1px;
font-family: helvetica, arial, sans serif;
padding-left: 1px;
}
#report{
float:left;
margin-left:20px;
margin-top:10px;
font-family: helvetica, arial, sans serif;
font-size:12px;
color:#900;
}
</style>
</head>
<body>
<?php
if(isset($_GET['r'])){ ?><div id="report">
<?php echo $_GET['r']; ?> is changed.
</div><?php
}
?>
<div id="formBox">
<form id="uploader" name="uploader" action="editaction.php" method="post" target="target" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
<input type="hidden" name="filename" value="" />
Insert image: <input name="uploadedfile" type="file" class="textField" onchange="placePic();return false;" />
</form>
<form name="editorform" id="editorform" method="post" action="editaction.php" >
<div id="field" >Site: <select name="site" class="textField" onchange="loadContent();return false;">
<option value=""></option>
<option value="scubatortuga">scubatortuga</option>
<option value="drytortugascharters">drytortugascharters</option>
<option value="keyscombo">keyscombo</option>
<option value="keywesttreasurehunters">keywesttreasurehunters</option>
<option value="spearfishkeywest">spearfishkeywest</option>
</select>
Page: <select name="page" class="textField" onchange="loadContent();return false;">
<option value=""></option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>
</div><br />
<textarea name="editor" id="editor"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<iframe name="target" id="target"></iframe>
</body>
</html>
And here is the action page, editaction.php, which does the actual file upload:
<?php
//editaction.php
foreach($_POST as $k => $v){
${"$k"} = $v;
}
//fileuploader.php
if($_FILES){
$target_path = "external/images/cms/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(! file_exists("$target_path$filename")){
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
}
}
else{
$string = stripslashes($editor);
$filename = "$site/$page.html";
$handle = fopen($filename,"w");
fwrite($handle,$string,strlen($string));
fclose($handle);
header("location: editor.php?r=$filename");
}
?>
In case anybody is interested, I wrote a solution for this using Prototype. In order to get the button to appear correctly, I had to specify extraPlugins: 'ajaxsave'
from inside the CKEDITOR.replace()
method call.
Here is the plugin.js:
CKEDITOR.plugins.add('ajaxsave',
{
init: function(editor)
{
var pluginName = 'ajaxsave';
editor.addCommand( pluginName,
{
exec : function( editor )
{
new Ajax.Request('ajaxsave.php',
{
method: "POST",
parameters: { filename: 'index.html', editor: editor.getData() },
onFailure: function() { ThrowError("Error: The server has returned an unknown error"); },
on0: function() { ThrowError('Error: The server is not responding. Please try again.'); },
onSuccess: function(transport) {
var resp = transport.responseText;
//Successful processing by ckprocess.php should return simply 'OK'.
if(resp == "OK") {
//This is a custom function I wrote to display messages. Nicer than alert()
ShowPageMessage('Changes have been saved successfully!');
} else {
ShowPageMessage(resp,'10');
}
}
});
},
canUndo : true
});
editor.ui.addButton('ajaxsave',
{
label: 'Save',
command: pluginName,
className : 'cke_button_save'
});
}
});
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
with hablar::convert
To easily convert multiple columns to different data types you can use hablar::convert
. Simple syntax: df %>% convert(num(a))
converts the column a from df to numeric.
Detailed example
Lets convert all columns of mtcars
to character.
df <- mtcars %>% mutate_all(as.character) %>% as_tibble()
> df
# A tibble: 32 x 11
mpg cyl disp hp drat wt qsec vs am gear carb
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 21 6 160 110 3.9 2.62 16.46 0 1 4 4
2 21 6 160 110 3.9 2.875 17.02 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
With hablar::convert
:
library(hablar)
# Convert columns to integer, numeric and factor
df %>%
convert(int(cyl, vs),
num(disp:wt),
fct(gear))
results in:
# A tibble: 32 x 11
mpg cyl disp hp drat wt qsec vs am gear carb
<chr> <int> <dbl> <dbl> <dbl> <dbl> <chr> <int> <chr> <fct> <chr>
1 21 6 160 110 3.9 2.62 16.46 0 1 4 4
2 21 6 160 110 3.9 2.88 17.02 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
4 21.4 6 258 110 3.08 3.22 19.44 1 0 3 1
Sometimes, a row contain double quote column. When csv reader try read this row, not understood end of column and fire this raise. Solution is below:
reader = csv.reader(cf, quoting=csv.QUOTE_MINIMAL)
<div>
<div style="float:left;width:45%;" >
<span>source list</span>
<select size="10">
<option />
<option />
<option />
</select>
</div>
<div style="float:right;width:45%;">
<span>destination list</span>
<select size="10">
<option />
<option />
<option />
</select>
</div>
<div style="clear:both; font-size:1px;"></div>
</div>
Clear must be used so as to prevent the float bug (height warping of outer Div).
style="clear:both; font-size:1px;
Like it's written up there, you forget to type #include <sstream>
#include <sstream>
using namespace std;
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
You can also use some other ways to convert int
to string
, like
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
check this!
Yes, you can use jQuery to make this done, the idea is
Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.
<form name="input" action="handle_email.php" method="post">
<input type="hidden" name="email" id="email" />
<input type="submit" value="Submit" />
</form>
<script>
$("form").submit(function() {
var emailFromOtherTextBox = $("#email_textbox").val();
$("#email").val(emailFromOtherTextBox );
return true;
});
</script>
also see http://api.jquery.com/submit/
Add the below to your global.asax for JSON serialization of c# enum as string
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
(new Newtonsoft.Json.Converters.StringEnumConverter());
Use strtotime to convert any date to unix timestamp and compare.
If you use "format-table" you can use -hidetableheaders
Just a word of caution. If you are trying to open an existing JKS keystore in Java 9 onwards, you need to make sure you mention the following properties too with value as "JKS":
javax.net.ssl.keyStoreType
javax.net.ssl.trustStoreType
The reason being that the default keystore type as prescribed in java.security file has been changed to pkcs12 from jks from Java 9 onwards.
I'm new to flutter. I found that one can also achieve it this way.
tabs: [
for (var title in movieTitles) Tab(text: title)
]
Note: It requires dart sdk version to be >= 2.3.0, see here
This table shows the difference. protected internal
is the same as protected
, except it also allows access from other classes in the same assembly.
Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.
When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.
>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False
It is very friendly framework for Notification Area Application... it is enough to add NotificationIcon to base form and change auto-generated code to code below:
public partial class Form1 : Form
{
private bool hidden = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ShowInTaskbar = false;
//this.WindowState = FormWindowState.Minimized;
this.Hide();
hidden = true;
}
private void notifyIcon1_Click(object sender, EventArgs e)
{
if (hidden) // this.WindowState == FormWindowState.Minimized)
{
// this.WindowState = FormWindowState.Normal;
this.Show();
hidden = false;
}
else
{
// this.WindowState = FormWindowState.Minimized;
this.Hide();
hidden = true;
}
}
}
If you are using java-8 there's also another way to do this.
int[] arr = list.stream().mapToInt(i -> i).toArray();
What it does is:
Stream<Integer>
from the listIntStream
by mapping each element to itself (identity function), unboxing the int
value hold by each Integer
object (done automatically since Java 5)int
by calling toArray
You could also explicitly call intValue
via a method reference, i.e:
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
It's also worth mentioning that you could get a NullPointerException
if you have any null
reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:
//.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();
Example:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]
list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]
You just add one additional row before you execute the loop. This row contains your CSV file header name.
schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
writer.writerow([g for g in schema])
#Data add in csv file
for x in xrange(rows):
writer.writerow([g() for g in generators])
Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).
I'm adding an answer-for-noobs because these answers seemed over my head, until I realized how simple it is. Sometimes it's your expectation that it's complicated that makes you unable to 'wrap your head around it'.
I didn't need to understand the difference until I walked into a really annoying 'bug' trying to use LINQ-to-SQL generically:
public IEnumerable<T> Get(Func<T, bool> conditionLambda){
using(var db = new DbContext()){
return db.Set<T>.Where(conditionLambda);
}
}
This worked great until I started getting OutofMemoryExceptions on larger datasets. Setting breakpoints inside the lambda made me realize that it was iterating through each row in my table one-by-one looking for matches to my lambda condition. This stumped me for a while, because why the heck is it treating my data table as a giant IEnumerable instead of doing LINQ-to-SQL like it's supposed to? It was also doing the exact same thing in my LINQ-to-MongoDb counterpart.
The fix was simply to turn Func<T, bool>
into Expression<Func<T, bool>>
, so I googled why it needs an Expression
instead of Func
, ending up here.
An expression simply turns a delegate into a data about itself. So a => a + 1
becomes something like "On the left side there's an int a
. On the right side you add 1 to it." That's it. You can go home now. It's obviously more structured than that, but that's essentially all an expression tree really is--nothing to wrap your head around.
Understanding that, it becomes clear why LINQ-to-SQL needs an Expression
, and a Func
isn't adequate. Func
doesn't carry with it a way to get into itself, to see the nitty-gritty of how to translate it into a SQL/MongoDb/other query. You can't see whether it's doing addition or multiplication or subtraction. All you can do is run it. Expression
, on the other hand, allows you to look inside the delegate and see everything it wants to do. This empowers you to translate the delegate into whatever you want, like a SQL query. Func
didn't work because my DbContext was blind to the contents of the lambda expression. Because of this, it couldn't turn the lambda expression into SQL; however, it did the next best thing and iterated that conditional through each row in my table.
Edit: expounding on my last sentence at John Peter's request:
IQueryable extends IEnumerable, so IEnumerable's methods like Where()
obtain overloads that accept Expression
. When you pass an Expression
to that, you keep an IQueryable as a result, but when you pass a Func
, you're falling back on the base IEnumerable and you'll get an IEnumerable as a result. In other words, without noticing you've turned your dataset into a list to be iterated as opposed to something to query. It's hard to notice a difference until you really look under the hood at the signatures.
You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.
You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig
. It will give out some information and your local IP should look like 192.168.1.x.
Try:
sheet 2 a1 =vlookup(sheet2a1,sheet1$a$1:$b$6,2)
Then drag it down.
It should work.
It seems that nobody has mentioned SDK man (https://sdkman.io/) yet.
SKD man allows installing multiple versions of Java on Mac and easy switching between these versions. More information is available at https://sdkman.io/usage.
For example:
$ sdk list java
================================================================================
Available Java Versions
================================================================================
* 12.ea.20-open
11.0.1-zulu
> * 11.0.1-open
10.0.2-zulu
10.0.2-open
9.0.7-zulu
9.0.4-open
8.0.192-zulu
8.0.191-oracle
+ 8.0.181-oracle
7.0.181-zulu
1.0.0-rc-10-grl
1.0.0-rc-9-grl
1.0.0-rc-8-grl
================================================================================
+ - local version
* - installed
> - currently in use
================================================================================
$ sdk install java 8.0.191-oracle
$ sdk use java 8.0.191-oracle
Using java version 8.0.191-oracle in this shell.
$ java -version
java version "1.8.0_191"
Java(TM) SE Runtime Environment (build 1.8.0_191-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)
$ sdk use java 11.0.1-open
Using java version 11.0.1-open in this shell.
$ java -version openjdk version "11.0.1" 2018-10-16
OpenJDK Runtime Environment 18.9 (build 11.0.1+13)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.1+13, mixed mode)
```
The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a>
tag:
<Tooltip title="Node.js" >
<a>
<FontAwesomeIcon icon={faNode} size="2x" />
</a>
</Tooltip>
you just provide one <folder>
argument to npm install
, argument should point toward the local folder instead of the package name:
npm install /path
While I agree with the results given, they didn't work for me. If your Table has a name this will work:
Public Sub GetCountOfResults(WorkSheetName As String, TableName As String)
Dim rnData As Range
Dim rngArea As Range
Dim lCount As Long
Set rnData = ThisWorkbook.Worksheets(WorkSheetName).ListObjects(TableName).Range
With rnData
For Each rngArea In .SpecialCells(xlCellTypeVisible).Areas
lCount = lCount + rngArea.Rows.Count
Next
MsgBox "Autofilter " & lCount - 1 & " records"
End With
Set rnData = Nothing
lCount = Empty
End Sub
This is modified to work with ListObjects from an original version I found here:
Fairly new to using PowerShell, think I might be able to help. Could you try this?
I believe you're not getting the correct parameters to your script block:
param([string]$one, [string]$two)
$res = Invoke-Command -Credential $migratorCreds -ScriptBlock {Get-LocalUsers -parentNodeXML $args[0] -migratorUser $args[1] } -ArgumentList $xmlPRE, $migratorCreds
$setPristine() was introduced in the 1.1.x branch of angularjs. You need to use that version rather than 1.0.7 in order for it to work.
let i: Int = 20
func getTypeName(v: Any) -> String {
let fullName = _stdlib_demangleName(_stdlib_getTypeName(i))
if let range = fullName.rangeOfString(".") {
return fullName.substringFromIndex(range.endIndex)
}
return fullName
}
println("Var type is \(getTypeName(i)) = \(i)")
Make an object
$obj = json_decode(json_encode($need_to_json));
Show data from this $obj
$obj->{'needed'};
Base URL in JavaScript
Here is simple function for your project to get base URL in JavaScript.
// base url
function base_url() {
var pathparts = location.pathname.split('/');
if (location.host == 'localhost') {
var url = location.origin+'/'+pathparts[1].trim('/')+'/'; // http://localhost/myproject/
}else{
var url = location.origin; // http://stackoverflow.com
}
return url;
}
To have a query working in any locale settings, consider formatting the date yourself:
SELECT *
FROM testbed
WHERE start_date >= to_date('2012-01-01','YYYY-MM-DD')
AND end_date <= to_date('2012-04-13','YYYY-MM-DD');
There are two things I think you could try to develop iPhone applications.
You can try the Aptana mobile wep app plugin for eclipse which is nice, although still in early stage. It comes with a emulator for running the applications so this could be helpful
You can try cocoa
(Extra) Here is a nice guide I found of guy who managed to get the iPhone SDK running in ubuntu, hope this help -_-. iPhone on Ubuntu
After nine years I thought it was time to bring a new version. Here are my two (and now one) favourites.
Margin
Set margin
to auto
. You should know the direction sequence is margin: *top* *right* *bottom* *left*;
or margin: *top&bottom* *left&right*
aside{_x000D_
display: block;_x000D_
width: 50px;_x000D_
height: 100px;_x000D_
background-color: green;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
article{_x000D_
height: 100px;_x000D_
margin: 0 0 0 50px; /* 50px aside width */_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
div{_x000D_
margin: 0 auto;_x000D_
display:block;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background-color: blue;_x000D_
color: white;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<aside>_x000D_
</aside>_x000D_
<article> _x000D_
<div>The div</div>_x000D_
</article>_x000D_
</body>_x000D_
</html>
_x000D_
Center: Depricated, don't use this!
Use <center></center>
tags as a wrap around your <div></div>
.
Example:
aside{_x000D_
display:block;_x000D_
background-color:green;_x000D_
width: 50px;_x000D_
height: 100px;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
center{_x000D_
display:block;_x000D_
background-color:grey;_x000D_
height: 100px;_x000D_
margin-left: 50px; /* Width of the aside */_x000D_
}_x000D_
_x000D_
div{_x000D_
display:block; _x000D_
width: 60px; _x000D_
height: 60px; _x000D_
background-color:blue;_x000D_
color: white;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<aside>_x000D_
</aside>_x000D_
<article>_x000D_
<center>_x000D_
<div>The div</div>_x000D_
</center>_x000D_
</article>_x000D_
</body>_x000D_
</html>
_x000D_
To reload a section of the page, you could use jquerys load
with the current url and specify the fragment you need, which would be the same element that load
is called on, in this case #here
:
function updateDiv()
{
$( "#here" ).load(window.location.href + " #here" );
}
+ " #here"
This function can be called within an interval, or attached to a click event
This is a common problem, so here's a relatively thorough illustration.
For non-unicode strings (i.e. those without u
prefix like u'\xc4pple'
), one must decode from the native encoding (iso8859-1
/latin1
, unless modified with the enigmatic sys.setdefaultencoding
function) to unicode
, then encode to a character set that can display the characters you wish, in this case I'd recommend UTF-8
.
First, here is a handy utility function that'll help illuminate the patterns of Python 2.7 string and unicode:
>>> def tell_me_about(s): return (type(s), s)
>>> v = "\xC4pple" # iso-8859-1 aka latin1 encoded string
>>> tell_me_about(v)
(<type 'str'>, '\xc4pple')
>>> v
'\xc4pple' # representation in memory
>>> print v
?pple # map the iso-8859-1 in-memory to iso-8859-1 chars
# note that '\xc4' has no representation in iso-8859-1,
# so is printed as "?".
>>> uv = v.decode("iso-8859-1")
>>> uv
u'\xc4pple' # decoding iso-8859-1 becomes unicode, in memory
>>> tell_me_about(uv)
(<type 'unicode'>, u'\xc4pple')
>>> print v.decode("iso-8859-1")
Äpple # convert unicode to the default character set
# (utf-8, based on sys.stdout.encoding)
>>> v.decode('iso-8859-1') == u'\xc4pple'
True # one could have just used a unicode representation
# from the start
>>> u"Ä" == u"\xc4"
True # the native unicode char and escaped versions are the same
>>> "Ä" == u"\xc4"
False # the native unicode char is '\xc3\x84' in latin1
>>> "Ä".decode('utf8') == u"\xc4"
True # one can decode the string to get unicode
>>> "Ä" == "\xc4"
False # the native character and the escaped string are
# of course not equal ('\xc3\x84' != '\xc4').
>>> u8 = v.decode("iso-8859-1").encode("utf-8")
>>> u8
'\xc3\x84pple' # convert iso-8859-1 to unicode to utf-8
>>> tell_me_about(u8)
(<type 'str'>, '\xc3\x84pple')
>>> u16 = v.decode('iso-8859-1').encode('utf-16')
>>> tell_me_about(u16)
(<type 'str'>, '\xff\xfe\xc4\x00p\x00p\x00l\x00e\x00')
>>> tell_me_about(u8.decode('utf8'))
(<type 'unicode'>, u'\xc4pple')
>>> tell_me_about(u16.decode('utf16'))
(<type 'unicode'>, u'\xc4pple')
>>> print u8
Äpple # printing utf-8 - because of the encoding we now know
# how to print the characters
>>> print u8.decode('utf-8') # printing unicode
Äpple
>>> print u16 # printing 'bytes' of u16
???pple
>>> print u16.decode('utf16')
Äpple # printing unicode
>>> v == u8
False # v is a iso8859-1 string; u8 is a utf-8 string
>>> v.decode('iso8859-1') == u8
False # v.decode(...) returns unicode
>>> u8.decode('utf-8') == v.decode('latin1') == u16.decode('utf-16')
True # all decode to the same unicode memory representation
# (latin1 is iso-8859-1)
>>> u8.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
>>> u16.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)
>>> v.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0:
ordinal not in range(128)
One would get around these by converting from the specific encoding (latin-1, utf8, utf16) to unicode e.g. u8.decode('utf8').encode('latin1')
.
So perhaps one could draw the following principles and generalizations:
str
is a set of bytes, which may have one of a number of encodings such as Latin-1, UTF-8, and UTF-16unicode
is a set of bytes that can be converted to any number of encodings, most commonly UTF-8 and latin-1 (iso8859-1)print
command has its own logic for encoding, set to sys.stdout.encoding
and defaulting to UTF-8str
to unicode before converting to another encoding.Of course, all of this changes in Python 3.x.
Hope that is illuminating.
And the very illustrative rants by Armin Ronacher:
First off, it's helpful to create a database named the same as your current use, to prevent the error when you just want to use the default database and create new tables without declaring the name of a db explicitly.
Replace "skynotify" with your username:
psql -d postgres -c "CREATE DATABASE skynotify ENCODING 'UTF-8';"
-d explicitly declares which database to use as the default for SQL statements that don't explicitly include a db name during this interactive session.
BASICS FOR GETTING A CLEAR PICTURE OF WHAT YOUR PostgresQL SERVER has in it.
You must connect to an existing database to use psql interactively. Fortunately, you can ask psql for a list of databases:
psql -l
.
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
----------------------------------+-----------+----------+-------------+-------------+-------------------
skynotify | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
myapp_dev | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
ruby-getting-started_development | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify +
| | | | | skynotify=CTc/skynotify
template1 | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify +
| | | | | skynotify=CTc/skynotify
(6 rows)
This does NOT start the interactive console, it just outputs a text based table to the terminal.
As another answers says, postgres is always created, so you should use it as your failsafe database when you just want to get the console started to work on other databases. If it isn't there, then list the databases and then use any one of them.
In a similar fashion, select tables from a database:
psql -d postgres -c "\dt;"
My "postgres" database has no tables, but any database that does will output a text based table to the terminal (standard out).
And for completeness, we can select all rows from a table too:
psql -d ruby-getting-started_development -c "SELECT * FROM widgets;"
.
id | name | description | stock | created_at | updated_at
----+------+-------------+-------+------------+------------
(0 rows)
Even if there are zero rows returned, you'll get the field names.
If your tables have more than a dozen rows, or you're not sure, it'll be more useful to start with a count of rows to understand how much data is in your database:
psql -d ruby-getting-started_development -c "SELECT count(*) FROM widgets;"
.
count
-------
0
(1 row)
And don't that that "1 row" confuse you, it just represents how many rows are returned by the query, but the 1 row contains the count you want, which is 0 in this example.
NOTE: a db created without an owner defined will be owned by the current user.
Use the %02X
format parameter:
printf("%02X",word[i]);
More info can be found here: http://www.cplusplus.com/reference/cstdio/printf/
Have you tried it without the ANSI join ?
CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.* FROM TPM_PROJECTVERSION V,TPM_PROJECT P
WHERE P.PROJECTID = V.PROJECTID
In addition to the locations listed above, the OS X version of Perl also has two more ways:
The /Library/Perl/x.xx/AppendToPath file. Paths listed in this file are appended to @INC at runtime.
The /Library/Perl/x.xx/PrependToPath file. Paths listed in this file are prepended to @INC at runtime.
If Age and Palt are columns in the same Table, you can count(*) all tasks and sum only late ones like this:
select ks,
count(*) tasks,
sum(case when Age > Palt then 1 end) late
from Table
group by ks
SELECT DATE_FORMAT(NOW() - INTERVAL FLOOR(RAND() * 14) DAY,'%Y-%m-%d');
This one can be used to get date in 'yyyy-mm-dd' format.
import os
def fs_tree_to_dict(path_):
file_token = ''
for root, dirs, files in os.walk(path_):
tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs}
tree.update({f: file_token for f in files})
return tree # note we discontinue iteration trough os.walk
If anybody is interested - that recursive function returns nested structure of dictionaries. Keys are file system
names (of directories and files), values are either:
file_token
)The strings designating files are empty in this example. They can also be e.g. given file contents or its owner info or privileges or whatever object different than a dict. Unless it's a dictionary it can be easily distinguished from a "directory type" in further operations.
Having such a tree in a filesystem:
# bash:
$ tree /tmp/ex
/tmp/ex
+-- d_a
¦ +-- d_a_a
¦ +-- d_a_b
¦ ¦ +-- f1.txt
¦ +-- d_a_c
¦ +-- fa.txt
+-- d_b
¦ +-- fb1.txt
¦ +-- fb2.txt
+-- d_c
The result will be:
# python 2 or 3:
>>> fs_tree_to_dict("/tmp/ex")
{
'd_a': {
'd_a_a': {},
'd_a_b': {
'f1.txt': ''
},
'd_a_c': {},
'fa.txt': ''
},
'd_b': {
'fb1.txt': '',
'fb2.txt': ''
},
'd_c': {}
}
If you like that, I've already created a package (python 2 & 3) with this stuff (and a nice pyfakefs
helper):
https://pypi.org/project/fsforge/
It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.
template < typename ... >
class MyClass
{
int myMethod()
{
// Not just declaration. Add method implementation here
}
};
Just delete the ${user.home}/.m2/repository/org/apache/maven/archetypes to refresh all files needed, it worked fine to me!
Try this:
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Tempo"
End Sub
Or use a With
clause to avoid repeatedly calling out your object
Private Sub CreateSheet()
Dim ws As Worksheet
With ThisWorkbook
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
ws.Name = "Tempo"
End With
End Sub
Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.
Sub CreateSheet()
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
End With
End Sub
You can read existing sheets of your interests, for example, 'x1', 'x2', into memory and 'write' them back prior to adding more new sheets (keep in mind that sheets in a file and sheets in memory are two different things, if you don't read them, they will be lost). This approach uses 'xlsxwriter' only, no openpyxl involved.
import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
# begin <== read selected sheets and write them back
df1 = pd.read_excel(path, sheet_name='x1', index_col=0) # or sheet_name=0
df2 = pd.read_excel(path, sheet_name='x2', index_col=0) # or sheet_name=1
writer = pd.ExcelWriter(path, engine='xlsxwriter')
df1.to_excel(writer, sheet_name='x1')
df2.to_excel(writer, sheet_name='x2')
# end ==>
# now create more new sheets
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
df3.to_excel(writer, sheet_name='x3')
df4.to_excel(writer, sheet_name='x4')
writer.save()
writer.close()
If you want to preserve all existing sheets, you can replace above code between begin and end with:
# read all existing sheets and write them back
writer = pd.ExcelWriter(path, engine='xlsxwriter')
xlsx = pd.ExcelFile(path)
for sheet in xlsx.sheet_names:
df = xlsx.parse(sheet_name=sheet, index_col=0)
df.to_excel(writer, sheet_name=sheet)
for select2 v4.0.0 slightly different
$(".itemSearch").select2({
tags: true,
multiple: true,
tokenSeparators: [',', ' '],
minimumInputLength: 2,
minimumResultsForSearch: 10,
ajax: {
url: URL,
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.tag_value,
id: item.tag_id
}
})
};
}
}
});
I assume you are using gcc
, to simply link object files do:
$ gcc -o output file1.o file2.o
To get the object-files simply compile using
$ gcc -c file1.c
this yields file1.o and so on.
If you want to link your files to an executable do
$ gcc -o output file1.c file2.c
Just note that this commands can be very destructive. If more people are working on the repo they'll all have to pull the new tree. The three middle commands are not necessary if your goal is NOT to reduce the size. Because the filter branch creates a backup of the removed file and it can stay there for a long time.
$ git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch YOURFILENAME" HEAD
$ rm -rf .git/refs/original/
$ git reflog expire --all
$ git gc --aggressive --prune
$ git push origin master --force
Seems like already a lot of people answers this question.
in Swift 3.0, single line comment is to put double forward slashes upfront : "//" ; multiline is put "/* .... */".
Hope this helps.
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
I know this is an old question, but I have just had a similar problem and I think what I did would work for you too.
I used the to_csv() method and wrote to stdout:
import sys
paramdata.to_csv(sys.stdout)
This should dump the whole dataframe whether it's nicely-printable or not, and you can use the to_csv parameters to configure column separators, whether the index is printed, etc.
Edit: It is now possible to use None
as the target for .to_csv()
with similar effect, which is arguably a lot nicer:
paramdata.to_csv(None)
For an updated answer you can build a forEach
function in Python easily:
def forEach(list, function):
for i, v in enumerate(list):
function(v, i, list)
You could also adapt this to map
, reduce
, filter
, and any other array functions from other languages or precedence you'd want to bring over. For loops are fast enough, but the boiler plate is longer than forEach
or the other functions. You could also extend list to have these functions with a local pointer to a class so you could call them directly on lists as well.
For newer version of laravel:
composer create-project --prefer-dist laravel/laravel=5.5.* project_name
I had the same problem in my JSF application which was having a comment line containing some special characters in the XMHTL page. When I compared the previous version in my eclipse it had a comment,
//Some ? ? special characters found
Removed those characters and the page loaded fine. Mostly it is related to XML files, so please compare it with the working version.
It sounds like your response is being evaluated somehow. This gives the same error in Chrome:
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
This is due to the braces '{...}' being interpreted by javascript as a code block and not an object literal as one might expect.
I would look at the JSON.decode() function and see if there is an eval in there.
Similar issue here: Eval() = Unexpected token : error
http://maps.googleapis.com/maps/api/geocode/OUTPUT?address=YOUR_LOCATION&sensor=true
OUTPUT = json or xml;
for detail information about google map api go through url:
http://code.google.com/apis/maps/documentation/geocoding/index.html
Hope this will help
This one has parametrized ip, port, timeout in seconds, handle connection errors and give you connection time in milliseconds:
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char **argv) {
struct sockaddr_in addr_s;
char *addr;
short int fd=-1;
int port;
fd_set fdset;
struct timeval tv;
int rc;
int so_error;
socklen_t len;
struct timespec tstart={0,0}, tend={0,0};
int seconds;
if (argc != 4) {
fprintf(stderr, "Usage: %s <ip> <port> <timeout_seconds>\n", argv[0]);
return 1;
}
addr = argv[1];
port = atoi(argv[2]);
seconds = atoi(argv[3]);
addr_s.sin_family = AF_INET; // utilizzo IPv4
addr_s.sin_addr.s_addr = inet_addr(addr);
addr_s.sin_port = htons(port);
clock_gettime(CLOCK_MONOTONIC, &tstart);
fd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(fd, F_SETFL, O_NONBLOCK); // setup non blocking socket
// make the connection
rc = connect(fd, (struct sockaddr *)&addr_s, sizeof(addr_s));
if ((rc == -1) && (errno != EINPROGRESS)) {
fprintf(stderr, "Error: %s\n", strerror(errno));
close(fd);
return 1;
}
if (rc == 0) {
// connection has succeeded immediately
clock_gettime(CLOCK_MONOTONIC, &tend);
printf("socket %s:%d connected. It took %.5f seconds\n",
addr, port, (((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec)));
close(fd);
return 0;
} /*else {
// connection attempt is in progress
} */
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
tv.tv_sec = seconds;
tv.tv_usec = 0;
rc = select(fd + 1, NULL, &fdset, NULL, &tv);
switch(rc) {
case 1: // data to read
len = sizeof(so_error);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
clock_gettime(CLOCK_MONOTONIC, &tend);
printf("socket %s:%d connected. It took %.5f seconds\n",
addr, port, (((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec)));
close(fd);
return 0;
} else { // error
printf("socket %s:%d NOT connected: %s\n", addr, port, strerror(so_error));
}
break;
case 0: //timeout
fprintf(stderr, "connection timeout trying to connect to %s:%d\n", addr, port);
break;
}
close(fd);
return 0;
}
Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.
They're all similar in that they're essentially zip files containing the actual file components. You can see the contents just by replacing the extension with .zip and opening them up. The difference with xlsb seems to be that the components are not XML-based but are in a binary format: supposedly this is beneficial when working with large files.
https://blogs.msdn.microsoft.com/dmahugh/2006/08/22/new-binary-file-format-for-spreadsheets/
The answers given here does not return the correct object type, hence I created these methods below. They also fail if you try to add more fields to the class that does not exist in the given JSON:
def dict_to_class(class_name: Any, dictionary: dict) -> Any:
instance = class_name()
for key in dictionary.keys():
setattr(instance, key, dictionary[key])
return instance
def json_to_class(class_name: Any, json_string: str) -> Any:
dict_object = json.loads(json_string)
return dict_to_class(class_name, dict_object)
To angular version 4, you can use this:
this.heroForm.reset();
But, you could need a initial value like:
ngOnChanges() {
this.heroForm.reset({
name: this.hero.name, //Or '' to empty initial value.
address: this.hero.addresses[0] || new Address()
});
}
It is important to resolve null problem in your object reference.
reference link, Search for "reset the form flags".
At our shop, I introduced the convention of adding recognizably named annotated tags to commits with incorrect messages, and using the annotation as the replacement.
Even though this doesn't help folks who run casual "git log" commands, it does provide us with a way to fix incorrect bug tracker references in the comments, and all my build and release tools understand the convention.
This is obviously not a generic answer, but it might be something folks can adopt within specific communities. I'm sure if this is used on a larger scale, some sort of porcelain support for it may crop up, eventually...
First of all, when you create ob1
then constructor is called and it starts execution. At that time t.start()
also runs in separate thread. Remember when a new thread is created, it runs parallely to main thread. And thats why main start execution again with next statement.
And Join()
statement is used to prevent the child thread from becoming orphan. Means if you did'nt call join()
in your main class, then main thread will exit after its execution and child thread will be still there executing the statements. Join()
will wait until all child thread complete its execution and then only main method will exit.
Go through this article, helps a lot.
Unfortunately, it the Developer Tools in Chrome seem to be unable to "stop on all errors", as Firebug does.
Instance of a class when compared with == comes to non-equal. The best way is to ass the cmp function to your class which will do the stuff.
If you want to do comparison by the content you can simply use cmp(obj1,obj2)
In your case cmp(doc1,doc2) It will return -1 if the content wise they are same.
These steps worked for me on several Systems using Ubuntu 16.04, Apache 2.4, MariaDB, PDO
log into MYSQL as root
mysql -u root
Grant privileges. To a new user execute:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';
FLUSH PRIVILEGES;
UPDATE for Google Cloud Instances
MySQL on Google Cloud seem to require an alternate command (mind the backticks).
GRANT ALL PRIVILEGES ON `%`.* TO 'newuser'@'localhost';
bind to all addresses:
The easiest way is to comment out the line in your /etc/mysql/mariadb.conf.d/50-server.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf file, depending on what system you are running:
#bind-address = 127.0.0.1
exit mysql and restart mysql
exit
service mysql restart
By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*.
To check the binding of mysql service execute as root:
netstat -tupan | grep mysql
A nuanced variant of some of the answers here that answers the OP's question:
git archive [email protected]:foo/bar.git \
HEAD path/to/file.txt | tar -xO path/to/file.txt > file.txt
Instead of telling you how you could execute a certain command (Esc:wq), I can provide you two links that may help you with VIM:
However, the best way to learn Vim is not only using it for Git commits, but as a regular editor for your everyday work.
If you're not going to switch to Vim, it's nonsense to keep its commands in mind. In that case, go and set up your favourite editor to use with Git.
One option would be to use some sort of streaming server/gateway. I tried various solutions (vlc, ffmpeg and a few more) and the one that worked best for me was Janus WebRTC server. It is somewhat difficult to set up, and you will have to compile it from source(when I tried it the version in Ubuntu repos didn't have RTSP support), but they have detailed compiling instructions and documentation on how to set everything up.
I managed to get video and audio feed from 3 FullHD cameras on local network with very little delay. I can confirm it works with Dahua and Hikvision cameras (not sure if all models).
What I used was Ubuntu Server 18.04 running Apache web server, and Chrome as a browser (it did not work on Firefox by default but perhaps there are workarounds for it).
do while loop, it's flexable and fast and easy to read and write.
auto textRegion = m_pdfTextRegions.begin();
while(textRegion != m_pdfTextRegions.end())
{
if ((*textRegion)->glyphs.empty())
{
m_pdfTextRegions.erase(textRegion);
textRegion = m_pdfTextRegions.begin();
}
else
textRegion++;
}
Pass 65536
to mysql_connect
as 5th parameter.
Example:
$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */)
or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);
DELETE FROM table3 WHERE field6 = 6;
UPDATE table4 SET field7 = 7 WHERE field8 = 8;
INSERT INTO table5
SELECT t6.field11, t6.field12, t7.field13
FROM table6 t6
INNER JOIN table7 t7 ON t7.field9 = t6.field10;
-- etc
");
When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.
For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
SELECT * FROM table2;
");
Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
SELECT * FROM table2;
INSERT INTO table1 (field1,field2) VALUES(1,2);
");
In addition to the other answers (particularly by Lekakis), some string replacements can also be used in the option --log-file=
as elaborated in the Valgrind's user manual.
Four replacements were available at the time of writing:
%p
: Prints the current process ID
valgrind --log-file="myFile-%p.dat" <application-name>
%n
: Prints file sequence number unique for the current process
valgrind --log-file="myFile-%p-%n.dat" <application-name>
%q{ENV}
: Prints contents of the environment variable ENV
valgrind --log-file="myFile-%q{HOME}.dat" <application-name>
%%
: Prints %
valgrind --log-file="myFile-%%.dat" <application-name>
After trial and error I came up with this function, works with iframe too.
function bringElIntoView(el) {
var elOffset = el.offset();
var $window = $(window);
var windowScrollBottom = $window.scrollTop() + $window.height();
var scrollToPos = -1;
if (elOffset.top < $window.scrollTop()) // element is hidden in the top
scrollToPos = elOffset.top;
else if (elOffset.top + el.height() > windowScrollBottom) // element is hidden in the bottom
scrollToPos = $window.scrollTop() + (elOffset.top + el.height() - windowScrollBottom);
if (scrollToPos !== -1)
$('html, body').animate({ scrollTop: scrollToPos });
}
You need to return false;
:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
You can use self.data
in the clean_email
method to access the POST data before validation. It should contain a key called newsletter_sub
or newsletter_unsub
depending on which button was pressed.
# in the context of a django.forms form
def clean(self):
if 'newsletter_sub' in self.data:
# do subscribe
elif 'newsletter_unsub' in self.data:
# do unsubscribe
The loading of a .json
file from harddisk is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
This function works also for loading a .html
or .txt
files, by overriding the mime type parameter to "text/html"
, "text/plain"
etc.
Use delegate
and event.target
. delegate
takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target
is the jQ-normalized property of the event
object representing the object from which the event originated.
$(document).delegate('*', 'click', function (event) {
// event.target is the element
// $(event.target).text() gets its text
});
you cat use it
$(document).on("keypress","input,select",function (e) {
e.preventDefault();
if (e.keyCode==13) {
$(':input:eq(' + ($(':input').index(this) + 1) +')').focus();
}
});
You can try this:
Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);
I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar
from a Date
and just get the month's diff.
Motivation
Many data sets are large enough that we need to concern ourselves with speed/efficiency. So I offer this solution in that spirit. It happens to also be succinct.
For the sake of comparison, let's drop the index
column
df = data_set.drop('index', 1)
Solution
I'll propose the use of zip
and map
list(zip(*map(df.get, df)))
[('2012-02-17', 24.75, 25.03),
('2012-02-16', 25.0, 25.07),
('2012-02-15', 24.99, 25.15),
('2012-02-14', 24.68, 25.05),
('2012-02-13', 24.62, 24.77),
('2012-02-10', 24.38, 24.61)]
It happens to also be flexible if we wanted to deal with a specific subset of columns. We'll assume the columns we've already displayed are the subset we want.
list(zip(*map(df.get, ['data_date', 'data_1', 'data_2'])))
[('2012-02-17', 24.75, 25.03),
('2012-02-16', 25.0, 25.07),
('2012-02-15', 24.99, 25.15),
('2012-02-14', 24.68, 25.05),
('2012-02-13', 24.62, 24.77),
('2012-02-10', 24.38, 24.61)]
Turn's out records
is quickest followed by asymptotically converging zipmap
and iter_tuples
I'll use a library simple_benchmarks
that I got from this post
from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()
import pandas as pd
import numpy as np
def tuple_comp(df): return [tuple(x) for x in df.to_numpy()]
def iter_namedtuples(df): return list(df.itertuples(index=False))
def iter_tuples(df): return list(df.itertuples(index=False, name=None))
def records(df): return df.to_records(index=False).tolist()
def zipmap(df): return list(zip(*map(df.get, df)))
funcs = [tuple_comp, iter_namedtuples, iter_tuples, records, zipmap]
for func in funcs:
b.add_function()(func)
def creator(n):
return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})
@b.add_arguments('Rows in DataFrame')
def argument_provider():
for n in (10 ** (np.arange(4, 11) / 2)).astype(int):
yield n, creator(n)
r = b.run()
Check the results
r.to_pandas_dataframe().pipe(lambda d: d.div(d.min(1), 0))
tuple_comp iter_namedtuples iter_tuples records zipmap
100 2.905662 6.626308 3.450741 1.469471 1.000000
316 4.612692 4.814433 2.375874 1.096352 1.000000
1000 6.513121 4.106426 1.958293 1.000000 1.316303
3162 8.446138 4.082161 1.808339 1.000000 1.533605
10000 8.424483 3.621461 1.651831 1.000000 1.558592
31622 7.813803 3.386592 1.586483 1.000000 1.515478
100000 7.050572 3.162426 1.499977 1.000000 1.480131
r.plot()
The top rated answers are working perfect (a bit old but still working), but I just want to mention that since Android N we all can configure your apps in order to have diff trust SSL certificates (for release , debug only and so on), including Charles SSL Proxy certificate (if you download the Charles certificate and put .pem file in your raw folder). More info can be found here: https://developer.android.com/training/articles/security-config.html
Also the official Charles documentation can be useful to setup this : https://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
Hope this will help to setup Charles inside your app project not on every single Android device.
This one matches all i need in c#:
(?<=(^|,)(?<quote>"?))([^"]|(""))*?(?=\<quote>(?=,|$))
I think, it is redundant. rs.getObject("ID_PARENT")
should return an Integer
object or null
, if the column value actually was NULL
. So it should even be possible to do something like:
if (rs.next()) {
Integer idParent = (Integer) rs.getObject("ID_PARENT");
if (idParent != null) {
iVal = idParent; // works for Java 1.5+
} else {
// handle this case
}
}
There is a method update
on BaseQuery object in SQLAlchemy, which is returned by filter_by
.
num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()
The advantage of using update
over changing the entity comes when there are many objects to be updated.
If you want to give add_user
permission to all the admin
s,
rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user'))
db.session.commit()
Notice that filter_by
takes keyword arguments (use only one =
) as opposed to filter
which takes an expression.
Hi this is due to new version of the jQuery => 1.9.0
you can check the update : http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/
jQuery.Browser is deprecated. you can keep latest version by adding a migration script : http://code.jquery.com/jquery-migrate-1.0.0.js
replace :
<script src="http://code.jquery.com/jquery-latest.js"></script>
by :
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>
in your page and its working.
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
//$("form").submit(function(e){
$("#btn1").click(function(e){
e.preventDefault();
// alert('here');
$(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');
});
//}
});
</script>
</head>
<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file" name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>
<tr><td>Address:</td><td><textarea cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input type="number" maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio" name="r1" value="Male" checked="checked"/>Male<input type="radio" name="r1" value="feale"/>Female</td></tr>
<tr><td><input id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){
move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);
$fname = $_FILES['e5']['name'][$key];
$imgarryimp[]=$fname;
//echo $fname;
if(strlen($fname)>0)
{
$img = $fname;
}
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
}
exit;
// echo $values;exit;
//foreach($_POST['e1'] as $row)
//{
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
//}
//exit;
}
?>
</form>
<table>
<?php
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
del df
will not be deleted if there are any reference to the df
at the time of deletion. So you need to to delete all the references to it with del df
to release the memory.
So all the instances bound to df should be deleted to trigger garbage collection.
Use objgragh to check which is holding onto the objects.
There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.
If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.
You can't do this with enums, but you can do it like that:
public static class SeparatorChars
{
public static string Comma = ",";
public static string Tab = "\t";
public static string Space = " ";
}
A solution by using the new ConstraintLayout
is wrapping the ConstraintLayout
in a LinearLayout
with minHeight and minWidth fixed. Without the wrapping, ConstraintLayout is not getting the right size for the Dialog.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="1000dp"
android:minHeight="1000dp"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background_color"
android:orientation="vertical">
<!-- some constrained views -->
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Option using dplyr
require(dplyr)
dt<-as.data.frame(matrix(runif(10*10),10,10))
dt <- select(dt, -V1, -V2, -V3, -V4)
cor(dt)
LivingRoom.objects.create()
calls LivingRoom.__init__()
- as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Model
subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the default
keyword as explained in the FineManual.
When it comes to float
numbers, you can use format specifiers:
f'{value:{width}.{precision}}'
where:
value
is any expression that evaluates to a numberwidth
specifies the number of characters used in total to display, but if value
needs more space than the width specifies then the additional space is used. precision
indicates the number of characters used after the decimal pointWhat you are missing is the type specifier for your decimal value. In this link, you an find the available presentation types for floating point and decimal.
Here you have some examples, using the f
(Fixed point) presentation type:
# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: ' 5.500'
# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}'
Out[2]: '3001.7'
In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'
# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}'
Out[4]: '7.234'
# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'
You can use opacity:
.image {
background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
width: 58px;
height: 58px;
opacity:0.5;
}
.image:hover{
opacity:1;
}
You can use
"CamelCasedName".tableize.singularize
Or just
"CamelCasedName".underscore
Both options ways will yield "camel_cased_name"
. You can check more details it here.
This is actually a failure of design. You shouldn't be using a return value for anything not a primitive for anything that is not relatively trivial.
The ideal solution should be implemented through a return parameter with a decision on reference/pointer and the proper use of a "const\'y\'ness" as a descriptor.
On top of this, you should realise that the label on an array in C and C++ is effectively a pointer and its subscription are effectively an offset or an addition symbol.
So the label or ptr array_ptr === array label thus returning foo[offset] is really saying return element at memory pointer location foo + offset of type return type.
I faced a similar kind of issue while using a custom object as a key in Treemap. Whenever you are using a custom object as a key in hashmap then you override two function equals and hashcode, However if you are using ContainsKey method of Treemap on this object then you need to override CompareTo method as well otherwise you will be getting this error Someone using a custom object as a key in hashmap in kotlin should do like following
data class CustomObjectKey(var key1:String = "" , var
key2:String = ""):Comparable<CustomObjectKey?>
{
override fun compareTo(other: CustomObjectKey?): Int {
if(other == null)
return -1
// suppose you want to do comparison based on key 1
return this.key1.compareTo((other)key1)
}
override fun equals(other: Any?): Boolean {
if(other == null)
return false
return this.key1 == (other as CustomObjectKey).key1
}
override fun hashCode(): Int {
return this.key1.hashCode()
}
}
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
Try to use:
mvn jacoco:report -debug
to see the details about your reporting process.
I configured my jacoco like this:
<configuration>
<dataFile>~/jacoco.exec</dataFile>
<outputDirectory>~/jacoco</outputDirectory>
</configuration>
Then mvn jacoco:report -debug
shows it using the default configuration, which means jacoco.exec
is not in ~/jacoco.exec
. The error says missing execution data file
.
So just use the default configuration:
<execution>
<id>default-report</id>
<goals>
</goals>
<configuration>
<dataFile>${project.build.directory}/jacoco.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
</configuration>
</execution>
And everything works fine.
Please Try, if use "extends AppCompatActivity" and present actionbar.
ActionBar eksinbar=getSupportActionBar();
if (eksinbar != null) {
eksinbar.setDisplayHomeAsUpEnabled(true);
eksinbar.setHomeAsUpIndicator(R.mipmap.imagexxx);
}
I'm not expert enough in the inner workings of Postgres to know why your query with the double condition in the WHERE
clause be not working. But one way to get around this would be to use a UNION
of the two queries which you know do work:
SELECT * FROM table_name WHERE boolean_column IS NULL
UNION
SELECT * FROM table_name WHERE boolean_column = FALSE
You could also try using COALESCE
:
SELECT * FROM table_name WHERE COALESCE(boolean_column, FALSE) = FALSE
This second query will replace all NULL
values with FALSE
and then compare against FALSE
in the WHERE
condition.
Having tested, the solutions posted above by various, including chaos, to hide elements do now work in the latest versions of Firefox (66.0.4), Chrome (74.0.3729.169) and Edge (42.17134.1.0)
$("#edit-field-service-sub-cat-value option[value=" + title + "]").hide();
$("#edit-field-service-sub-cat-value option[value=" + title + "]").show();
For IE, this does not work, however you can disable the option
$("#edit-field-service-sub-cat-value option[value=" + title + "]").attr("disabled", "disabled");
$("#edit-field-service-sub-cat-value option[value=" + title + "]").removeAttr("disabled");
and then force the selection of a different value.
$("#edit-field-service-sub-cat-value").val("0");
Note, for a disabled option, the val of the drop down will now be null, not the value of the selected option if it is disabled.
Well, depending on your needs you can choose any of the following. Out put is written against each method
You can choose the one you need
This will round
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global
flag needs to be provided.
In order to uninstall the globally linked foo
package, the following command can be used (using sudo
if necessary, depending on your setup and permissions)
sudo npm rm --global foo
This will uninstall the package.
To check whether a package is installed, the npm ls
command can be used:
npm ls --global foo
If the value of a disabled textbox needs to be retained when a form is cleared (reset), disabled = "disabled"
has to be used, as read-only textbox will not retain the value
For Example:
HTML
Textbox
<input type="text" id="disabledText" name="randombox" value="demo" disabled="disabled" />
Reset button
<button type="reset" id="clearButton">Clear</button>
In the above example, when Clear button is pressed, disabled text value will be retained in the form. Value will not be retained in the case of input type = "text" readonly="readonly"
The interrupt process is hardware and OS dependent. So you will have very different behavior depending on where you run your python script. For example, on Windows machines we have Ctrl+C (SIGINT
) and Ctrl+Break (SIGBREAK
).
So while SIGINT is present on all systems and can be handled and caught, the SIGBREAK signal is Windows specific (and can be disabled in CONFIG.SYS) and is really handled by the BIOS as an interrupt vector INT 1Bh, which is why this key is much more powerful than any other. So if you're using some *nix flavored OS, you will get different results depending on the implementation, since that signal is not present there, but others are. In Linux you can check what signals are available to you by:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGEMT 8) SIGFPE 9) SIGKILL 10) SIGBUS
11) SIGSEGV 12) SIGSYS 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGURG 17) SIGSTOP 18) SIGTSTP 19) SIGCONT 20) SIGCHLD
21) SIGTTIN 22) SIGTTOU 23) SIGIO 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGPWR 30) SIGUSR1
31) SIGUSR2 32) SIGRTMAX
So if you want to catch the CTRL+BREAK
signal on a linux system you'll have to check to what POSIX signal they have mapped that key. Popular mappings are:
CTRL+\ = SIGQUIT
CTRL+D = SIGQUIT
CTRL+C = SIGINT
CTRL+Z = SIGTSTOP
CTRL+BREAK = SIGKILL or SIGTERM or SIGSTOP
In fact, many more functions are available under Linux, where the SysRq (System Request) key can take on a life of its own...
Use this function like
String.prototype.text=function(){
return this ? String(this).replace(/<[^>]+>/gm, '') : '';
}
"<span>My text</span>".text()
output:
My text
A = filename
ftp = ftplib.FTP("IP")
ftp.login("USR Name", "Pass")
ftp.cwd("/Dir")
try:
ftp.retrbinary("RETR " + filename ,open(A, 'wb').write)
except:
print "Error"
is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)
with open('in.txt') as f:
rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))
another way:
is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4),
as well for complex matrices see the example below (only change int
to complex
)
with open('in.txt') as f:
data = []
cols,rows=list(map(int, f.readline().split()))
for i in range(0, rows):
data.append(list(map(int, f.readline().split()[:cols])))
print (data)
I updated the code, this method is working for any number of matrices and any kind of matrices(int
,complex
,float
) in the initial in.txt
file.
This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes
print to print()
and
print "%7g" %a[i,j], to print ("%7g" %a[i,j],end="")
the script:
import numpy as np
def printMatrix(a):
print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
rows = a.shape[0]
cols = a.shape[1]
for i in range(0,rows):
for j in range(0,cols):
print "%7g" %a[i,j],
print
print
def readMatrixFile(FileName):
rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
return a
def readMatrixFileComplex(FileName):
data = []
rows,cols=list(map(int, FileName.readline().split()))
for i in range(0, rows):
data.append(list(map(complex, FileName.readline().split()[:cols])))
a = np.array(data)
return a
f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()
print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)
with open('complex_in.txt') as fid:
a2=readMatrixFileComplex(fid)
print(a2)
b2=readMatrixFileComplex(fid)
print(b2)
print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)
as input file I take in.txt
:
4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5
and complex_in.txt
3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j
and the output look like:
Matrix[4][4]
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
Matrix[4][3]
4.02 -3 4
-13 19 -7
3 -2 7
-1 1 -1
Matrix[3][4]
1 2 -2 0
-3 4 7 2
6 0 3 1
Matrix[4][2]
-1 3
0 9
1 -11
4 -5
matrix multiplication
Matrix[4][3]
-6.98 15 3
-35.96 70 20
-104.94 189 57
-255.92 420 96
Matrix[3][2]
-3 43
18 -60
1 -20
[[ 1.+1.j 2.+2.j -2.-2.j 0.+0.j]
[-3.-3.j 4.+4.j 7.+7.j 2.+2.j]
[ 6.+6.j 0.+0.j 3.+3.j 1.+1.j]]
[[ -1. -1.j 3. +3.j]
[ 0. +0.j 9. +9.j]
[ 1. +1.j -11.-11.j]
[ 4. +4.j -5. -5.j]]
complex matrix multiplication
[[ 0. -6.j 0. +86.j]
[ 0. +36.j 0.-120.j]
[ 0. +2.j 0. -40.j]]
real part of complex matrix
Matrix[3][2]
0 0
0 0
0 0
imaginary part of complex matrix
Matrix[3][2]
-6 86
36 -120
2 -40
Well, to answer the immediate question:
>>> s = "http://www.domain.com/?s=some&two=20"
The rfind
method returns the index of right-most substring:
>>> s.rfind("&")
29
You can take all elements up to a given index with the slicing operator:
>>> "foobar"[:4]
'foob'
Putting the two together:
>>> s[:s.rfind("&")]
'http://www.domain.com/?s=some'
If you are dealing with URLs in particular, you might want to use built-in libraries that deal with URLs. If, for example, you wanted to remove two
from the above query string:
First, parse the URL as a whole:
>>> import urlparse, urllib
>>> parse_result = urlparse.urlsplit("http://www.domain.com/?s=some&two=20")
>>> parse_result
SplitResult(scheme='http', netloc='www.domain.com', path='/', query='s=some&two=20', fragment='')
Take out just the query string:
>>> query_s = parse_result.query
>>> query_s
's=some&two=20'
Turn it into a dict
:
>>> query_d = urlparse.parse_qs(parse_result.query)
>>> query_d
{'s': ['some'], 'two': ['20']}
>>> query_d['s']
['some']
>>> query_d['two']
['20']
Remove the 'two'
key from the dict:
>>> del query_d['two']
>>> query_d
{'s': ['some']}
Put it back into a query string:
>>> new_query_s = urllib.urlencode(query_d, True)
>>> new_query_s
's=some'
And now stitch the URL back together:
>>> result = urlparse.urlunsplit((
parse_result.scheme, parse_result.netloc,
parse_result.path, new_query_s, parse_result.fragment))
>>> result
'http://www.domain.com/?s=some'
The benefit of this is that you have more control over the URL. Like, if you always wanted to remove the two
argument, even if it was put earlier in the query string ("two=20&s=some"
), this would still do the right thing. It might be overkill depending on what you want to do.
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
Android wifi ADB was earlier working on my IDE but after Updating Android Studio (my current is Android Studio 3.3) it is not working and always prompt as "Unable to connect to device......Same network"
After spending much time i was unbale to resolve the issue.
Then i tried - WIFI ADB ULTIMATE by
https://github.com/huazhouwang/WIFIADB/tree/master/WIFIADBIntelliJPlugin
It worked for me.
This can might be in the version difference in the app level gradle check it once and then re-build
write.csv(t, "t.csv", row.names=FALSE)
From ?write.csv
:
row.names: either a logical value indicating whether the row names of
‘x’ are to be written along with ‘x’, or a character vector
of row names to be written.
putty
cd $ADMIN_SCRIPTS_HOME
./adstpall.sh
drop table t;
This will workout..
Updated for Swift 3 and above:
//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)
//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
textField.text = "Some default text"
}
// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert.textFields![0] // Force unwrapping because we know it exists.
print("Text field: \(textField.text)")
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
Swift 2.x
Assuming you want an action alert on iOS:
//1. Create the alert controller.
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)
//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.text = "Some default text."
})
//3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
let textField = alert.textFields![0] as UITextField
println("Text field: \(textField.text)")
}))
// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)
You can set new indices by using set_index
:
df2.set_index(np.arange(len(df2.index)))
Output:
x y
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2
This is my method and it works perfectly.
asp
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="5%" HeaderStyle-Width="5%" HeaderStyle-CssClass="color" HeaderText="Edit"
EditText="<span style='font-size: 20px; color: #27ae60;'><span class='glyphicons glyph-edit'></span></span>"
DeleteText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-bin'></span></span>"
CancelText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-remove-2'></span></span>"
UpdateText="<span style='font-size: 20px; color: #2980b9;'><span class='glyphicons glyph-floppy-saved'></span></span>" />
C# (replace 5 with the column number of the button)
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
}
else {
((LinkButton)e.Row.Cells[5].Controls[2]).OnClientClick = "return confirm('Do you really want to delete?');";
}
Well, container objects' __str__
methods will use repr
on their contents, not str
. So you could use __repr__
instead of __str__
, seeing as you're using an ID as the result.
Though you can't add a key pair to a running EC2 instance directly, you can create a linux user and create a new key pair for him, then use it like you would with the original user's key pair.
In your case, you can ask the instance owner (who created it) to do the following. Thus, the instance owner doesn't have to share his own keys with you, but you would still be able to ssh into these instances. These steps were originally posted by Utkarsh Sengar (aka. @zengr) at http://utkarshsengar.com/2011/01/manage-multiple-accounts-on-1-amazon-ec2-instance/. I've made only a few small changes.
Step 1: login by default “ubuntu” user:
$ ssh -i my_orig_key.pem [email protected]
Step 2: create a new user, we will call our new user “john”:
[ubuntu@ip-11-111-111-111 ~]$ sudo adduser john
Set password for “john” by:
[ubuntu@ip-11-111-111-111 ~]$ sudo su -
[root@ip-11-111-111-111 ubuntu]# passwd john
Add “john” to sudoer’s list by:
[root@ip-11-111-111-111 ubuntu]# visudo
.. and add the following to the end of the file:
john ALL = (ALL) ALL
Alright! We have our new user created, now you need to generate the key file which will be needed to login, like we have my_orin_key.pem in Step 1.
Now, exit and go back to ubuntu, out of root.
[root@ip-11-111-111-111 ubuntu]# exit
[ubuntu@ip-11-111-111-111 ~]$
Step 3: creating the public and private keys:
[ubuntu@ip-11-111-111-111 ~]$ su john
Enter the password you created for “john” in Step 2. Then create a key pair. Remember that the passphrase for key pair should be at least 4 characters.
[john@ip-11-111-111-111 ubuntu]$ cd /home/john/
[john@ip-11-111-111-111 ~]$ ssh-keygen -b 1024 -f john -t dsa
[john@ip-11-111-111-111 ~]$ mkdir .ssh
[john@ip-11-111-111-111 ~]$ chmod 700 .ssh
[john@ip-11-111-111-111 ~]$ cat john.pub > .ssh/authorized_keys
[john@ip-11-111-111-111 ~]$ chmod 600 .ssh/authorized_keys
[john@ip-11-111-111-111 ~]$ sudo chown john:ubuntu .ssh
In the above step, john is the user we created and ubuntu is the default user group.
[john@ip-11-111-111-111 ~]$ sudo chown john:ubuntu .ssh/authorized_keys
Step 4: now you just need to download the key called “john”. I use scp to download/upload files from EC2, here is how you can do it.
You will still need to copy the file using ubuntu user, since you only have the key for that user name. So, you will need to move the key to ubuntu folder and chmod it to 777.
[john@ip-11-111-111-111 ~]$ sudo cp john /home/ubuntu/
[john@ip-11-111-111-111 ~]$ sudo chmod 777 /home/ubuntu/john
Now come to local machine’s terminal, where you have my_orig_key.pem file and do this:
$ cd ~/.ssh
$ scp -i my_orig_key.pem [email protected]:/home/ubuntu/john john
The above command will copy the key “john” to the present working directory on your local machine. Once you have copied the key to your local machine, you should delete “/home/ubuntu/john”, since it’s a private key.
Now, one your local machine chmod john to 600.
$ chmod 600 john
Step 5: time to test your key:
$ ssh -i john [email protected]
So, in this manner, you can setup multiple users to use one EC2 instance!!
is a HTML entity. When doing .text()
, all HTML entities are decoded to their character values.
Instead of comparing using the entity, compare using the actual raw character:
var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
x = '';
}
Or you can also create the character from the character code manually it in its Javascript escaped form:
var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
x = '';
}
More information about String.fromCharCode
is available here:
More information about character codes for different charsets are available here:
You can use:
\set list '''foobar'''
SELECT * FROM dbo.PubLists WHERE name = :list;
That will do
If the one to many relationship is from T1 to T2 then it doesn't represent a function and therefore cannot be used to deduce or infer an inverse function that guarantees the resulting T2 value doesn't omit tuples of T1 join T2 that are deductively valid, because there is no deductively valid inverse function. ( representing functions was the purpose of primary keys. ) The answer in SQL think is yes you can do it. The answer in relational think is no you can't do it. See points of ambiguity in Codd 1970. The relationship would have to be many-to-one from T1 to T2.
Combination of two previous answers:
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
});
To get summary of new/missing files, and which files differ:
diff -arq folder1 folder2
a
treats all files as text, r
recursively searched subdirectories, q
reports 'briefly', only when files differ
I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.
class MyClass {
constructor ( arg1, arg2, arg3 )
myFunction1 () {...}
myFunction2 () {...}
myFunction3 () {...}
}
module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }
And then you get your expected behaviour.
var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )
steps to get sshpass For rhel/centos 6 :
# wget http://epel.mirror.net.in/epel/6/i386/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm
# yum install sshpass
This code will help you add a MsgBox in your asp.net file. You can change the function definition to your requirements. Hope this helps!
protected void Addstaff_Click(object sender, EventArgs e)
{
if (intClassCapcity < intCurrentstaffNumber)
{
MsgBox("Record cannot be added because max seats available for the " + (string)Session["course_name"] + " training has been reached");
}
else
{
sqlClassList.Insert();
}
}
private void MsgBox(string sMessage)
{
string msg = "<script language=\"javascript\">";
msg += "alert('" + sMessage + "');";
msg += "</script>";
Response.Write(msg);
}
I tried Kuzhichamadam Inn's solution and found that a slight change needed to be made.
MYSQL57 was a network service. I had tried this repeatedly with no success. When I opened services.msc I found another service for localhost: MySQL. I started that one using the process below and it worked.
run > services.msc > rightclick MySQL > properties >start
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
Make sure your project is 32 bit.
I had this problem, as soon as I ticked "Prefer 32 bit and rebuilt" all the Office Interop assemblies where available in Reference->Assemblies->Search "Office".
Firstly, as @l33tnerd said, f.close
should be outside the for loop.
Secondly, you are only calling readline
once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:
if data.find('!masters') != -1:
f = open('masters.txt')
for line in f:
print line,
sck.send('PRIVMSG ' + chan + " " + line)
f.close()
Finally, you were referring to the variable lines
inside the loop; I assume you meant to refer to line
.
Edit: Oh and you need to indent the contents of the if
statement.
Here is a helper function I use:
using System.Collections.Generic;
namespace HelperMethods
{
public static class MergeDictionaries
{
public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
{
if (second == null || first == null) return;
foreach (var item in second)
if (!first.ContainsKey(item.Key))
first.Add(item.Key, item.Value);
}
}
}
#include
works just like the C #include
.
#import
keeps track of which headers have already been included and is ignored if a header is imported more than once in a compilation unit. This makes it unnecessary to use header guards.
The bottom line is just use #import
in Objective-C and don't worry if your headers wind up importing something more than once.
There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self
in a default parameter and will never be able to.
The universal tool for string formatting, sprintf
:
$stamp = sprintf('%s%02s', $year, $month);
I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:
Hope that helps!
Are you trying to run "Hello world" for the first time? Please make sure you choose proper toolchain. For Windows you have to choose MinGW GCC.
To make MinGW GCC compiler as default or change you original project with error "Program “make” not found in PATH" or "launch failed binary not found eclipse c++" when you trying to run program simply go to Windows >> Preferences >> C\C++ Build >> Tool Chain Editor >> Change Current toolchain to MinGW GCC
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection.
using(SqlConnection openCon=new SqlConnection("your_connection_String"))
{
string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";
using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
{
querySaveStaff.Connection=openCon;
querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
.....
openCon.Open();
querySaveStaff.ExecuteNonQuery();
}
}
Disabling SQL Net Banners saved us.
I was having problem with finding the enhanced uploader tool for uploading folder and subfolders inside it in S3. But rather than finding a tool I could upload the folders along with the subfolders inside it by simply dragging and dropping it in the S3 bucket.
Note: This drag and drop feature doesn't work in Safari. I've tested it in Chrome and it works just fine.
After you drag and drop the files and folders, this screen opens up finally to upload the content.
As I had imported my project from a "git clone", I had to select File->Import-> Git->Project from git -> Existing local repository
Is [COL] really a character field that's holding numbers, or can you get rid of the single-quotes around the values? @Alex is right that IN is slower than =, so if you can do this, you'll be better off:
DELETE FROM [table] WHERE [COL] = '1'
But better still is using numbers rather than strings to find the rows (sql likes numbers):
DELETE FROM [table] WHERE [COL] = 1
Maybe try:
DELETE FROM [table] WHERE CAST([COL] AS INT) = 1
In either event, make sure you have an index on column [COL] to speed up the table scan.
$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity()
.
See also section "Custom Validation" on the Forms page, if you haven't already.
Also, for the first argument to $setValidity, use just 'filetype' and 'size'.
I think the below rules are recommended for a default wordpress site:
For folders inside wp-content, set 0755 permissions:
chmod -R 0755 plugins
chmod -R 0755 uploads
chmod -R 0755 upgrade
Let apache user be the owner for the above directories of wp-content:
chown apache uploads
chown apache upgrade
chown apache plugins
Perhaps you have some very weird and restrictive SELinux rules in place?
If not, try strace -o /tmp/wtf -fF curl -v google.com
and try to spot from /tmp/wtf
output file what's going on.
It seems nobody has mentioned that you can use a function as arg2 in $filter('filtername')(arg1,arg2);
For example:
$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});
Since Date type only accepts the format "yyyy-MM-dd", you need to format the date value accordingly.
Here is the solution for this,
var d = new Date();
var month = d.getMonth();
var month_actual = month + 1;
if (month_actual < 10) {
month_actual = "0"+month_actual;
}
var day_val = d.getDate();
if (day_val < 10) {
day_val = "0"+day_val;
}
document.getElementById("datepicker_id").value = d.getFullYear()+"-"+ month_actual +"-"+day_val;
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)
mvn install "-Dsomeproperty=propety value"
In pom.xml:
<properties>
<someproperty> ${someproperty} </someproperty>
</properties>
Referred from this question
Maybe you like to check the links below:
For the MS-SQL server driver (Microsoft SQL Server JDBC Driver).
try using:
logging.level.com.microsoft.sqlserver.jdbc=debug
in your application.properties file.
My personal preference is to set:
logging.level.com.microsoft.sqlserver.jdbc=info
logging.level.com.microsoft.sqlserver.jdbc.internals=debug
You can look at these links for reference:
This would definitely help Many!
private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
{
if(e.nButton==2)
{
contextMenuStrip1.Show(MousePosition);
}
}
[ e.nbutton==2 ] is like [ e.button==MouseButtons.Right ]
You have installed the library in a non-standard location ($HOME/zlib/
). That means the compiler will not know where your header files are and you need to tell the compiler that.
You can add a path to the list that the compiler uses to search for header files by using the -I
(upper-case i) option.
Also note that the LD_LIBRARY_PATH
is for the run-time linker and loader, and is searched for dynamic libraries when attempting to run an application. To add a path for the build-time linker use the -L
option.
All-together the command line should look like
$ c++ -I$HOME/zlib/include some_file.cpp -L$HOME/zlib/lib -lz
using System.Windows.Input
Keyboard.ClearFocus();
As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.
Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here
Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html
I have implement following it working for iOS devices but failed on android devices
<a href="mailto:?subject=Your mate might be interested...&body=<div style='padding: 0;'><div style='padding: 0;'><p>I found this on the site I think you might find it interesting. <a href='@(Request.Url.ToString())' >Click here </a></p></div></div>">Share This</a>
yes, safe to delete, my script searches and nukes every instance it finds, easily modified to a local directory
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
for drive in Swap Media OSX_10.11.6/$HOME
do
pushd /Volumes/${drive} &> /dev/null
gfind . -depth -name 'DerivedData'|xargs -I '{}' /bin/rm -fR '{}'
popd &> /dev/null
done
Using dplyr:
library(dplyr)
# exclude ID column then get mean
DF %>%
transmute(ID,
Mean = rowMeans(select(., -ID)))
Or
# select the columns to include in mean
DF %>%
transmute(ID,
Mean = rowMeans(select(., C1:C3)))
# ID Mean
# 1 A 3.666667
# 2 B 4.333333
# 3 C 3.333333
# 4 D 4.666667
# 5 E 4.333333
One small point to Andy Hayden's solution – it doesn't work (anymore?) because np.nan == np.nan
yields False
, so the replace
function doesn't actually do anything.
What worked for me was this:
df['b'] = df['b'].apply(lambda x: x if not np.isnan(x) else -1)
(At least that's the behavior for Pandas 0.19.2. Sorry to add it as a different answer, I do not have enough reputation to comment.)
To get it at any time, you can do SELECT MAX(Id) FROM Customers
.
In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY
-- to get the id last added by that procedure.
This is safer, because it will guarantee you get your Id
--just in case others are being added to the database at the same time.
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
It can be done by three different ways,though all them are nearly the same
Javascript way
document.getElementById('test').value
Jquery way
$("#test").val()
$("#test")[0].value
$("#test").get(0).value
I've just created a javascript shim to achieve this goal. Take a look if you want, it's a proof-of-concept, but take care: it's a early version and still needs some work.
you may put your Auth settings into a Environment. Like:
SetEnvIf HTTP_HOST testsite.local APPLICATION_ENV=development
<IfDefine !APPLICATION_ENV>
Allow from all
AuthType Basic
AuthName "My Testseite - Login"
AuthUserFile /Users/tho/htdocs/wgh_staging/.htpasswd
Require user username
</IfDefine>
The Auth is working, but I couldn't get my environment really running.
<?php
$test1='2010-04-19 18:31:27';
echo date('d/m/Y',strtotime($test1));
?>
try this
If others who view this question only have a JSON string (not in an object), then you can put it into a HashMap
and still get the ObjectMapper
to work. The result
variable is your JSON string.
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
// Pretty-print the JSON result
try {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Can you provide more info on the deployment failure? Is the application's failure to deploy triggering a .war.failed marker file?
The standalone instance Deployment folder ships with automatic deployment enabled by default. The automatic deployment mode automates the same functionality that you use with the manual mode, by using a series of marker files to indicate both the action and status of deployment to the runtime. For example, you can use the unix/linux "touch" command to create a .war.dodeploy marker file to tell the runtime to deploy the application.
It might be useful to know that there are in total five methods of deploying applications to AS7. I touched on this in another topic here : JBoss AS7 *.dodeploy files
I tend to use the Management Console for application management, but I know that the Management CLI is very popular among other uses also. Both are separate to the deployment folder processes. See how you go with the other methods to fit your needs.
If you search for "deploy" in the Admin Guide, you can see a section on the Deployment Scanner and a more general deployment section (including the CLI): https://docs.jboss.org/author/display/AS7/Admin+Guide
I don't think you can tell with the std::string class. However, if you really need this information, you could always derive a class from std::string and give the derived class the ability to tell if it had been changed since construction (or some other arbitrary time). Or better yet, just write a new class that wraps std::string since deriving from std::string may not be a good idea given the lack of a base class virtual destructor. That's probably more work, but more work tends to be needed for an optimal solution.
Of course, you can always just assume if it contains something other than "" then it has been "set", this won't detect it manually getting set to "" though.
I found a posting about Using the Windows Hosts File that also says "No wildcards are allowed."
In the past, I have just added the additional entries to the hosts file, because (as previously said), it's not that much extra work when you already are editing the apache config file.
I've found the same problem. I lost almost a day trying to start a service from OnClickListener
method - outside the onCreate
and after 1 day, I still failed!!!! Very frustrating!
I was looking at the sample example RemoteServiceController
. Theirs works, but my implementation does not work!
The only way that was working for me, was from inside onCreate
method. None of the other variants worked and believe me I've tried them all.
Conclusion:
Also the one "/" couldn't find path to the service, tried starting with Intent(package,className)
and nothing , also other type of Intent starting
I moved the service class in the same package of the activity Final form that works
Hopefully this helps someone by defining the listerners onClick
inside the onCreate
method like this:
public void onCreate() {
//some code......
Button btnStartSrv = (Button)findViewById(R.id.btnStartService);
Button btnStopSrv = (Button)findViewById(R.id.btnStopService);
btnStartSrv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startService(new Intent("RM_SRV_AIDL"));
}
});
btnStopSrv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
stopService(new Intent("RM_SRV_AIDL"));
}
});
} // end onCreate
Also very important for the Manifest file, be sure that service is child of application:
<application ... >
<activity ... >
...
</activity>
<service
android:name="com.mainActivity.MyRemoteGPSService"
android:label="GPSService"
android:process=":remote">
<intent-filter>
<action android:name="RM_SRV_AIDL" />
</intent-filter>
</service>
</application>
Select ColumnB and as two CF formula rules apply:
Green: =AND(B1048576="X",B1="Y")
Red: =AND(B1048576="X",B1="W")
Base(Base::UPtr n):next(std::move(n)) {}
should be much better as
Base(Base::UPtr&& n):next(std::forward<Base::UPtr>(n)) {}
and
void setNext(Base::UPtr n)
should be
void setNext(Base::UPtr&& n)
with same body.
And ... what is evt
in handle()
??
In bash
you can get the script file name using $0
. Generally $1
, $2
etc are to access CLI arguments. Similarly $0
is to access the name which triggers the script(script file name).
#!/bin/bash
echo "You are running $0"
...
...
If you invoke the script with path like /path/to/script.sh
then $0
also will give the filename with path. In that case need to use $(basename $0)
to get only script file name.
see if their duplicate jars or dependencies your adding remove it and your error will be gone: Eg: if you add android:supportv4 jar and also dependency you will get the error so remove the jar error will be gone
If you want to overwrite the element with key 0
function[0] = 42;
Otherwise:
function.insert(std::make_pair(0, 42));
If you are using in NodeJS then you can set timeout in package.json
"test": "mocha --timeout 10000"
then you can run using npm like:
npm test
I think you must use rawurlencode() instead urlencode() for your purpose.
sample
$image = 'some images.jpg';
$url = 'http://example.com/'
With urlencode($str) will result
echo $url.urlencode($image); //http://example.com/some+images.jpg
its not change to %20 at all
but with rawurlencode($image) will produce
echo $url.rawurlencode(basename($image)); //http://example.com/some%20images.jpg
You can also enable multiple GPU cores, like so:
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"
For ng-click working properly you need define your controller after angularjs script binding and use it via $scope.
you could try
$('*').not('#div').bind('touchmove', false);
add this if necessary
$('#div').bind('touchmove');
note that everything is fixed except #div
You can set the datatable as a datasource to many elements.
For eg
gridView
repeater
datalist
etc etc
If you need to extract data from each row then you can use
table.rows[rowindex][columnindex]
or
if you know the column name
table.rows[rowindex][columnname]
If you need to iterate the table then you can either use a for loop or a foreach loop like
for ( int i = 0; i < table.rows.length; i ++ )
{
string name = table.rows[i]["columnname"].ToString();
}
foreach ( DataRow dr in table.Rows )
{
string name = dr["columnname"].ToString();
}
You can use the attribute selector here:
input[type="text"] {
font-family: Arial, sans-serif;
}
This is supported in IE7 and above. You can use IE7.js to add support for this if you need to support IE6.
See: http://reference.sitepoint.com/css/attributeselector for more information
The answer about threading is good, but you need to be a bit more specific about what you want to do.
If you have two functions that both use a lot of CPU, threading (in CPython) will probably get you nowhere. Then you might want to have a look at the multiprocessing module or possibly you might want to use jython/IronPython.
If CPU-bound performance is the reason, you could even implement things in (non-threaded) C and get a much bigger speedup than doing two parallel things in python.
Without more information, it isn't easy to come up with a good answer.
As of Django 1.2, you can use exists()
:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists
if some_queryset.filter(pk=entity_id).exists():
print("Entry contained in queryset")
In the earlier versions of MySQL ( < 5.7.5 ) the only way to set
'innodb_buffer_pool_size'
variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :
[mysqld]
innodb_buffer_pool_size = 2147483648
You need to restart your mysql server to have it's effect in action.
As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:
mysql> SET GLOBAL innodb_buffer_pool_size=402653184;
Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html
Use substring method like this::
str.substring(str.length()-2);
This will safely remove only if token is at end of string.
StringUtils.removeEnd(string, ".xml");
Apache StringUtils functions are null-, empty-, and no match- safe
As others mentioned, unions combined with enumerations and wrapped into structs can be used to implement tagged unions. One practical use is to implement Rust's Result<T, E>
, which is originally implemented using a pure enum
(Rust can hold additional data in enumeration variants). Here is a C++ example:
template <typename T, typename E> struct Result {
public:
enum class Success : uint8_t { Ok, Err };
Result(T val) {
m_success = Success::Ok;
m_value.ok = val;
}
Result(E val) {
m_success = Success::Err;
m_value.err = val;
}
inline bool operator==(const Result& other) {
return other.m_success == this->m_success;
}
inline bool operator!=(const Result& other) {
return other.m_success != this->m_success;
}
inline T expect(const char* errorMsg) {
if (m_success == Success::Err) throw errorMsg;
else return m_value.ok;
}
inline bool is_ok() {
return m_success == Success::Ok;
}
inline bool is_err() {
return m_success == Success::Err;
}
inline const T* ok() {
if (is_ok()) return m_value.ok;
else return nullptr;
}
inline const T* err() {
if (is_err()) return m_value.err;
else return nullptr;
}
// Other methods from https://doc.rust-lang.org/std/result/enum.Result.html
private:
Success m_success;
union _val_t { T ok; E err; } m_value;
}
Do this.
public void FullScreencall() {
if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
View v = this.getWindow().getDecorView();
v.setSystemUiVisibility(View.GONE);
} else if(Build.VERSION.SDK_INT >= 19) {
//for new api versions.
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
decorView.setSystemUiVisibility(uiOptions);
}
}
This works 100% and you can do same for lower API versions, even if it's a late answer I hope it will helps someone else.
If you want this to be permanent, just call FullscreenCall()
inside your onResume()
method.
The following will work in MVC 4
@Html.HiddenFor(x => x.CRN, new { @Value = "1" });
@Value property is case sensitive. You need a capital 'V' on @Value.
Here is my model
public int CRN { get; set; }
Here is what is output in html when you look in the browser
<input value="1" data-val="true" data-val-number="The field CRN must be a number." data-val-required="The CRN field is required." id="CRN" name="CRN" type="hidden" value="1"/>
Here is my method
[HttpPost]
public ActionResult MyMethod(MyViewModel viewModel)
{
int crn = viewModel.CRN;
}