You can use the beforeSend
callback to set additional parameters (The XMLHTTPRequest
object is passed to it as its only parameter).
Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:
$.ajax({
url: 'http://bar.other',
data: { whatever:'cool' },
type: 'GET',
beforeSend: function(xhr){
xhr.withCredentials = true;
}
});
One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.
Python3
use
from .user import User inside dir.py file
and
use from class.dir import Dir inside main.py
or from class.usr import User inside main.py
like so
To answer your extra question
:
You can set which rows should be repeated on every page using:
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
Now, row 1, 2, 3, 4 and 5 will be repeated.
import java.util.Date;
public class IsDateBetween {
public static void main (String[] args) {
IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
}
public IsDateBetween(String dd) {
long from=Date.parse("01/01/2000"); // From some date
long to=Date.parse("12/12/2010"); // To Some Date
long check=Date.parse(dd);
int x=0;
if((check-from)>0 && (to-check)>0)
{
x=1;
}
System.out.println ("From Date is greater Than ToDate : "+x);
}
}
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
You should apply a "clearfix" to clear the parent element. Next thing, the h4 for the header title, extend all the way across the header, so after you apply clearfix, it will push down the child element causing the header div to have a larger height.
Here is a fix, just replace it with your code.
<div class="panel-heading clearfix">
<b>Panel header</b>
<div class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</div>
</div>
Editted on 12/22/2015 - added .clearfix to heading div
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
It means that you have a memory error. You may be trying to free
a pointer that wasn't allocated by malloc
(or delete
an object that wasn't created by new
) or you may be trying to free
/delete
such an object more than once. You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.
Any number of programming errors can cause this problem. You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs. If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).
Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.
create table batch(batchid number,
batchname varchar2(30),
batchtype char(1),
source char(1),
intarea number)
/
create sequence batch_seq start with 1
/
create trigger batch_bi
before insert on batch
for each row
begin
select batch_seq.nextval into :new.batchid from dual;
end;
/
create procedure insert_batch(v_batchname batch.batchname%TYPE,
v_batchtype batch.batchtype%TYPE,
v_source batch.source%TYPE,
v_intarea batch.intarea%TYPE,
v_batchid out batch.batchid%TYPE)
as
begin
insert into batch(batchname, batchtype, source, intarea)
values(v_batchname, v_batchtype, v_source, v_intarea)
returning batchid into v_batchid;
end;
/
You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:
declare
l_batchid batch.batchid%TYPE;
begin
insert_batch(v_batchname => 'Batch 1',
v_batchtype => 'A',
v_source => 'Z',
v_intarea => 1,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
insert_batch(v_batchname => 'Batch 99',
v_batchtype => 'B',
v_source => 'Y',
v_intarea => 9,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
end;
/
Generated id: 1
Generated id: 2
You can make the call without an explicit anonymous block, e.g. from SQL*Plus:
variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);
... and use the bind variable :l_batchid
to refer to the generated value afterwards:
print l_batchid;
insert into some_table values(:l_batch_id, ...);
Use FromResult Method
public async Task<string> GetString()
{
System.Threading.Thread.Sleep(5000);
return await Task.FromResult("Hello");
}
You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!
To get the current memory_limit value, run:
php -r "echo ini_get('memory_limit').PHP_EOL;"
Try increasing the limit in your php.ini
file (ex. /etc/php5/cli/php.ini
for Debian-like systems):
; Use -1 for unlimited or define an explicit value like 2G
memory_limit = -1
Or, you can increase the limit with a command-line argument:
php -d memory_limit=-1 composer.phar require hwi/oauth-bundle php-http/guzzle6-adapter php-http/httplug-bundle
To get loaded php.ini files location try:
php --ini
Another quick solution:
php composer.phar COMPOSER_MEMORY_LIMIT=-1 require hwi/oauth-bundle php-http/guzzle6-adapter php-http/httplug-bundle
A CustomValidator would also work here:
<asp:CustomValidator runat="server"
ID="valDateRange"
ControlToValidate="txtDatecompleted"
onservervalidate="valDateRange_ServerValidate"
ErrorMessage="enter valid date" />
Code-behind:
protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
Following Works for me and its good from readability point of view when array element values are small:
key: [string1, string2, string3, string4, string5, string6]
Note:snakeyaml implementation used
How about just:
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, 280, 32)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self addSubview:textField];
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
The previous answers did not solve my problem, but this code did:
import sys
for name, module in sorted(sys.modules.items()):
if hasattr(module, '__version__'):
print name, module.__version__
I would like just to add that if you want to use windows socket library you have to :
at the beginning : call WSAStartup()
at the end : call WSACleanup()
Regards;
Unfortunately disown
is specific to bash and not available in all shells.
Certain flavours of Unix (e.g. AIX and Solaris) have an option on the nohup
command itself which can be applied to a running process:
nohup -p pid
Try this:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.
$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force
Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.
If you want to bring an activity to the top of the stack when clicking on a Notification then you may need to do the following to make the FLAG_ACTIVITY_REORDER_TO_FRONT work:
The solution for me for this was to make a broadcast receiver that listens to broadcast actions that the notification triggers. So basically:
Notification triggers a broadcast action with an extra the name of the activity to launch.
Broadcast receiver catches this when the notification is clicked, then creates an intent to launch that activity using the FLAG_ACTIVITY_REORDER_TO_FRONT flag
Activity is brought to the top of activity stack, no duplicates.
You could do something like this:
int thread_counter = 0;
pthread_mutex_t thread_counter_lock = PTHREAD_MUTEX_INITIALIZER;
int new_thread_id() {
int rv;
pthread_mutex_lock(&thread_counter_lock);
rv = ++thread_counter;
pthread_mutex_unlock(&thread_counter_lock);
return rv;
}
static void *threadproc(void *data) {
int thread_id = new_thread_id();
printf("Thread %d reporting for duty!\n", thread_id);
return NULL;
}
If you can rely on having GCC (clang also works in this case), you can also do this:
int thread_counter = 0;
static void *threadproc(void *data) {
int thread_id = __sync_add_and_fetch(&thread_counter, 1);
printf("Thread %d reporting for duty!\n", thread_id);
return NULL;
}
If your platform supports this, a similar option:
int thread_counter = 0;
int __thread thread_id = 0;
static void *threadproc(void *data) {
thread_id = __sync_add_and_fetch(&thread_counter, 1);
printf("Thread %d reporting for duty!\n", thread_id);
return NULL;
}
This has the advantage that you don't have to pass around thread_id in function calls, but it doesn't work e.g. on Mac OS.
This is my personal approach.
class ColorType {
static get RED () {
return "red";
}
static get GREEN () {
return "green";
}
static get BLUE () {
return "blue";
}
}
// Use case.
const color = Color.create(ColorType.RED);
I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.
jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.
I tried many, many, many different methods, but in the end, it was Charles Guilbert's method that worked best for me.
Hats off to Charles Guilbert! Using his answer, I am able to get data into my variables, even when my page first loads.
Here's an example of the working script:
jQuery.extend
(
{
getValues: function(url)
{
var result = null;
$.ajax(
{
url: url,
type: 'get',
dataType: 'html',
async: false,
cache: false,
success: function(data)
{
result = data;
}
}
);
return result;
}
}
);
// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");
// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");
// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");
// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");
It's not a problem. When you first design your application, you can use the test codes provided by AdMob. These codes work great on your emulators and on real devices. But as soon as you publish your application on Google Play, these codes stop working immediately. You need to make your test devices. https://developers.google.com/admob/android/test-ads
But you can use a life hack to continue using test codes for an already published application. Change the application ID in the build.gradle(android) file to a different name and everything will work. Do not forget to return the old name before publishing the application to the Market.
Basing on this tutorial, here a very basic way to do that:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
Don't forget to add proper error handling
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
In my case, if I remove the the contentType
, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify()
to the data as mentioned in the update of this answer.
This is wild because none of these answers actually provide the return of an actual Python set. Here is a messy implementation that will give a powerset that actually is a Python set
.
test_set = set(['yo', 'whatup', 'money'])
def powerset( base_set ):
""" modified from pydoc's itertools recipe shown above"""
from itertools import chain, combinations
base_list = list( base_set )
combo_list = [ combinations(base_list, r) for r in range(len(base_set)+1) ]
powerset = set([])
for ll in combo_list:
list_of_frozensets = list( map( frozenset, map( list, ll ) ) )
set_of_frozensets = set( list_of_frozensets )
powerset = powerset.union( set_of_frozensets )
return powerset
print powerset( test_set )
# >>> set([ frozenset(['money','whatup']), frozenset(['money','whatup','yo']),
# frozenset(['whatup']), frozenset(['whatup','yo']), frozenset(['yo']),
# frozenset(['money','yo']), frozenset(['money']), frozenset([]) ])
I'd love to see a better implementation, though.
In my case decorating the parameter class with the [JsonObject(MemberSerialization.OptOut)]
attribute from Newtonsoft did the trick.
For example:
[HttpPost]
[Route("MyRoute")]
public IHttpActionResult DoWork(MyClass args)
{
...
}
[JsonObject(MemberSerialization.OptOut)]
public Class MyClass
{
...
}
I have used react-native-image-picker
to select photo. In my case after choosing the photp from mobile. I'm storing it's info in component state
. After, I'm sending POST
request using fetch
like below
const profile_pic = {
name: this.state.formData.profile_pic.fileName,
type: this.state.formData.profile_pic.type,
path: this.state.formData.profile_pic.path,
uri: this.state.formData.profile_pic.uri,
}
const formData = new FormData()
formData.append('first_name', this.state.formData.first_name);
formData.append('last_name', this.state.formData.last_name);
formData.append('profile_pic', profile_pic);
const Token = 'secret'
fetch('http://10.0.2.2:8000/api/profile/', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data",
Authorization: `Token ${Token}`
},
body: formData
})
.then(response => console.log(response.json()))
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf
, rather than ..\sqldeveloper\bin\ide.conf
:
# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----
Git requires a commit to have a comment, otherwise it wont accept the commit.
You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.
Use an Gradient Generator - and everything will be perfect ;) http://www.colorzilla.com/gradient-editor/
There is another way to do XOR:
bool XOR(bool a, bool b)
{
return (a + b) % 2;
}
Which obviously can be demonstrated to work via:
#include <iostream>
bool XOR(bool a, bool b)
{
return (a + b) % 2;
}
int main()
{
using namespace std;
cout << "XOR(true, true):\t" << XOR(true, true) << endl
<< "XOR(true, false):\t" << XOR(true, false) << endl
<< "XOR(false, true):\t" << XOR(false, true) << endl
<< "XOR(false, false):\t" << XOR(false, false) << endl
<< "XOR(0, 0):\t\t" << XOR(0, 0) << endl
<< "XOR(1, 0):\t\t" << XOR(1, 0) << endl
<< "XOR(5, 0):\t\t" << XOR(5, 0) << endl
<< "XOR(20, 0):\t\t" << XOR(20, 0) << endl
<< "XOR(6, 6):\t\t" << XOR(5, 5) << endl
<< "XOR(5, 6):\t\t" << XOR(5, 6) << endl
<< "XOR(1, 1):\t\t" << XOR(1, 1) << endl;
return 0;
}
>>> L = [1,2,3]
>>> " ".join(str(x) for x in L)
'1 2 3'
This is more of a continuation of jglouie's response.
If you are using openssl to convert the PKCS#12 certificate to public/private PEM keys, there is no need to rename the file. Assuming the file is called cert.pfx, the following three commands will create a public pem key and an encrypted private pem key:
openssl pkcs12 -in cert.pfx -out cert.pem -nodes -nokeys
openssl pkcs12 -in cert.pfx -out cert_key.pem -nodes -nocerts
openssl rsa -in cert_key.pem -out cert_key.pem -des3
The first two commands may prompt for an import password. This will be a password that was provided with the PKCS#12 file.
The third command will let you specify the encryption passphrase for the certificate. This is what you will enter when using the certificate.
You can use papaparse.js like the example below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSV</title>
</head>
<body>
<input type="file" id="files" multiple="">
<button onclick="csvGetter()">CSV Getter</button>
<h3>The Result will be in the Console.</h3>
<script src="papaparse.min.js"></script>
<script>
function csvGetter() {
var file = document.getElementById('files').files[0];
Papa.parse(file, {
complete: function(results) {
console.log(results.data);
}
});
}
</script>
</body>
</html>
Don't forget to include papaparse.js in the same folder.
In the absence of more detailed info:
using(var dbContext = new dbDataContext())
{
var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
if(data != null)
{
data.SomeField = newValue;
}
dbContext.SubmitChanges();
}
I would do it this way:
import sys
def do_my_stuff():
pass
if __name__ == "__main__":
try:
do_my_stuff()
except SystemExit, e:
print(e)
The following Link has explained complete details about how to back sql server 2008 database using c#
Sql Database backup can be done using many way. You can either use Sql Commands like in the other answer or have create your own class to backup data.
But these are different mode of backup.
But the disadvantage with this method is that it needs your sql management studio to be installed on your client system.
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
Other answers have already covered profiling to avoid premature optimization and overhead cost in parallel processing. This answer explains the ideal choice of data structures for parallel streaming.
As a rule, performance gains from parallelism are best on streams over
ArrayList
,HashMap
,HashSet
, andConcurrentHashMap
instances; arrays;int
ranges; andlong
ranges. What these data structures have in common is that they can all be accurately and cheaply split into subranges of any desired sizes, which makes it easy to divide work among parallel threads. The abstraction used by the streams library to perform this task is the spliterator , which is returned by thespliterator
method onStream
andIterable
.Another important factor that all of these data structures have in common is that they provide good-to-excellent locality of reference when processed sequentially: sequential element references are stored together in memory. The objects referred to by those references may not be close to one another in memory, which reduces locality-of-reference. Locality-of-reference turns out to be critically important for parallelizing bulk operations: without it, threads spend much of their time idle, waiting for data to be transferred from memory into the processor’s cache. The data structures with the best locality of reference are primitive arrays because the data itself is stored contiguously in memory.
Source: Item #48 Use Caution When Making Streams Parallel, Effective Java 3e by Joshua Bloch
As the best anwser have writed using XMLHttpResponse
except window.open
, and I make the abstracts-anwser as a instance.
The main Js file is download.js
Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules";
var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
function download33() {
var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
var x=new XMLHttpRequest();
x.open("POST", download_url, true);
x.setRequestHeader("Content-type","application/json");
// x.setRequestHeader("Access-Control-Allow-Origin", "*");
x.setRequestHeader("Authorization", "JWT " + localStorage.token );
x.responseType = 'blob';
x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
x.send( JSON.stringify(sender_data) ); // post-data
}
2 more solutions I had luck with when neither tab close + reopening the page in another tab nor closing all tabs in Chrome (and the browser) then restarting it didn't work:
1) I fixed it on my machine by closing the tab, force-closing Chrome, & restarting the browser without restoring tabs (Note: on a computer running CentOS Linux).
2) My boss (also on CentOS) had the same issue (alerts are a big part of my company's Javascript debugging process for numerous reasons e.g. legacy), but my 1st method didn't work for him. However, I managed to fix it for him with the following process:
a) Make an empty text file called FixChrome.sh, and paste in the following bash script:
#! /bin/bash
cd ~/.config/google-chrome/Default //adjust for your Chrome install location
rm Preferences
rm 'Current Session'
rm 'Current Tabs'
rm 'Last Session'
rm 'Last Tabs'
b) close Chrome, then open Terminal and run the script (bash FixChrome.sh).
It worked for him. Downside is that you lose all tabs from your current & previous session, but it's worth it if this matters to you.
You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.
inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024]; //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
System.out.println(read);
// Your code to handle the data
}
Running 'pod update' in my project fixed my problem with the 'library not found for -lSTPopup' error.
Remarking Trevor Panhorst's answer:
"Just be careful doing pod update if you don't use explicit versions in your pod file."
First run:
find . -type f -name "*.py[c|o]" -exec rm -f {} +
Then add:
export PYTHONDONTWRITEBYTECODE=1
To ~/.profile
If you have the process ID (PID
) you can kill this process as follow:
Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();
The initialize
method is called after all @FXML
annotated members have been injected. Suppose you have a table view you want to populate with data:
class MyController {
@FXML
TableView<MyModel> tableView;
public MyController() {
tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point.
}
@FXML
public void initialize() {
tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members.
}
}
Can I check - do you mean a rectangular array ([,]
)or a jagged array ([][]
)?
It is quite easy to sort a jagged array; I have a discussion on that here. Obviously in this case the Comparison<T>
would involve a column instead of sorting by ordinal - but very similar.
Sorting a rectangular array is trickier... I'd probably be tempted to copy the data out into either a rectangular array or a List<T[]>
, and sort there, then copy back.
Here's an example using a jagged array:
static void Main()
{ // could just as easily be string...
int[][] data = new int[][] {
new int[] {1,2,3},
new int[] {2,3,4},
new int[] {2,4,1}
};
Sort<int>(data, 2);
}
private static void Sort<T>(T[][] data, int col)
{
Comparer<T> comparer = Comparer<T>.Default;
Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col]));
}
For working with a rectangular array... well, here is some code to swap between the two on the fly...
static T[][] ToJagged<T>(this T[,] array) {
int height = array.GetLength(0), width = array.GetLength(1);
T[][] jagged = new T[height][];
for (int i = 0; i < height; i++)
{
T[] row = new T[width];
for (int j = 0; j < width; j++)
{
row[j] = array[i, j];
}
jagged[i] = row;
}
return jagged;
}
static T[,] ToRectangular<T>(this T[][] array)
{
int height = array.Length, width = array[0].Length;
T[,] rect = new T[height, width];
for (int i = 0; i < height; i++)
{
T[] row = array[i];
for (int j = 0; j < width; j++)
{
rect[i, j] = row[j];
}
}
return rect;
}
// fill an existing rectangular array from a jagged array
static void WriteRows<T>(this T[,] array, params T[][] rows)
{
for (int i = 0; i < rows.Length; i++)
{
T[] row = rows[i];
for (int j = 0; j < row.Length; j++)
{
array[i, j] = row[j];
}
}
}
You want:
insert into prices (group, id, price)
select
7, articleId, 1.50
from article where name like 'ABC%';
where you just hardcode the constant fields.
1) echo logpath=F:\mongodb\log\mongo.log > F:\mongodb\mongod.cfg
2) dbpath=F:\mongodb\data\db [add this to the next line in mongod.cfg]
C:\>F:\mongodb\bin\mongod.exe –config F:\mongodb\mongod.cfg –install
It's working..
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(
SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(col,'1', 1), '2', 1), '3', 1), '4', 1), '5', 1), '6', 1)
, '7', 1), '8', 1), '9', 1), '0', 1) as new_col
FROM table_name group by new_col;
Nowadays people tend to use website builders (CMS like Wordpress) instead of coding their own blog from scratch. Even professional web developers do it because it's faster.
It would be nice if you could mention the advantages and things to keep in mind when coding your own blog in real life, for example:
Anyways, you can use css/css3 or JavaScript for making interactive webpage. Even you can upload your all sort of code into a server formatting the default blog theme.
If you want the executable:
System.Reflection.Assembly.GetEntryAssembly().Location
If you want the assembly that's consuming your library (which could be the same assembly as above, if your code is called directly from a class within your executable):
System.Reflection.Assembly.GetCallingAssembly().Location
If you'd like just the filename and not the path, use:
Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location)
collection : A collection(with small 'c') represents a group of objects/elements.
Collection
: The root interface of Java Collections Framework.
Collections
: A utility class that is a member of the Java Collections Framework.
It is better to save files into a sub-directory of user.home than wherever the app. might reside.
Sun went to considerable effort to ensure that applets and apps. launched using Java Web Start cannot determine the apps. real path. This change broke many apps. I would not be surprised if the changes are extended to other apps.
try this:
@media (hover:<s>on-demand</s>) {
button:hover {
background-color: #color-when-NOT-touch-device;
}
}
UPDATE: unfortunately W3C has removed this property from the specs (https://github.com/w3c/csswg-drafts/commit/2078b46218f7462735bb0b5107c9a3e84fb4c4b1).
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:
let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
tempArr.push(objectArr[element]);
});
let json = JSON.stringify(tempArr);
You can write:
$(document).ready(function() {
$("#select-all-teammembers").click(function() {
var checkBoxes = $("input[name=recipients\\[\\]]");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
Before jQuery 1.6, when we only had attr() and not prop(), we used to write:
checkBoxes.attr("checked", !checkBoxes.attr("checked"));
But prop()
has better semantics than attr()
when applied to "boolean" HTML attributes, so it is usually preferred in this situation.
Since I wanted to compare two arrays for a unit Test and I arrived on this answer I thought I could share.
You can also do it with:
@Test
public void testTwoArrays() {
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
Assert.assertArrayEquals(array, secondArray);
}
And you could check on Comparing arrays in JUnit assertions for more infos.
There is a new property in CSS3 that you can use to change the way the box model calculates width/height, it's called box-sizing.
By setting this property with the value "border-box" it makes whichever element you apply it to not stretch when you add a padding or border. If you define something with 100px width, and 10px padding, it will still be 100px wide.
box-sizing: border-box;
See here for browser support. It does not work for IE7 and lower, however, I believe that Dean Edward's IE7.js adds support for it. Enjoy :)
The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.
$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString
This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))
If the info does not need to be secure at all you can convert it to plain text:
$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0
If you are using the Genymotion emulator:
Make sure that the SDK path used for Genymotion is also the same path used for the Eclipse.
This error also occurs if those two paths are different.
The <img>
element is empty — it doesn't have an end tag.
If the image is a background image, use CSS. If it is a content image, then set position: relative
on a container, then absolutely position the image and/or text within it.
Insert:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
at the end of AssemblyInfo.cs file
both specify elements, attributes, nesting, ordering, #occurences
XSD also has data types, (typed) pointers, namespaces, keys and more.... unlike DTD
Moreover though XSD is little verbose its syntax is extension of XML, making it convenient to learn fast.
Try to use single quotes (') to avoid shell escaping of your string. Remember that the expression needs to match the whole path, i.e. needs to look like:
find . -regex '\./[a-f0-9-]*.jpg'
Apart from that, it seems that my find (GNU 4.4.2) only knows basic regular expressions, especially not the {36} syntax. I think you'll have to make do without it.
Girls and guys we are in 2019 and we do not have that much time for typing... So lets do this cool new fancy ECMAScript 2016:
Object.keys(obj).forEach(e => console.log(`key=${e} value=${obj[e]}`));
Ctrl + Shift + R refreshes intellisense in management studio 2008 as well.
Check os.makedirs
: (It makes sure the complete path exists.)
To handle the fact the directory might exist, catch OSError
.
(If exist_ok
is False
(the default), an OSError
is raised if the target directory already exists.)
import os
try:
os.makedirs('./path/to/somewhere')
except OSError:
pass
try this, hope help you
$("input[name=search-mini]").on("search", function() {
//do something for search
});
By passing a block to find_or_create
, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.
Assuming:
class GroupMember < ActiveRecord::Base
validates_presence_of :name
end
then
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }
will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4
and group_id 7
The docs show you are now able to add:
"env": {
"jest/globals": true
}
To your .eslintrc
which will add all the jest related things to your environment, eliminating the linter errors/warnings.
I am late for the answer but I think this is another solution which is not mentioned here so posting.
Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.
filter.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="@+id/action_filter"
android:title="@string/filter"
android:orderInCategory="10"
android:icon="@drawable/filter"
app:showAsAction="ifRoom" />
</menu>
Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Step 3: Now add the method onCreateOptionsMenu which will be override as:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.filter, menu); // Use filter.xml from step 1
}
Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_filter){
//Do whatever you want to do
return true;
}
return super.onOptionsItemSelected(item);
}
List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
Had the same problem on another server, but realized that locales are messed.
export LC_ALL="en_US.UTF-8"
fixed the problem
This should help you
HTML
<!-- pretty much i just need to click a link within the regions table and it changes to the neccesary div. -->
<table>
<tr class="thumb"></tr>
<td><a href="#" class="showall">All Regions</a> (shows main map) (link)</td>
<tr class="thumb"></tr>
<td>Northern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Southern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Eastern Region (link)</td>
</tr>
</table>
<br />
<div id="mainmapplace">
<div id="mainmap">
All Regions image
</div>
</div>
<div id="region">
<div class="replace">northern image</div>
<div class="replace">southern image</div>
<div class="replace">Eastern image</div>
</div>
JavaScript
var originalmap;
var flag = false;
$(function (){
$(".replace").click(function(){
flag = true;
originalmap = $('#mainmap');
$('#mainmap').replaceWith($(this));
});
$('.showall').click(
function(){
if(flag == true){
$('#region').append($('#mainmapplace .replace'));
$('#mainmapplace').children().remove();
$('#mainmapplace').append($(originalmap));
//$('#mapplace').append();
}
}
)
})
CSS
#mainmapplace{
width: 100px;
height: 100px;
background: red;
}
#region div{
width: 100px;
height: 100px;
background: blue;
margin: 10px 0 0 0;
}
What I use to get the desired outcome is:
toggle_cell.py
in the same directory as of your notebookfrom IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Sloution"></form>
'''
toggle_code_prepare_str = '''
<script>
function code_toggle() {
if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
$('div.cell.code_cell.rendered.selected div.input').hide();
} else {
$('div.cell.code_cell.rendered.selected div.input').show();
}
}
</script>
'''
display(HTML(toggle_code_prepare_str + toggle_code_str))
def hide_sloution():
display(HTML(toggle_code_str))
from toggle_cell import toggle_code as hide_sloution
hide_sloution()
Do you see anything wrong with the code?
Yes. Why are you adding the three fields together before you compare them?
I would probably do something like this: (assuming the fields are in the order you wish to sort them in)
@Override public int compare(final Report record1, final Report record2) {
int c;
c = record1.getReportKey().compareTo(record2.getReportKey());
if (c == 0)
c = record1.getStudentNumber().compareTo(record2.getStudentNumber());
if (c == 0)
c = record1.getSchool().compareTo(record2.getSchool());
return c;
}
To restart a service with changes here are the steps that I performed:
docker-compose stop -t 1 worker
docker-compose build worker
docker-compose up --no-start worker
docker-compose start worker
In this specific case, note that bash has a variable called PWD
that contains the current directory: $PWD
is equivalent to `pwd`
. (So do other shells, this is a standard feature.) So you can write your script like this:
#!/bin/bash
until [ "$PWD" = "/" ]; do
echo "$PWD"
ls && cd .. && ls
done
Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*
), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo"
and command substitutions "$(foo)"
(unless you specifically know you have not to).
In the general case, as other answers have mentioned already:
var=value
, not var = value
$
means “take the value of this variable”, so you don't use it when assigning: var=value
, not $var=value
Use Invalidations to clear the cache, you can put the path to the files you want to clear, or simply use wild cards to clear everything.
This can also be done using the API! http://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.html
The AWS PHP SDK now has the methods but if you want to use something lighter check out this library: http://www.subchild.com/2010/09/17/amazon-cloudfront-php-invalidator/
user3305600's solution doesn't work as setting it to zero is the equivalent of Using the Origin Cache Headers.
With Javascript SDK, you can change the code as below, this should be added after FB.init call.
// Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
alert('we are fine');
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
alert('please like us');
$("#container_notlike").show();
} else {
// the user isn't logged in to Facebook.
alert('please login');
}
});
FB.Event.subscribe('edge.create',
function(response) {
alert('You liked the URL: ' + response);
$("#container_like").show();
}
Yes, you absolutely can do this. For example:
public class PersonComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
// Assume no nulls, and simple ordinal comparisons
// First by campus - stop if this gives a result.
int campusResult = p1.getCampus().compareTo(p2.getCampus());
if (campusResult != 0)
{
return campusResult;
}
// Next by faculty
int facultyResult = p1.getFaculty().compareTo(p2.getFaculty());
if (facultyResult != 0)
{
return facultyResult;
}
// Finally by building
return p1.getBuilding().compareTo(p2.getBuilding());
}
}
Basically you're saying, "If I can tell which one comes first just by looking at the campus (before they come from different campuses, and the campus is the most important field) then I'll just return that result. Otherwise, I'll continue on to compare faculties. Again, stop if that's enough to tell them apart. Otherwise, (if the campus and faculty are the same for both people) just use the result of comparing them by building."
As an update to Austyn Mahoney's answer, configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see here.
Extending your code (assuming that the XML you want to send is in xmlString
) :
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
This one of many ways, not tested, but should work.
$link = 'http://mydomain.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0';
$linkParts = explode('&return=', $link);
$link = $linkParts[0];
De-structuring Assignment in ES6 would help here.For Ex:
let [arg1, arg2] = new Promise((resolve, reject) => {
resolve([argument1, argument2]);
});
Just put the CSS outside the PHP Tag. Here:
<html>
<head>
<title>Title</title>
<style type="text/css">
table {
margin: 8px;
}
</style>
</head>
<body>
<table>
<tr><th>ID</th><th>hashtag</th></tr>
<?php
while($row = mysql_fetch_row($result))
{
echo "<tr onmouseover=\"hilite(this)\" onmouseout=\"lowlite(this)\"><td>$row[0]</td> <td>$row[1]</td></tr>\n";
}
?>
</table>
</body>
</html>
Take note that the PHP tags are <?php
and ?>
.
apparently this problem got solved just by increasing queue size on my 3rd party smtp server. but the answer by Nip sounds like it is fairly usefull too
I'm surprised no one has mentioned filter_input, so here is Alix Axel's answer condensed to one-line:
function get_ip_address(&$keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'])
{
return empty($keys) || ($ip = filter_input(INPUT_SERVER, array_pop($keys), FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))? $ip : get_ip_address($keys);
}
Like stated in other answers, create a Twitter app to get the token, key and secret.
Using the code bellow, you can modify request parameters from one spot and avoid typos and similar errors (change $request
array in returnTweet()
function).
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function returnTweet(){
$oauth_access_token = "x";
$oauth_access_token_secret = "x";
$consumer_key = "x";
$consumer_secret = "x";
$twitter_timeline = "user_timeline"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
// create request
$request = array(
'screen_name' => 'budidino',
'count' => '3'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// make request
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return json_decode($json, true);
}
and then just call returnTweet()
Another way to do this is:
mongo mongodb://mongoDbIPorDomain:port
I found that the following worked for me - instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));
If you're looking for a particular string, put quotes around it:
awk '$1 == "findtext" {print $3}'
Otherwise, awk will assume it's a variable name.
If you're dealing with multiple (html 5) file uploads, I took the top suggested comment and modified it a little:
var files = $('#file1')[0].files;
var len = $('#file1').get(0).files.length;
for (var i = 0; i < len; i++) {
f = files[i];
var ext = f.name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('invalid extension!');
}
}
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
map.entrySet()
gives you a collection of Map.Entry
objects containing both key and value. you can then transform this into any collection object you like, such as new ArrayList(map.entrySet())
;
If you are using GCC, you can use the GNU extension asprintf function.
char* str;
asprintf (&str, "%i", 12313);
free(str);
Ideally, you should add a button/keybinding/menu to each webpage with an option to synchronize content.
To do so, you would keep track of resources that may need to be synchronized, and either use xhr to probe the images with a dynamic querystring, or create an image at runtime with src using a dynamic querystring. Then use a broadcasting mechanism to notify all components of the webpages that are using the resource to update to use the resource with a dynamic querystring appended to its url.
A naive example looks like this:
Normally, the image is displayed and cached, but if the user pressed the button, an xhr request is sent to the resource with a time querystring appended to it; since the time can be assumed to be different on each press, it will make sure that the browser will bypass cache since it can't tell whether the resource is dynamically generated on the server side based on the query, or if it is a static resource that ignores query.
The result is that you can avoid having all your users bombard you with resource requests all the time, but at the same time, allow a mechanism for users to update their resources if they suspect they are out of sync.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="mobile-web-app-capable" content="yes" />
<title>Resource Synchronization Test</title>
<script>
function sync() {
var xhr = new XMLHttpRequest;
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var images = document.getElementsByClassName("depends-on-resource");
for (var i = 0; i < images.length; ++i) {
var image = images[i];
if (image.getAttribute('data-resource-name') == 'resource.bmp') {
image.src = 'resource.bmp?i=' + new Date().getTime();
}
}
}
}
xhr.open('GET', 'resource.bmp', true);
xhr.send();
}
</script>
</head>
<body>
<img class="depends-on-resource" data-resource-name="resource.bmp" src="resource.bmp"></img>
<button onclick="sync()">sync</button>
</body>
</html>
I received the same error after installing android studio and trying to run hello world. I think you need to use the SDK Manager inside Android Studio to install some things first.
Open up Android Studio, and click on the SDK Manager in the toolbar.
Now install the SDK tools you need.
For each Android release you are targeting, hit the appropriate Android X.X folder and select (at a minimum):
The SDK Manager will run (this can take a while) and download and install the various SDKs.
Inside Android Studio, File->Project Structure will show you where your Android sdks are installed. As you can see mine is c:\users\Joe\AppData\Local\Android\sdk1.
If I navigate to C:\Users\Joe\AppData\Local\Android\sdk1\sources you can see the various Android SDKs installed there...
Note that datalist
is not the same as a select
. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.
Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.
If you want to disallow user input entirely, maybe select
would be a better choice.
To show only the text value of the option
in the dropdown, we use the inner text for it and leave out the value
attribute. The actual value that we want to send along is stored in a custom data-value
attribute:
To submit this data-value
we have to use an <input type="hidden">
. In this case we leave out the name="answer"
on the regular input and move it to the hidden copy.
<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist
and fetch its data-value
. That value is inserted into the hidden input and submitted.
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
The id answer
and answer-hidden
on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple input
s on the same page with one or more datalist
s providing suggestions.
Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue
to hiddenInput.value = ""
Working jsFiddle examples: plain javascript and jQuery
The easiest fix for me was to change SQL Agent job to run in 32-bit runtime. Go to SQL Job > right click properties > step > edit(step) > Execution option tab > Use 32 bit runtime
For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.
The Ruby Style Guide says it better than I could:
Use &&/|| for boolean expressions, and/or for control flow. (Rule of thumb: If you have to use outer parentheses, you are using the wrong operators.)
# boolean expression
if some_condition && some_other_condition
do_something
end
# control flow
document.saved? or document.save!
var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});
console.log(a[0]);
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).
You specify sigma
and hsize
in fspecial
.
%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)
public class MyThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Threado o =new Threado();
o.start();
Threade e=new Threade();
e.start();
}
}
class Threade extends Thread{
public void run(){
for(int i=2;i<10;i=i+2)
System.out.println("evens "+i);
}
}
class Threado extends Thread{
public void run(){
for(int i=1;i<10;i=i+2)
System.out.println("odds "+i);
}
}
OUTPUT :-
odds 1 odds 3 odds 5 odds 7 odds 9 evens 2 evens 4 evens 6 evens 8
This comes up a lot when your gemfile.lock has different versions of the gems installed on your machine. You may get a warning after running rake (or rspec or others) such as:
You have already activated rake 10.3.1, but your Gemfile requires rake 10.1.0. Prepending "bundle exec" to your command may solve this.
Prepending bundle exec
tells the bundler to execute this command regardless of the version differential. There isn't always an issue, however, you might run into problems.
Fortunately, there is a gem that solves this: rubygems-bundler.
$ gem install rubygems-bundler
$ $ gem regenerate_binstubs
Then try your rake, rspec, or whatever again.
All pages of the resulting document will be scaled to that size. The resulting file size is nearly identical to the original PDF, so I conclude, that image resolutions/compressions are not changed.
Hints:
I am not sure whether the "Export as PDF" menu item is available by default or only if Adobe Acrobat is installed.
My first trial was to use Preview App and print (!) into a new PDF, but this leads to additional margins around the page content.
Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.
I'd normally write the code without them. IMO, dead code tends to indicate sloppiness and/or lack of understanding.
Of course, I'd also consider something like:
char const *rets[] = {"blah", "foo", "bar"};
return rets[something];
Edit: even with the edited post, this general idea can work fine:
char const *rets[] = { "blah", "foo", "bar", "bar", "foo"};
if ((unsigned)something < 5)
return rets[something]
return "foobar";
At some point, especially if the input values are sparse (e.g., 1, 100, 1000 and 10000), you want a sparse array instead. You can implement that as either a tree or a map reasonably well (though, of course, a switch still works in this case as well).
You can
There are Two ways (both requiring device root) :
1- First way, open the device in adb window command
, and then run the following:
adb shell >
pm disable-user --user 0 com.android.systemui >
and to get it back just do the same but change disable
to enable
.
2- second way, add the following line to the end of your device's build.prop file :
qemu.hw.mainkeys = 1
then to get it back just remove it.
and if you don't know how to edit build.prop file:
Is it pausing, but you don't see your red color appear in the cell? Try this:
dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
dataGridView1.Refresh();
System.Threading.Thread.Sleep(1000);
Getting first and last elements in an array in Java
int[] a = new int[]{1, 8, 5, 9, 4};
First Element: a[0]
Last Element: a[a.length-1]
I also encountered the same problem but brew install python3
does not work properly to install pip3
.
brre will throw the warning The post-install step did not complete successfully
.
It has to do with homebrew does not have permission to /usr/local
Create the directory if not exist
sudo mkdir lib
sudo mkdir Frameworks
Give the permissions inside /usr/local
to homebrew so it can access them:
sudo chown -R $(whoami) $(brew --prefix)/*
Now ostinstall python3
brew postinstall python3
This will give you a successful installation
Thought I'd update this with a dplyr
solution
library(dplyr)
filter(studentdata, Drink == "water")
I'm trying to JMC to run the Flight Recorder (JFR) to profile NiFi on a remote server that doesn't offer a graphical environment on which to run JMC.
Based on the other answers given here, and upon much trial and error, here is what I'm supplying to the JVM (conf/bootstrap.conf)when I launch NiFi:
java.arg.90=-Dcom.sun.management.jmxremote=true
java.arg.91=-Dcom.sun.management.jmxremote.port=9098
java.arg.92=-Dcom.sun.management.jmxremote.rmi.port=9098
java.arg.93=-Dcom.sun.management.jmxremote.authenticate=false
java.arg.94=-Dcom.sun.management.jmxremote.ssl=false
java.arg.95=-Dcom.sun.management.jmxremote.local.only=false
java.arg.96=-Djava.rmi.server.hostname=10.10.10.92 (the IP address of my server running NiFi)
I did put this in /etc/hosts, though I doubt it's needed:
10.10.10.92 localhost
Then, upon launching JMC, I create a remote connection with these properties:
Host: 10.10.10.92
Port: 9098
User: (nothing)
Password: (ibid)
Incidentally, if I click the Custom JMX service URL, I see:
service:jmx:rmi:///jndi/rmi://10.10.10.92:9098/jmxrmi
This finally did it for me.
This problem was happening me, I had an external .jar in my libs folder called gson-2.2.2.jar but for some reason there were two of them, gson-2.2.2.jar and gson-2.2.2.jar(1), I simply deleted the latter and my project built fine again.
try to do this in the behind code
public diagboxclass()
{
List<object> list = new List<object>();
list = GetObjectList();
Imported.ItemsSource = null;
Imported.ItemsSource = list;
}
Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.
Instead of adding Reader("Name")
you add a new ListItem
. ListItem
has a Text
and a Value
property that you can set.
$(document).keyup(function (e) {
if ($(".input1:focus") && (e.keyCode === 13)) {
alert('ya!')
}
});
Or just bind to the input itself
$('.input1').keyup(function (e) {
if (e.keyCode === 13) {
alert('ya!')
}
});
To figure out which keyCode you need, use the website http://keycode.info
Using %.2f in printf. It only print 2 decimal points.
Example:
printf("%.2f", 37.777779);
Output:
37.77
instead of
http://localhost/xampp/htdocs/index.html
try just
http://localhost/index.html
or if index.html is saved in a folder in htdocs then
http://localhost/<folder-name>/index.html
Since the fmt:formatNumber
tag doesn't always yield the correct result, here is another JSP-only approach: It just formats the number as string and does the rest of the computation on the string, since that is easier and doesn't involve further floating point arithmetics.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
double[] numbers = { 0.0, 3.25, 3.75, 3.5, 2.5, -1.5, -2.5 };
pageContext.setAttribute("numbers", numbers);
%>
<html>
<body>
<ul>
<c:forEach var="n" items="${numbers}">
<li>${n} = ${fn:substringBefore(n, ".")} + ${n - fn:substringBefore(n, ".")}</li>
</c:forEach>
</ul>
</body>
</html>
I think you are looking for this
git reset --soft HEAD~1
It undoes the most recent commit whilst keeping the changes made in that commit to staging.
Similarly to Jakob's answer, you can use HTML tags. Just a note that the color
attribute of font
(<font color=...>
) is deprecated in HTML5. The following syntax would be HTML5-compliant:
This <span style="color:red">word</span> is not black.
Same caution that Jakob made probably still applies:
Be aware that this will not survive a conversion of the notebook to latex.
You can use like
My table is bellow like..
<table>
<thead>
<tr>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr th:each="user: ${staffList}">
<td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
</tr>
</tbody>
</table>
Here is my controller ..
@GetMapping(value = "/details-view/{userId}")
public String details(@PathVariable String userId) {
Logger.getLogger(getClass().getName()).info("userId-->" + userId);
return "user-details";
}
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
Off the top of my head, one way would be to grab all previous elements and count them.
$('td').click(function(){
var colIndex = $(this).prevAll().length;
var rowIndex = $(this).parent('tr').prevAll().length;
});
If you mean you want to see them like this:
WORKPLACEID NAME ADDRESS TELEPHONE
----------- ---------- -------------- ---------
1 HSBC Nugegoda Road 43434
2 HNB Bank Colombo Road 223423
then in SQL Plus you can set the column widths like this (for example):
column name format a10
column address format a20
column telephone format 999999999
You can also specify the line size and page size if necessary like this:
set linesize 100 pagesize 50
You do this by typing those commands into SQL Plus before running the query. Or you can put these commands and the query into a script file e.g. myscript.sql and run that. For example:
column name format a10
column address format a20
column telephone format 999999999
select name, address, telephone
from mytable;
Here's my take on this question following the msft documentation:
$gpParams = @{
Path = 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
ErrorAction = 'SilentlyContinue'
}
$release = Get-ItemProperty @gpParams | Select-Object -ExpandProperty Release
".NET Framework$(
switch ($release) {
({ $_ -ge 528040 }) { ' 4.8'; break }
({ $_ -ge 461808 }) { ' 4.7.2'; break }
({ $_ -ge 461308 }) { ' 4.7.1'; break }
({ $_ -ge 460798 }) { ' 4.7'; break }
({ $_ -ge 394802 }) { ' 4.6.2'; break }
({ $_ -ge 394254 }) { ' 4.6.1'; break }
({ $_ -ge 393295 }) { ' 4.6'; break }
({ $_ -ge 379893 }) { ' 4.5.2'; break }
({ $_ -ge 378675 }) { ' 4.5.1'; break }
({ $_ -ge 378389 }) { ' 4.5'; break }
default { ': 4.5+ not installed.' }
}
)"
This example works with all PowerShell versions and will work in perpetuity as 4.8 is the last .NET Framework version.
If you want to show it in a presentation then consider using requestFullscreen() method
let canvas = document.getElementById("canvas_id");
canvas.requestFullscreen();
that should make it fullscreen whatever the current circumstances are.
also check the support table https://caniuse.com/?search=requestFullscreen
In addition to specify a fixed amount of characters, you can also use *
which means that printf takes the number of characters from an argument:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char hello[] = "Hello world";
printf("message: '%.3s'\n", hello);
printf("message: '%.*s'\n", 3, hello);
printf("message: '%.*s'\n", 5, hello);
return 0;
}
Prints:
message: 'Hel'
message: 'Hel'
message: 'Hello'
Since curl 7.67.0 (2019-11-06) there is --no-progress-meter
, which does exactly this, and nothing else. From the man page:
--no-progress-meter Option to switch off the progress meter output without muting or otherwise affecting warning and informational messages like -s, --silent does. Note that this is the negated option name documented. You can thus use --progress-meter to enable the progress meter again. See also -v, --verbose and -s, --silent. Added in 7.67.0.
It's available in Ubuntu =20.04 and Debian =11 (Bullseye).
For a bit of history on curl's verbosity options, you can read Daniel Stenberg's blog post.
Simply
$("<style>")
.prop("type", "text/css")
.html("\
#my-window {\
position: fixed;\
z-index: 102;\
display:none;\
top:50%;\
left:50%;\
}")
.appendTo("head");
Noticed the back slashes? They are used to join strings that are on new lines. Leaving them out generates an error.
My problem was that the Id of the table is not AUTO_INCREMENT and I was trying to add range.
You can transfer value from controller using ViewData[""]
.
ViewData["hdnFlag"] = userId;
return View();
Now, In you view.
@{
var localVar = ViewData["hdnFlag"]
}
<input type="hidden" asp-for="@localVar" />
Hope this will help...
Somewhere in your initialisation put this code.
Array.prototype.contains = function contains(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] === obj) {
return true;
}
}
return false;
};
Then, you can use it this way:
<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>
I want change default directory dumpfile.
You could create a new directory and give it required privileges, for example:
SQL> CREATE DIRECTORY dmpdir AS '/opt/oracle';
Directory created.
SQL> GRANT read, write ON DIRECTORY dmpdir TO scott;
Grant succeeded.
To use the newly created directory, you could just add it as a parameter:
DIRECTORY=dmpdir
Oracle introduced a default directory from 10g R2, called DATA_PUMP_DIR, that can be used. To check the location, you could look into dba_directories:
SQL> select DIRECTORY_NAME, DIRECTORY_PATH from dba_directories where DIRECTORY_NAME = 'DATA_PUMP_DIR';
DIRECTORY_NAME DIRECTORY_PATH
-------------------- --------------------------------------------------
DATA_PUMP_DIR C:\app\Lalit/admin/orcl/dpdump/
SQL>
1) You cannot overload the method (Why doesn't ruby support method overloading?) so why not write a new method altogether?
2) I solved a similar problem using the splat operator * for an array of zero or more length. Then, if I want to pass a parameter(s) I can, it is interpreted as an array, but if I want to call the method without any parameter then I don't have to pass anything. See Ruby Programming Language pages 186/187
No, Integer
and String
are different types. To convert an integer to string use: String.valueOf(integer)
, or Integer.toString(integer)
for primitive, or Integer.toString()
for the object.
None is a special value in Python which usually designates an uninitialized variable. To test whether A does not have this particular value you use:
if A is not None
Falsey values are a special class of objects in Python (e.g. false, []). To test whether A is falsey use:
if not A
Thus, the two expressions are not the same And you'd better not treat them as synonyms.
P.S. None is also falsey, so the first expression implies the second. But the second covers other falsey values besides None. Now... if you can be sure that you can't have other falsey values besides None in A, then you can replace the first expression with the second.
Simply add container to sticky navbar ;
You can use this Autoit script to handle the login popup:
WinWaitActive("Authentication Required","","10")
If WinExists("Authentication Required") Then
Send("username{TAB}")
Send("Password{Enter}")
EndIf'
ToInt32 rounds. Casting to int just throws away the non-integer component.
Use the apply method of a function:-
function mainfunc (func){
window[func].apply(null, Array.prototype.slice.call(arguments, 1));
}
Edit: It occurs to me that this would be much more useful with a slight tweak:-
function mainfunc (func){
this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}
This will work outside of the browser (this
defaults to the global space). The use of call on mainfunc would also work:-
function target(a) {
alert(a)
}
var o = {
suffix: " World",
target: function(s) { alert(s + this.suffix); }
};
mainfunc("target", "Hello");
mainfunc.call(o, "target", "Hello");
create a new database with same name copy the .frm .ibd files into xampp/mysql/data/[databasename]/
you will need ibdata file as well which is found inside
xampp/mysql/data/ copy the previous ibdata1 file paste in the paste the file and replace it with the existing ibdata file
[caution: you may loose the contents of the database which are newly created in the new ibdata file]
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
I would avoid to put modifiers that are applied by default. As pointed out, it can lead to inconsistency and confusion.
The worst I saw is an interface with methods declared abstract
...
If you forget your password for SQL plus 10g then follow the steps :
If it asks your old password then type the one you have given while installing.
create two tabs, one with the formulas and then a second where you paste link the entire table. the second tab should have no problems when sorting!
An alternative solution is to execute an external command, obviously, this solution limits the portability of the application.
For example, for an application that runs on Windows, a PowerShell command can be executed through jPowershell, as shown in the following code:
public String getMyPublicIp() {
// PowerShell command
String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();
// Connection failed
if (powerShellOut.contains("InvalidOperation")) {
powerShellOut = null;
}
return powerShellOut;
}
If you want to ask based on condition:
var ask = true
window.onbeforeunload = function (e) {
if(!ask) return null
e = e || window.event;
//old browsers
if (e) {e.returnValue = 'Sure?';}
//safari, chrome(chrome ignores text)
return 'Sure?';
};
I know this question is a bit old but i would suggest to use some cachebraking hash in the url of the javascript. This works perfectly in production as well as during development because you can have both infinite cache times and intant updates when changes occur.
Lets assume you have a javascript file /js/script.min.js, but in the referencing html/php file you do not use the actual path but:
<script src="/js/script.<?php echo md5(filemtime('/js/script.min.js')); ?>.min.js"></script>
So everytime the file is changed, the browser gets a different url, which in turn means it cannot be cached, be it locally or on any proxy inbetween.
To make this work you need nginx to rewrite any request to /js/script.[0-9a-f]{32}.min.js to the original filename. In my case i use the following directive (for css also):
location ~* \.(css|js)$ {
expires max;
add_header Pragma public;
etag off;
add_header Cache-Control "public";
add_header Last-Modified "";
rewrite "^/(.*)\/(style|script)\.min\.([\d\w]{32})\.(js|css)$" /$1/$2.min.$4 break;
}
I would guess that the filemtime call does not even require disk access on the server as it should be in linux's file cache. If you have doubts or static html files you can also use a fixed random value (or incremental or content hash) that is updated when your javascript / css preprocessor has finished or let one of your git hooks change it.
In theory you could also use a cachebreaker as a dummy parameter (like /js/script.min.js?cachebreak=0123456789abcfef), but then the file is not cached at least by some proxies because of the "?".
I copy and change a part of your code as the below:
from pandas import read_csv, DataFrame
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from os import system
data = read_csv('D:/training.csv')
Y = data.Y
X = data.ix[:,"X0":"X33"]
dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(X, Y)
After making sure you have dtree, which means that the above code runs well, you add the below code to visualize decision tree:
Remember to install graphviz first: pip install graphviz
import graphviz
from graphviz import Source
dot_data = tree.export_graphviz(dtree, out_file=None, feature_names=X.columns)
graph = graphviz.Source(dot_data)
graph.render("name of file",view = True)
I tried with my data, visualization worked well and I got a pdf file viewed immediately.
<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top" Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
<StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
<Image HorizontalAlignment="Left" Source="image/bg/Save.png" Height="36" Width="124" />
<TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
</StackPanel>
</Button>
@robertklep's answer to check socket.connected is correct except for reconnect event, https://socket.io/docs/client-api/#event-reconnect
As the document said it is "Fired upon a successful reconnection." but when you check socket.connected
then it is false.
Not sure it is a bug or intentional.
Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like
Update addresses
Set cid = (
Select c.id
From customers As c
where c.id = a.id
)
Where Exists (
Select 1
From customers As C1
Where C1.id = addresses.id
)
However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:
Update addresses
Set cid = c.id
From addresses As a
Join customers As c
On c.id = a.id
For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.
If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.
Good luck!
(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)
This works and shows more than 255 characters in the message box.
Sub TestStrLength()
Dim s As String
Dim i As Integer
s = ""
For i = 1 To 500
s = s & "1234567890"
Next i
MsgBox s
End Sub
The message box truncates the string to 1023 characters, but the string itself can be very large.
I would also recommend that instead of using fixed variables names with numbers (e.g. Var1
, Var2
, Var3
, ... Var255
) that you use an array. This is much shorter declaration and easier to use - loops.
Here's an example:
Sub StrArray()
Dim var(256) As Integer
Dim i As Integer
Dim s As String
For i = 1 To 256
var(i) = i
Next i
s = "Tims_pet_Robot"
For i = 1 To 256
s = s & " """ & var(i) & """"
Next i
SecondSub (s)
End Sub
Sub SecondSub(s As String)
MsgBox "String length = " & Len(s)
End Sub
Updated this to show that a string can be longer than 255 characters and used in a subroutine/function as a parameter that way. This shows that the string length is 1443 characters. The actual limit in VBA is 2GB per string.
Perhaps there is instead a problem with the API that you are using and that has a limit to the string (such as a fixed length string). The issue is not with VBA itself.
Ok, I see the problem is specifically with the Application.OnTime method itself. It is behaving like Excel functions in that they only accept strings that are up to 255 characters in length. VBA procedures and functions though do not have this limit as I have shown. Perhaps then this limit is imposed for any built-in Excel object method.
Update:
changed ...longer than 256 characters...
to ...longer than 255 characters...
Print arbitrarily named remote fetch URLs:
git remote -v | grep fetch | awk '{print $2}'
Extension methods:
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool?>> expression)
{
return htmlHelper.CheckBoxFor<TModel>(expression, null);
}
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool?>> expression, object htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
bool? isChecked = null;
if (metadata.Model != null)
{
bool modelChecked;
if (Boolean.TryParse(metadata.Model.ToString(), out modelChecked))
{
isChecked = modelChecked;
}
}
return htmlHelper.CheckBox(ExpressionHelper.GetExpressionText(expression), isChecked??false , htmlAttributes);
}
|| is a logical or and | is a bit-wise or.
Working solution for all modern browsers.
input[type=checkbox] {_x000D_
transform: scale(1.5);_x000D_
}
_x000D_
<label><input type="checkbox"> Test</label>
_x000D_
Appearance:
No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.
Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.
As other said, bubbling and capturing describe in which order some nested elements receive a given event.
I wanted to point out that for the innermost element may appear something strange. Indeed, in this case the order in which the event listeners are added does matter.
In the following example, capturing for div2
will be executed first than bubbling; while bubbling for div4
will be executed first than capturing.
function addClickListener (msg, num, type) {
document.querySelector("#div" + num)
.addEventListener("click", () => alert(msg + num), type);
}
bubble = (num) => addClickListener("bubble ", num, false);
capture = (num) => addClickListener("capture ", num, true);
// first capture then bubble
capture(1);
capture(2);
bubble(2);
bubble(1);
// try reverse order
bubble(3);
bubble(4);
capture(4);
capture(3);
_x000D_
#div1, #div2, #div3, #div4 {
border: solid 1px;
padding: 3px;
margin: 3px;
}
_x000D_
<div id="div1">
div 1
<div id="div2">
div 2
</div>
</div>
<div id="div3">
div 3
<div id="div4">
div 4
</div>
</div>
_x000D_
Should the benchmark measure time/iteration or iterations/time, and why?
It depends on what you are trying to test.
If you are interested in latency, use time/iteration and if you are interested in throughput, use iterations/time.
On XP, I clicked the Advanced
button on the Schedule
tab. There is a checkbox for Repeat task
. The default is every 10 minutes.
Additionally, you can create scheduled task via the command line. I haven't tried this myself, but it looks like you'd want something along the lines of (not tested):
schtasks /create /tn "Some task name" /tr "app.exe" /sc HOURLY
Based on the answer from Luis, you can do something more like the default findBy method.
First, create a default repository class that is going to be used by all your entities.
/* $config is the entity manager configuration object. */
$config->setDefaultRepositoryClassName( 'MyCompany\Repository' );
Or you can edit this in config.yml
doctrine: orm: default_repository_class: MyCompany\Repository
Then:
<?php
namespace MyCompany;
use Doctrine\ORM\EntityRepository;
class Repository extends EntityRepository {
public function findByNot( array $criteria, array $orderBy = null, $limit = null, $offset = null )
{
$qb = $this->getEntityManager()->createQueryBuilder();
$expr = $this->getEntityManager()->getExpressionBuilder();
$qb->select( 'entity' )
->from( $this->getEntityName(), 'entity' );
foreach ( $criteria as $field => $value ) {
// IF INTEGER neq, IF NOT notLike
if($this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldMapping($field)["type"]=="integer") {
$qb->andWhere( $expr->neq( 'entity.' . $field, $value ) );
} else {
$qb->andWhere( $expr->notLike( 'entity.' . $field, $qb->expr()->literal($value) ) );
}
}
if ( $orderBy ) {
foreach ( $orderBy as $field => $order ) {
$qb->addOrderBy( 'entity.' . $field, $order );
}
}
if ( $limit )
$qb->setMaxResults( $limit );
if ( $offset )
$qb->setFirstResult( $offset );
return $qb->getQuery()
->getResult();
}
}
The usage is the same than the findBy method, example:
$entityManager->getRepository( 'MyRepo' )->findByNot(
array( 'status' => Status::STATUS_DISABLED )
);
AFAIK, I don't think this is possible with a direct method naming query. You can however use the built in sorting mechanism, using the Sort
class. The repository has a findAll(Sort)
method that you can pass an instance of Sort
to. For example:
import org.springframework.data.domain.Sort;
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(sortByIdAsc());
}
private Sort sortByIdAsc() {
return new Sort(Sort.Direction.ASC, "id");
}
}
Here's an answer that actually gives the solution the OP asked for:
>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1])
(321, 0)
Using d.iteritems()
will be more efficient for larger dictionaries, however.
For manually resetting the password in Wordpress DB, a simple MD5 hash is sufficient. (see reason below)
To prevent breaking backwards compatibility, MD5-hashed passwords stored in the database are still valid. When a user logs in with such a password, WordPress detects MD5 was used, rehashes the password using the more secure method, and stores the new hash in the database.
Source: http://eamann.com/tech/wordpress-password-hashing/
Update: this was an answer posted in 2014. I don't know if it still works for the latest version of WP since I don't work with WP anymore.
Since Docker 1.13.x you can use Docker container prune:
docker container prune
This will remove all stopped containers and should work on all platforms the same way.
There is also a Docker system prune:
docker system prune
which will clean up all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes, in one command.
For older Docker versions, you can string Docker commands together with other Unix commands to get what you need. Here is an example on how to clean up old containers that are weeks old:
$ docker ps --filter "status=exited" | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm
To give credit, where it is due, this example is from https://twitter.com/jpetazzo/status/347431091415703552.
Try psrinfo to find the processor type and the number of physical processors installed on the system.
The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.
Here is my solution for Java:
public List<String> getBoundedRectangleOfElement(WebElement we)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
List<String> bounds = (ArrayList<String>) je.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
System.out.println("top: " + bounds.get(1));
return bounds;
}
And then, to scroll, you call it like this:
public void scrollToElementAndCenterVertically(WebElement we)
{
List<String> bounds = getBoundedRectangleOfElement(we);
Long totalInnerPageHeight = getViewPortHeight(driver);
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}
Based off this answer from Lucas Cerro I calculated the dimensions using the ratios in the Android docs, using the baseline in the answer. I hope this helps someone else coming to this post!
You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).
Consider how your application should respond to various cases.
The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.
Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.
If you want to right-align in a form, you can try:
| Option | Description |
| ------:| -----------:|
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. |
https://learn.getgrav.org/content/markdown#right-aligned-text
An old post but thought i would share an answer for anyone looking.
And because when you use absolute
things can go wrong.
What I would do is
HTML
<div id="parentDiv"></div>
<div class="childDiv"></div>
The Css
parentDiv{
}
childDiv{
height:40px;
margin-top:-20px;
}
And that would just sit that bottom div back up into the parent div. safe for most browsers too
Ohh what a mess! My advise: When its comes to messy poms or project packaging, Eclipse is really bad at showing the real problem. It will tell you some dependencies are missing, when in fact for pom is malformed or some other problem are present in your pom.
Leave Eclipse alone are run a maven install. You will get to the real problem really quick!
I think we should use the following rule to determine when we talk about Design vs Architecture: If the elements of a software picture you created can be mapped one to one to a programming language syntactical construction, then is Design, if not is Architecture.
So, for example, if you are seeing a class diagram or a sequence diagram, you are able to map a class and their relationships to an Object Oriented Programming language using the Class syntactical construction. This is clearly Design. In addition, this might bring to the table that this discussion has a relation with the programming language you will use to implement a software system. If you use Java, the previous example applies, as Java is an Object Oriented Programming Language. If you come up with a diagram that shows packages and its dependencies, that is Design too. You can map the element (a package in this case) to a Java syntactical construction.
Now, suppose your Java application is divided in modules, and each module is a set of packages (represented as a jar file deployment unit), and you are presented with a diagram containing modules and its dependencies, then, that is Architecture. There isn’t a way in Java (at least not until Java 7) to map a module (a set of packages) to a syntactical construction. You might also notice that this diagram represents a step higher in the level of abstraction of your software model. Any diagram above (coarse grained than) a package diagram, represents an Architectural view when developing in the Java programming language. On the other hand, if you are developing in Modula-2, then, a module diagram represents a Design.
(A fragment from http://www.copypasteisforword.com/notes/software-architecture-vs-software-design)
Here are a couple of ways.
The first will order things based on the order seen in the data frame:
x$variable <- factor(x$variable, levels=unique(as.character(x$variable)) )
The second orders the levels based on another variable (value in this case):
x <- transform(x, variable=reorder(variable, -value) )
You could download a free GeoIP database and lookup the IP address locally, or you could use a third party service and perform a remote lookup. This is the simpler option, as it requires no setup, but it does introduce additional latency.
One third party service you could use is mine, http://ipinfo.io. They provide hostname, geolocation, network owner and additional information, eg:
$ curl ipinfo.io/8.8.8.8
{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"loc": "37.385999999999996,-122.0838",
"org": "AS15169 Google Inc.",
"city": "Mountain View",
"region": "CA",
"country": "US",
"phone": 650
}
Here's a PHP example:
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $details->city; // -> "Mountain View"
You can also use it client-side. Here's a simple jQuery example:
$.get("https://ipinfo.io/json", function (response) {_x000D_
$("#ip").html("IP: " + response.ip);_x000D_
$("#address").html("Location: " + response.city + ", " + response.region);_x000D_
$("#details").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3>_x000D_
_x000D_
<hr/>_x000D_
<div id="ip"></div>_x000D_
<div id="address"></div>_x000D_
<hr/>Full response: <pre id="details"></pre>
_x000D_
I submitted an updated version of a patch to the PostgreSQL JDBC driver to enable this a few years back. You'll have to build the PostreSQL JDBC driver from source (after adding in the patch) to use it:
http://archives.postgresql.org/pgsql-jdbc/2008-07/msg00012.php
You could write a script to update the FK's for you.. check out this blog: http://multunus.com/2011/03/how-to-easily-merge-two-identical-mysql-databases/
They have a clever script to use the information_schema tables to get the "id" columns:
SET @db:='id_new';
select @max_id:=max(AUTO_INCREMENT) from information_schema.tables;
select concat('update ',table_name,' set ', column_name,' = ',column_name,'+',@max_id,' ; ') from information_schema.columns where table_schema=@db and column_name like '%id' into outfile 'update_ids.sql';
use id_new
source update_ids.sql;
I put this into my log4j config file
log4j.logger.org.apache.http.wire=WARN
This limits the output to Warning level or above
To break out from a ruby block simply use return
keyword
return if value.nil?
private Color FromHex(string hex)
{
if (hex.StartsWith("#"))
hex = hex.Substring(1);
if (hex.Length != 6) throw new Exception("Color not valid");
return Color.FromArgb(
int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
}
var x = $($('div').html($('#container').clone())).html();
In python3 the following works:
>>> v=10.4
>>> print('% 6.2f' % v)
10.40
>>> print('% 12.1f' % v)
10.4
>>> print('%012.1f' % v)
0000000010.4
public class Example extends Activity
{
private ListView lv;
ArrayList<String> arrlist=new ArrayList<String>();
//let me assume that you are putting the values in this arraylist
//Now convert your arraylist to array
//You will get an exmaple here
//http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html
private String arr[]=convert(arrlist);
@Override
public void onCreate(Bundle bun)
{
super.onCreate(bun);
setContentView(R.layout.main);
lv=(ListView)findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
}
}