The code you've already tried:
document.getElementById("gift-close").click();
...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:
onload
handler for the window. http://jsfiddle.net/LKNYg/So:
$(document).ready(function() {
document.getElementById("gift-close").click();
// OR
$("#gift-close")[0].click();
});
After looking at the code you're having typos, here is the updated code
var clicks = 0; // should be var not int
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit
}
Note: Don't use in-built handlers, as .click()
is javascript function try giving different name like clickME()
This is an extension to Langdon's answer with a directive approach to the problem. If you're going to have multiple galleries on the page this may be one way to go about it without much fuss.
Usage:
<gallery images="items"></gallery>
<gallery images="cats"></gallery>
You need to set the inflated view "Clickable" and "able to listen to click events" in your adapter class getView() method.
convertView = mInflater.inflate(R.layout.list_item_text, null);
convertView.setClickable(true);
convertView.setOnClickListener(myClickListener);
and declare the click listener in your ListActivity as follows,
public OnClickListener myClickListener = new OnClickListener() {
public void onClick(View v) {
//code to be written to handle the click event
}
};
This holds true only when you are customizing the Adapter by extending BaseAdapter.
Refer the ANDROID_SDK/samples/ApiDemos/src/com/example/android/apis/view/List14.java for more details
create an intent and set an action for it while passing the url to the intent
yourbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String theurl = "http://google.com";
Uri urlstr = Uri.parse(theurl);
Intent urlintent = new Intent();
urlintent.setData(urlstr);
urlintent.setAction(Intent.ACTION_VIEW);
startActivity(urlintent);
You could also use CSS pseudo elements to pick and display your labels from all your checkbox's value attributes (respectively).
Edit: This will only work with webkit and blink based browsers (Chrome(ium), Safari, Opera....) and thus most mobile browsers. No Firefox or IE support here.
This may only be useful when embedding webkit/blink onto your apps.
<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
content: attr(value);
margin: -3px 15px;
vertical-align: top;
white-space:nowrap;
display: inline-block;
}
</style>
All pseudo element labels will be clickable.
Add a
-webkit-animation-play-state: paused;
to your CSS file, then you can control whether the animation is running or not by using this JS line:
document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";
if you want the animation to run once, every time you click. Remember to set
-webkit-animation-iteration-count: 1;
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
If you are using jQuery, you can do it with jQuery.trigger
http://api.jquery.com/trigger/
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<a id="foo" onclick="action()"></a>
<script type="text/javascript">
function action(){
window.location.replace("http://stackoverflow.com/q/9081426/5526354")
}
$("#foo").trigger("click");
</script>
</body>
</html>
In my case, onclick event was firing multiple times coz I had made a generic event handler comparatively as
`$('div').on("click", 'a[data-toggle="tab"]',function () {
console.log("dynamic bootstrap tab clicked");
var href = $(this).attr('href');
window.location.hash = href;
});`
changed to
`$('div#mainData').on("click", 'a[data-toggle="tab"]',function () {
console.log("dynamic bootstrap tab clicked");
var href = $(this).attr('href');
window.location.hash = href;
});`
and also have to make separate handlers for static and dynamic clicks, for static tab click
`$('a[data-toggle="tab"]').on("click",function () {
console.log("static bootstrap tab clicked");
var href = $(this).attr('href');
window.location.hash = href;
});`
<div onclick="location.href='#';" style="cursor: pointer;">
</div>
The conventional way of handling this doesn't play well with ES6. You can do this instead:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
this.delete(clickedElement.data('id'));
});
Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
const targetElement = clickedElement.closest('.delete');
this.delete(targetElement.data('id'));
});
Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.
Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):
onClick=""
OR
The element css needs to have the following declaration:
cursor:pointer
Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working
Use mouseover instead hover.
$('#target').on('click mouseover', function () {
// Do something for both
});
Check Safari developer reference on Touch class.
According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX
and not PageX
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
This is all you need: http://api.jquery.com/click/
Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.
I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...
For example in order to change it's background to yellow:
$("#"+String(this.id)).css("background-color","yellow");
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.
$('html').click(function(e){
if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
// clicked menu content or children
} else {
// didnt click menu content
}
});
my actual code:
$('html').click(function(e){
if (e.target.id != 'datepicker'
&& $(e.target).parents('#datepicker').length == 0
&& !$(e.target).hasClass('datepicker')
) {
$('#datepicker').remove();
}
});
$('.update-cart').click(function(e) {
updateCartWidget();
e.stopPropagation();
e.preventDefault();
});
$('.update-cart').click(function() {
updateCartWidget();
return false;
});
The following methods achieve the exact same thing.
button1, button2 and button3 have same even handler
private void button1_Click(Object sender, EventArgs e)
{
Button btnSender = (Button)sender;
if (btnSender == button1 || btnSender == button2)
{
//some code here
}
else if (btnSender == button3)
//some code here
}
You can do :
document.forms["loginForm"].submit()
But this won't call the onclick
action of your button, so you will need to call it by hand.
Be aware that you must use the name
of your form and not the id
to access it.
Is there a way to remove all previous click events that have been assigned to a button?
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
public MainWindow()
{
// This button needs to exist on your form.
myButton.Click += myButton_Click;
}
void myButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Message here");
this.Close();
}
This is the most important part in the code provided in the original post.
Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
To explain it step by step:
Button one = (Button) this.findViewById(R.id.button1);
First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById
, passing the Id we assigned to it (in this example's case: R.id.button1
), to get the button that we need. We cast it as a Button
so that it is easy to assign it to the variable one
that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
This is how to initialize a MediaPlayer
. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create()
method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho
. We declare it as final
. Jon Skeet provided a great explanation on why we do so here.
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//code
}
});
Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener
of our button one
. Inside is only one method, onClick()
which contains what instructions the button should do on click.
public void onClick(View v) {
mp.start();
}
To play the sound, we call MediaPlayer's start()
method. This method starts the playback of the sound.
There, you can now play a sound on button click in Android!
Bonus part:
As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release()
method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener
to our mp
like so:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//code
}
});
Inside the onCompletion
method, we release it like so:
public void onCompletion(MediaPlayer mp) {
mp.release();
}
There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment
or Activity
that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.
First. You should put your statements inside a block, and in this case the onCreate method.
Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.
Third, put the logic to play the sound inside the onClick.
In summary:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BasicScreenActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
}
}
Since this question is ranked #1 in Google for "triggering a click on an <a>
element" and no answer actually mentions how you do that, this is how you do it:
$('#titleee a')[0].click();
Explanation: you trigger a click
on the underlying html-element, not the jQuery-object.
You're welcome googlers :)
The jQuery way to click a link is
$('#LinkID').click();
For mailTo link, you have to write the following code
$('#LinkID')[0].click();
You are missing #
hash character before id selectors, this should work:
$(document).ready(function() {
$("#div2").hide();
$("#preview").click(function() {
$("#div1").hide();
$("#div2").show();
});
});
In case anyone else is running in to the same problem, the only solution I could find that satisfied me was to have the canvas cover everything and then to raise the Z-index of all clickable elements. You can't draw on them, but at least they are clickable...
Why not try something like this?
$('#menu li a').on('click', function(){
$('#menu li a.current').removeClass('current');
$(this).addClass('current');
});
JavaScript/jQuery doesn't support the default behavior of links "clicked" programmatically.
Instead, you can create a form and submit it. This way you don't have to use window.location
or window.open
, which are often blocked as unwanted popups by browsers.
This script has two different methods: one that tries to open three new tabs/windows (it opens only one in Internet Explorer and Chrome, more information is below) and one that fires a custom event on a link click.
Here is how:
<html>
<head>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<button id="testbtn">Test</button><br><br>
<a href="https://google.nl">Google</a><br>
<a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a><br>
<a href="https://stackoverflow.com/">Stack Overflow</a>
</body>
</html>
$(function()
{
// Try to open all three links by pressing the button
// - Firefox opens all three links
// - Chrome only opens one of them without a popup warning
// - Internet Explorer only opens one of them WITH a popup warning
$("#testbtn").on("click", function()
{
$("a").each(function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
});
});
// Or click the link and fire a custom event
// (open your own window without following
// the link itself)
$("a").on("click", function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
// The location given in the link itself
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
// Prevent the link from opening normally
return false;
});
});
For each link element, it:
Now you have a new tab/window loading "https://google.nl"
(or any URL you want, just replace it). Unfortunately when you try to open more than one window this way, you get an Popup blocked
messagebar when trying to open the second one (the first one is still opened).
More information on how I got to this method is found here:
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
I was facing a similar issue how to click a button, instead of a link. It did not success in the methods .trigger('click') or [0].click(), and I did not know why. At last, the following was working for me:
$('#elementid').mousedown();
You are assigning an onclick
event inside an function.
That means once the function has executed once, the second onclick
event is assigned to the element as well.
Either assign the function
onclick
or use jqueryclick()
.
There's no need to have both
This might be a better fix for some people.
$(".menu_link").click(function(){
// show menu code
});
$(".menu_link").mouseleave(function(){
//hide menu code, you may add a timer for 3 seconds before code to be run
});
I know mouseleave does not only mean a click outside, it also means leaving that element's area.
Once the menu itself is inside the menu_link
element then the menu itself should not be a problem to click on or move on.
Most fastest and easy way:
$('#myCheckbox').change(function(){
alert(this.checked);
});
$el[0].checked;
$el - is jquery element of selection.
Enjoy!
As mentioned by Seeker, the problem could have been that you setup the click()
function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.
An important point is to run such scripts after the document is ready. This is done by placing the click()
initialization within that other function as in:
jQuery(document).ready(function()
{
jQuery("body").click(function()
{
// ... your click code here ...
});
});
This is usually the best method, especially if you include your JavaScript code in your <head>
tag. If you include it at the very bottom of the page, then the ready()
function is less important, but it may still be useful.
find the document scroll move difference (both horizontal and vertical ) touchstart and touchend , if one of them is larger than 1 pixel, then it is move rather than click
var touchstartverscrollpos , touchstarthorscrollpos;
$('body').on('touchstart','.thumbnail',function(e){
touchstartverscrollpos = $(document).scrollTop();
touchstarthorscrollpos = $(document).scrollLeft();
});
$('body').on('touchend','.thumbnail',function(e){
var touchendverscrollpos = $(document).scrollTop();
var touchendhorscrollpos = $(document).scrollLeft();
var verdiff = touchendverscrollpos - touchstartverscrollpos;
var hordiff = touchendhorscrollpos - touchstarthorscrollpos;
if (Math.abs(verdiff) <1 && Math.abs(hordiff)<1){
// do you own function () here
e.stopImmediatePropagation();
return false;
}
});
For python, use the
from selenium.webdriver import ActionChains
and
ActionChains(browser).click(element).perform()
Just a quick check, if you are using client-side templating engine such as handlebars, your js will load after document.ready, hence there will be no element to bind the event to, therefore either use onclick handler or use it on the body and check for current target
If you want to reset the selected options
$('select option:selected').removeAttr('selected');
If you actually want to remove the options (although I don't think you mean this).
$('select').empty();
Substitute select
for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select>
elements on the page
Try this:
$("#test-element").on("click" ,function() {
alert("click");
});
The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.
On mobile iOS the click event does not bubble to the document body and thus cannot be used with .live() events. If you have to use a non native click-able element like a div or section is to use cursor: pointer; in your css for the non-hover on the element in question. If that is ugly you could look into delegate().
Unless you want your button to be a submit button, code it as Remove items That should solve your problem. If you do not specify the type for a button element, it will default to a submit button, leading to the problem you identified.
As far as ilearned from internet and some friends .on() is used when you dynamically add elements. But when i used it in a simple login page where click event should send AJAX to node.js and at return append new elements it started to call multi-AJAX calls. When i changed it to click() everything went right. Actually i did not faced with this problem before.
const {Builder, By, Key, util} = require('selenium-webdriver')
// FUNÇÃO PARA PAUSA
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
// chrome
let driver = await new Builder().forBrowser("firefox").build()
await driver.get('https://www.google.com.br')
// await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)
await sleep(2000)
await driver.findElement(By.name('q')).sendKeys('Selenium')
await sleep(2000)
// CLICAR
driver.findElement(By.name('btnK')).click()
}
example()
Com essas últimas linhas, você pode clicar !
What you need to do is this:
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[][] lists = new int[][] { list1 , list2 , list3 , list4 };
Another alternative would be to create a List<int[]>
type:
List<int[]> data=new List<int[]>(){list1,list2,list3,list4};
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
Try this:
Array.prototype.getItemCount = function(item) {
var counts = {};
for(var i = 0; i< this.length; i++) {
var num = this[i];
counts[num] = counts[num] ? counts[num]+1 : 1;
}
return counts[item] || 0;
}
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);
You don't need EXEC clause. Simply use
proc_name paramValue1, paramValue2
(and you need commas as Misnomer mentioned)
None of these solutions quite worked for me. My original audio was being overwritten, or I was getting an error like "failed to map memory" with the more complex 'amerge' example. It seems I needed -filter_complex amix.
ffmpeg -i videowithaudioyouwanttokeep.mp4 -i audiotooverlay.mp3 -vcodec copy -filter_complex amix -map 0:v -map 0:a -map 1:a -shortest -b:a 144k out.mkv
Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.
<h3>NATO Phonetic Alphabet</h3>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th>Letter</th>
<th>Phonetic Letter</th>
</tr>
</thead>
<tr>
<th>A</th>
<th>Alpha</th>
</tr>
<tr>
<td>B</td>
<td>Bravo</td>
</tr>
<tr>
<td>C</td>
<td>Charlie</td>
</tr>
</table>
Posting it from my project.
<select name="parent" id="parent"><option value="0">None</option>
<?php
$select="select=selected";
$allparent=mysql_query("select * from tbl_page_content where parent='0'");
while($parent=mysql_fetch_array($allparent))
{?>
<option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
<?php
}
?></select>
Short answer:
x.addEventListener("click", function(e){myfunction(e, param1, param2)});
...
function myfunction(e, param1, param1) {
...
}
The MAC address (the low-level local network interface address) does not survive hops through IP routers. You can't find the client MAC address from a remote server.
In a local subnet, the MAC addresses are mapped to IP addresses through the ARP system. Interfaces on the local net know how to map IP addresses to MAC addresses. However, when your packets have been routed on the local subnet to (and through) the gateway out to the "real" Internet, the originating MAC address is lost. Simplistically, each subnet-to-subnet hop of your packets involve the same sort of IP-to-MAC mapping for local routing in each subnet.
I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.
Solution:
First of all find the application which is causing heavy memory usage.
You can find this in the Details section of the Task Manager.
Next.
If this solution works for you please add a comment so that I can know.
Not sure if my solution is frowned upon or not, but I use a bound service to persist ViewModel state. Whether you store it in memory in the service or persist and retrieve it from a SQLite database depends on your requirements. This is what services of any flavor do, they provide services such as maintaining application state and abstract common business logic.
Because of memory and processing constraints inherent on mobile devices, I treat Android views in a similar way to a web page. The page does not maintain state, it is purely a presentation layer component whose only purpose is to present application state and accept user input. Recent trends in web app architecture employ the use of the age-old Model, View, Controller (MVC) pattern, where the page is the View, domain data is the model, and the controller sits behind a web service. The same pattern can be employed in Android with the View being, well ... the View, the model is your domain data, and the Controller is implemented as an Android bound service. Whenever you want a view to interact with the controller, bind to it on start/resume and unbind on stop/pause.
This approach gives you the added bonus of enforcing the Separation of Concern design principle in that all of you application business logic can be moved into your service which reduces duplicated logic across multiple views and allows the view to enforce another important design principle, Single Responsibility.
The +
operator should do the trick just fine. Keep something in mind though, if one of the columns is null or does not have any value, it will give you a NULL
result. Instead, combine +
with the function COALESCE
and you'll be set.
Here is an example:
SELECT COALESCE(column1,'') + COALESCE(column2,'') FROM table1.
For this example, if column1
is NULL
, then the results of column2
will show up, instead of a simple NULL
.
Hope this helps!
Swift 3
When you make the @IBAction:
@IBAction func btnAction(_ sender: UIButton) {
sender.setTitle("string goes here", for: .normal)
}
This sets the sender as UIButton (instead of Any) so it targets the btnAction as a UIButton
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
A boilerplate is a unit of writing that can be reused over and over without change. By extension, the idea is sometimes applied to reusable programming, as in “boilerplate code
You can use vertical-align and floating.
In most cases you want to vertical-align: middle, the image.
Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align
vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;
For middle, the definition is: The element is placed in the middle of the parent element.
So you might want to apply that to all elements within the element.
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
For me the first answer appears a bit confusing, so to make it short and clean:
npm install <package_name>
saves any specified packages into dependencies by default. Additionally, you can control where and how they get saved with some additional flags:
npm install <package_name> --no-save
Prevents saving to dependencies.
npm install <package_name> ---save-dev
updates the devDependencies
in your package. These are only used for local testing and development.
You can read more at in the dcu
For those who are using Eclipse IDE.
After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,
You will need to tell Eclipse IDE about the following
Here is how you go about it.
To Add mysql.h
1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql
To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.
2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient
3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.
Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql
a="Helloo"
print(a[:-1])
In the above code, [:-1] declares to print from the starting till the maximum limit-1.
OUTPUT :
>>> Hello
Note: Here a [:-1] is also the same as a [0:-1] and a [0:len(a)-1]
a="I Am Siva"
print(a[2:])
OUTPUT:
>>> Am Siva
In the above code a [2:] declares to print a from index 2 till the last element.
Remember that if you set the maximum limit to print a string, as (x) then it will print the string till (x-1) and also remember that the index of a list or string will always start from 0.
Thanks to Stack user over this explanation, I've got this working even on Android 4.1.1
((View)myView.getParent()).requestLayout();
myView.bringToFront();
On my dynamic use, for example, I did
public void onMyClick(View v)
{
((View)v.getParent()).requestLayout();
v.bringToFront();
}
And Bamm !
My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.
In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...
It also wraps shutil.rmtree
:
$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib
# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)
# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)
you can find it on github or PyPi
Disclaimer: I'm the author of the pathlib3x library.
Use $(this).find()
, or pass this in context, using jQuery context with selector.
Using $(this).find()
$(".class").click(function(){
$(this).find(".subclass").css("visibility","visible");
});
Using this
in context, $( selector, context )
, it will internally call find function, so better to use find on first place.
$(".class").click(function(){
$(".subclass", this).css("visibility","visible");
});
As long as the script is after the img
, then:
var youtubeimgsrc = document.getElementById("youtubeimg").src;
See getElementById
in the DOM specification.
If the script is before the img
, then of course the img
doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body
element.
Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:
<img id="foo" src="/images/example.png">
...the src
reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com
, document.getElementById("foo").src
would give you "http://www.example.com/images/example.png"
.
If you wanted the src
attribute's content as is, without being resolved, you'd use getAttribute
instead: document.getElementById("foo").getAttribute("src")
. That would give you "/images/example.png"
with my example above.
If you have an absolute URL, like the one in your question, it doesn't matter.
If you want to debug IAB what do you have to do is:
Submit to google play a version of your app with the IAB permission on the manifest:
Add a product to your app on google play: Administering In-app Billing
Set a custom debug keystore signed: Configure Eclipse to use signed keystore
I had similar issue but got solved when I corrected my zookeeper.yaml
file which had the service name mismatch with file deployment's container names. It got resolved by making them same.
apiVersion: v1
kind: Service
metadata:
name: zk1
namespace: nbd-mlbpoc-lab
labels:
app: zk-1
spec:
ports:
- name: client
port: 2181
protocol: TCP
- name: follower
port: 2888
protocol: TCP
- name: leader
port: 3888
protocol: TCP
selector:
app: zk-1
---
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
name: zk-deployment
namespace: nbd-mlbpoc-lab
spec:
template:
metadata:
labels:
app: zk-1
spec:
containers:
- name: zk1
image: digitalwonderland/zookeeper
ports:
- containerPort: 2181
env:
- name: ZOOKEEPER_ID
value: "1"
- name: ZOOKEEPER_SERVER_1
value: zk1
Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); return des.data.Count.ToString();
You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView.SelectedRows)
{
string value1 = row.Cells[0].Value.ToString();
string value2 = row.Cells[1].Value.ToString();
//...
}
}
You can also walk through the column collection instead of typing indexes...
All right after trying every solution on the web I ended up figuare out the issue using very simple method , first I cheked php-fpm err log
cat /var/log/php5-fpm.log
and the most repeated error was
" WARNING: [pool www] server reached pm.max_children setting (5), consider raising it "
I edit PHP-fpm pools setting
nano /etc/php5/fpm/pool.d/www.conf
I chenged This Line
pm.max_children = 5
To new Value
pm.max_children = 10
BTW I'm using low end VPS with 128MB ram As everyone else I was thinkin redusing pm.max_children
will make my server run faster consume less memory , but the setting we using were too low tho even start PHP-fpm process .
I hope this help others since I found this after 24 hour testing and failing , ever my webhost support were not able to solve the issue .
Keep your scripts right before </body>
. Async can be used with scripts located there in a few circumstances (see discussion below). Defer won't make much of a difference for scripts located there because the DOM parsing work has pretty much already been done anyway.
Here's an article that explains the difference between async and defer: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/.
Your HTML will display quicker in older browsers if you keep the scripts at the end of the body right before </body>
. So, to preserve the load speed in older browsers, you don't want to put them anywhere else.
If your second script depends upon the first script (e.g. your second script uses the jQuery loaded in the first script), then you can't make them async without additional code to control execution order, but you can make them defer because defer scripts will still be executed in order, just not until after the document has been parsed. If you have that code and you don't need the scripts to run right away, you can make them async or defer.
You could put the scripts in the <head>
tag and set them to defer
and the loading of the scripts will be deferred until the DOM has been parsed and that will get fast page display in new browsers that support defer, but it won't help you at all in older browsers and it isn't really any faster than just putting the scripts right before </body>
which works in all browsers. So, you can see why it's just best to put them right before </body>
.
Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading. The most often cited example for using async is an analytics script like Google Analytics that you don't want anything to wait for and it's not urgent to run soon and it stands alone so nothing else depends upon it.
Usually the jQuery library is not a good candidate for async because other scripts depend upon it and you want to install event handlers so your page can start responding to user events and you may need to run some jQuery-based initialization code to establish the initial state of the page. It can be used async, but other scripts will have to be coded to not execute until jQuery is loaded.
If you have Symbol
properties in your object, that should be filtered too, you can not use: Object.keys
Object.entries
Object.fromEntries
, ... because:
Symbol
keys are not enumerable !
You could use Reflect.ownKeys
and filter keys in reduce
Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && {...a, [k]: o[k]} || a, {});
(Open DevTools for log output - Symbols are not logged on Stackoverflow UI)
const bKey = Symbol('b_k');
const o = {
a: 1,
[bKey]: 'b',
c: [1, 3],
[Symbol.for('d')]: 'd'
};
const allow = ['a', bKey, Symbol.for('d')];
const z1 = Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && {...a, [k]: o[k]} || a, {});
console.log(z1); // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}
console.log(bKey in z1) // true
console.log(Symbol.for('d') in z1) // true
_x000D_
This is equal to this
const z2 = Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && Object.assign(a, {[k]: o[k]}) || a, {});
const z3 = Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && Object.defineProperty(a, k, {value: o[k]}) || a, {});
console.log(z2); // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}
console.log(z3); // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}
Wrapped in a filter()
function, an optional target
object could be passed
const filter = (o, allow, t = {}) => Reflect.ownKeys(o).reduce(
(a, k) => allow.includes(k) && {...a, [k]: o[k]} || a,
t
);
console.log(filter(o, allow)); // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}
console.log(filter(o, allow, {e: 'e'})); // {a: 1, e: "e", Symbol(b_k): "b", Symbol(d): "d"}
I think it was not possible earlier but I recently heard about PyMob, which seems interesting because the apps are written in Python and the final outputs are native source codes in various platforms (Obj-C for iOS, Java for Android etc). This is certainly quite unique. This webpage explains it in more detail.
I haven't given it a shot yet, but will take a look soon.
If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :
NavUtils.navigateUpFromSameTask(this);
Where this is your child activity.
Using BoxDecoration() is the best way to show border.
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xff000000),
width: 4,
)),
child: //Your child widget
),
You can also view full format here
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
Enter the password you use to open you Mac session and click on "Always allow" until all alerts are closed. The other buttons do not work...
I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia.
It looks like a floating-point calculation error. Check the numpy.seterr function to get more information about where it happens.
Edit: please see my other answer, as you probably don't need this now.
As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".
This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:
@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);
@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);
Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild
Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.
So, now you could set the onCompletion listener of the MediaPlayer instance like this:
OnCompletionListener ocl = new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
// Do stuff
}
};
Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);
The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.
Python comes with numerous ways of formatting strings:
New style .format()
, which supports a rich formatting mini-language:
>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!
Old style %
format specifier:
>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!
In Py 3.6 using the new f""
format strings:
>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!
Or using print()
s default sep
arator:
>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!
And least effectively, construct a new string by casting it to a str()
and concatenating:
>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!
Or join()
ing it:
>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!
Versioning your REST API is analogous to the versioning of any other API. Minor changes can be done in place, major changes might require a whole new API. The easiest for you is to start from scratch every time, which is when putting the version in the URL makes most sense. If you want to make life easier for the client you try to maintain backwards compatibility, which you can do with deprecation (permanent redirect), resources in several versions etc. This is more fiddly and requires more effort. But it's also what REST encourages in "Cool URIs don't change".
In the end it's just like any other API design. Weigh effort against client convenience. Consider adopting semantic versioning for your API, which makes it clear for your clients how backwards compatible your new version is.
You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:
public class Class1
{
public int Method1(string input)
{
//... do something
return 0;
}
public int Method2(string input)
{
//... do something different
return 1;
}
public bool RunTheMethod(Func<string, int> myMethodName)
{
//... do stuff
int i = myMethodName("My String");
//... do more stuff
return true;
}
public bool Test()
{
return RunTheMethod(Method1);
}
}
@CookieValue(value="abc",required=true) String m
when I changed required from true to false,it worked out.
Your regex pattern should have the g modifier:
var pattern = /[somepattern]+/g;
notice the g at the end. it tells the replacer to do a global replace.
Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:
var pattern = /[0-9a-zA-Z]+/g;
a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.
EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):
var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");
But you would need to change your replace function to this:
this.markup = this.markup.replace(pattern, value);
SELECT DateAdded, COUNT(1) AS NUMBERADDBYDAY
FROM Responses
WHERE DateAdded >= dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.
To disable this, use: struct.unpack("=BH", data)
. This will use standard alignment, which doesn't add padding:
>>> struct.calcsize('=BH')
3
The =
character will use native byte ordering. You can also use <
or >
instead of =
to force little-endian or big-endian byte ordering, respectively.
Live JsFiddle
It is possible with only HTML & CSS
table.scrollTable {_x000D_
border: 1px solid #963;_x000D_
width: 718px;_x000D_
}_x000D_
_x000D_
thead.fixedHeader {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
thead.fixedHeader tr {_x000D_
height: 30px;_x000D_
background: #c96;_x000D_
}_x000D_
_x000D_
thead.fixedHeader tr th {_x000D_
border-right: 1px solid black;_x000D_
}_x000D_
_x000D_
tbody.scrollContent {_x000D_
display: block;_x000D_
height: 262px;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
tbody.scrollContent td {_x000D_
background: #eee;_x000D_
border-right: 1px solid black;_x000D_
height: 25px;_x000D_
}_x000D_
_x000D_
tbody.scrollContent tr.alternateRow td {_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
thead.fixedHeader th {_x000D_
width: 233px;_x000D_
}_x000D_
_x000D_
thead.fixedHeader th:last-child {_x000D_
width: 251px;_x000D_
}_x000D_
_x000D_
tbody.scrollContent td {_x000D_
width: 233px;_x000D_
}
_x000D_
<table cellspacing="0" cellpadding="0" class="scrollTable">_x000D_
<thead class="fixedHeader">_x000D_
<tr class="alternateRow">_x000D_
<th>Header 1</th>_x000D_
<th>Header 2</th>_x000D_
<th>Header 3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody class="scrollContent">_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>And Repeat 1</td>_x000D_
<td>And Repeat 2</td>_x000D_
<td>And Repeat 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Cell Content 1</td>_x000D_
<td>Cell Content 2</td>_x000D_
<td>Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>More Cell Content 1</td>_x000D_
<td>More Cell Content 2</td>_x000D_
<td>More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="normalRow">_x000D_
<td>Even More Cell Content 1</td>_x000D_
<td>Even More Cell Content 2</td>_x000D_
<td>Even More Cell Content 3</td>_x000D_
</tr>_x000D_
<tr class="alternateRow">_x000D_
<td>End of Cell Content 1</td>_x000D_
<td>End of Cell Content 2</td>_x000D_
<td>End of Cell Content 3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
The function argument to setTimeout
is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i
, which is 3
.
Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:
for (var i = 1; i <= 2; i++) {
(function (x) {
setTimeout(function () { alert(x); }, 100);
})(i);
}
The TextField
widget is required to set keyboardType: TextInputType.number,
and inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly]
to accept numbers only as input.
TextField(
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
theme: ThemeData(primarySwatch: Colors.blue),
);
}
}
class HomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return HomePageState();
}
}
class HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Container(
padding: const EdgeInsets.all(40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("This Input accepts Numbers only"),
SizedBox(height: 20),
TextField(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.greenAccent, width: 5.0),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 5.0),
),
hintText: 'Mobile Number',
),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
SizedBox(height: 20),
Text("You can test be Typing"),
],
)),
);
}
}
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
It's very simple. Just try:
start chrome https://www.google.co.in/
it will open the Google page in the Chrome browser.
If you wish to open the page in Firefox, try:
start firefox https://www.google.co.in/
Have Fun!
@Mihai-Andrei Dinculescu's answer is correct, but for the benefit of searchers, there is also a subtle point that can cause this error.
Adding a '/' on the end of your URL will stop EnableCors from working in all instances (e.g. from the homepage).
I.e. This will not work
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net/", "*", "*");
config.EnableCors(cors);
but this will work:
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net", "*", "*");
config.EnableCors(cors);
The effect is the same if using the EnableCors Attribute.
Extension for @Kleist answer:
Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB)
and file(GLOB_RECURSE)
. With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.
However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.
Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB)
or file(GLOB_RECURSE)
for collect the sources.
You should put javascript tag in your html file.
because browser load your webpage according to html flow, you should put your javascript file<script src="javascript/game.js">
after the <canvas>
element tag. otherwise,if you put your javascript in the header of html.Browser load script first but it doesn't find the canvas. So your canvas doesn't work.
public static String[] split(String src, int len) {
String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
for (int i=0; i<result.length; i++)
result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
return result;
}
I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).
If you have configured ssh key to connect to your remote server, you could use the following command:
rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/
Where v
option is --verbose
, a
option is --archive
- archive mode, P
option same as --partial
- keep partially transferred files, e
option is --rsh=COMMAND
- specifying the remote shell to use.
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include> **/*.properties</include>
</includes>
</resource>
</resources>
...
</build>
You need to specify a type on person:
void addStudent(struct student person) {
...
}
Also, you can typedef your struct to avoid having to type struct every time you use it:
typedef struct student{
...
} student_t;
void addStudent(student_t person) {
...
}
Another possibility is to denote where you can find OpenCV_DIR
in the CMakeLists.txt file. For example, the following cmake scripts work for me:
cmake_minimum_required(VERSION 2.8)
project(performance_test)
set(OpenCV_STATIC ON)
set(OpenCV_CUDA OFF)
set(OpenCV_DIR "${CMAKE_SOURCE_DIR}/../install")
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
file(GLOB my_source_files ./src/*)
add_executable( performance_test ${my_source_files})
target_link_libraries(performance_test ${OpenCV_LIBS})
Just to remind that you should set OpenCV_STATIC
and OpenCV_CUDA
as well before you invoke OpenCVConfig.cmake
. In my case the built library is static library that does not use CUDA.
There's no way to specify a StringComparer
at the point where you try to get a value. If you think about it, "foo".GetHashCode()
and "FOO".GetHashCode()
are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.
You can, however, create a case-insensitive dictionary in the first place using:-
var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);
Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-
var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);
This new dictionary then uses the GetHashCode()
implementation on StringComparer.OrdinalIgnoreCase
so comparer.GetHashCode("foo")
and comparer.GetHashcode("FOO")
give you the same value.
Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>>
and just iterate over it:-
var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;
Or if you prefer, without the LINQ:-
var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
if (String.Equals(element.Key, myKey, comparer))
{
value = element.Value;
break;
}
}
This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).
Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:
onmouseover="this.bgColor='white'; this.style.color='black'"
onmouseout="this.bgColor='black'; this.style.color='white'"
Rebase explanation taken from the book Pragmatic Guide to Git - Travis Swicegood
Chapter III
16 . Rewriting History by Rebasing
Rebasing commits is the one concept in Git that has no counterpart inside the traditional version control world. Using git rebase, you can rewrite the history of a repository in a variety of ways. It is one of the most powerful commands in Git, which makes it one of the most dangerous.
rebase
takes a series of commits (normally a branch) and replays them on top of another commit (normally the last commit in another branch). The parent commit changes so all the commit IDs are recalculated. This can cause problems for other developers who have your code because the IDs don’t match up.There’s a simple rule of thumb with git rebase: use it as much as you want on local commits. Once you’ve shared changes with another developer, the headache is generally not worth the trouble.
I found a good method to detect application whether enter foreground or background. Here is my code. Hope this help you.
/**
* Custom Application which can detect application state of whether it enter
* background or enter foreground.
*
* @reference http://www.vardhan-justlikethat.blogspot.sg/2014/02/android-solution-to-detect-when-android.html
*/
public abstract class StatusApplication extends Application implements ActivityLifecycleCallbacks {
public static final int STATE_UNKNOWN = 0x00;
public static final int STATE_CREATED = 0x01;
public static final int STATE_STARTED = 0x02;
public static final int STATE_RESUMED = 0x03;
public static final int STATE_PAUSED = 0x04;
public static final int STATE_STOPPED = 0x05;
public static final int STATE_DESTROYED = 0x06;
private static final int FLAG_STATE_FOREGROUND = -1;
private static final int FLAG_STATE_BACKGROUND = -2;
private int mCurrentState = STATE_UNKNOWN;
private int mStateFlag = FLAG_STATE_BACKGROUND;
@Override
public void onCreate() {
super.onCreate();
mCurrentState = STATE_UNKNOWN;
registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// mCurrentState = STATE_CREATED;
}
@Override
public void onActivityStarted(Activity activity) {
if (mCurrentState == STATE_UNKNOWN || mCurrentState == STATE_STOPPED) {
if (mStateFlag == FLAG_STATE_BACKGROUND) {
applicationWillEnterForeground();
mStateFlag = FLAG_STATE_FOREGROUND;
}
}
mCurrentState = STATE_STARTED;
}
@Override
public void onActivityResumed(Activity activity) {
mCurrentState = STATE_RESUMED;
}
@Override
public void onActivityPaused(Activity activity) {
mCurrentState = STATE_PAUSED;
}
@Override
public void onActivityStopped(Activity activity) {
mCurrentState = STATE_STOPPED;
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
mCurrentState = STATE_DESTROYED;
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (mCurrentState == STATE_STOPPED && level >= TRIM_MEMORY_UI_HIDDEN) {
if (mStateFlag == FLAG_STATE_FOREGROUND) {
applicationDidEnterBackground();
mStateFlag = FLAG_STATE_BACKGROUND;
}
}else if (mCurrentState == STATE_DESTROYED && level >= TRIM_MEMORY_UI_HIDDEN) {
if (mStateFlag == FLAG_STATE_FOREGROUND) {
applicationDidDestroyed();
mStateFlag = FLAG_STATE_BACKGROUND;
}
}
}
/**
* The method be called when the application been destroyed. But when the
* device screen off,this method will not invoked.
*/
protected abstract void applicationDidDestroyed();
/**
* The method be called when the application enter background. But when the
* device screen off,this method will not invoked.
*/
protected abstract void applicationDidEnterBackground();
/**
* The method be called when the application enter foreground.
*/
protected abstract void applicationWillEnterForeground();
}
I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:
mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use
Function with_package
offered via the withr
package offers the possibility to:
attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.
library(withr)
with_package("ggplot2", {
ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context
exists("geom_point")
# [1] FALSE
geom_point
used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.
Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:
if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)
This should provide var3 with the following value:
blue_cheese
but instead yields:
_
because all 3 commands are cached and executed simultaneously upon exiting the code block.
I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.
if %ERRORLEVEL%==0 goto :error0
goto :endif
:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
:endif
You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml
available on the test classpath.
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {
@Autowired
protected SessionFactory sessionFactory;
@Test
public void testDBSourceIsCorrect() throws SQLException {
String databaseProductName = sessionFactory.getCurrentSession()
.connection()
.getMetaData()
.getDatabaseProductName();
assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
}
}
Note: This works with Spring 2.5.2 and Hibernate 3.6.5
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
If you see there is a method _numpy(), e.g for an EagerTensor simply call the above method and you will get an ndarray.
Functionally, you should be able to use
SELECT column_name
FROM table_name
WHERE TRIM(column_name) IS NULL
The problem there is that an index on COLUMN_NAME would not be used. You would need to have a function-based index on TRIM(column_name) if that is a selective condition.
For INNER
joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT *
to SELECT a.*, b.*, c.*
.
For (LEFT
, RIGHT
or FULL
) OUTER
joins, yes, the order matters - and (updated) things are much more complicated.
First, outer joins are not commutative, so a LEFT JOIN b
is not the same as b LEFT JOIN a
Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
is equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
but:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
AND c.bc_id = b.bc_id
is not equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
AND b.bc_id = c.bc_id
Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c
:
a LEFT JOIN b
ON b.ab_id = a.ab_id -- AB condition
LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
This is equivalent to a LEFT JOIN (b LEFT JOIN c)
:
a LEFT JOIN
b LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
ON b.ab_id = a.ab_id -- AB condition
only because we have "nice" ON
conditions. Both ON b.ab_id = a.ab_id
and c.bc_id = b.bc_id
are equality checks and do not involve NULL
comparisons.
You can even have conditions with other operators or more complex ones like: ON a.x <= b.x
or ON a.x = 7
or ON a.x LIKE b.x
or ON (a.x, a.y) = (b.x, b.y)
and the two queries would still be equivalent.
If however, any of these involved IS NULL
or a function that is related to nulls like COALESCE()
, for example if the condition was b.ab_id IS NULL
, then the two queries would not be equivalent.
use this
if (userProfile.AccountType == AccountType.Retailer)
{
...
}
If you want to get int from your AccountType enum and compare it (don't know why) do this:
if((int)userProfile.AccountType == 1)
{
...
}
Objet reference not set to an instance of an object
exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.
EDIT (thanks to @Rik and @KonradMorawski) :
Maybe you can do some check before:
if(userProfile!=null)
{
}
or
if(userProfile==null)
{
throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}
For those who are trying to use gulp for swagger local deployment, following code will help
var gulp = require("gulp");
var yaml = require("js-yaml");
var path = require("path");
var fs = require("fs");
//Converts yaml to json
gulp.task("swagger", done => {
var doc = yaml.safeLoad(fs.readFileSync(path.join(__dirname,"api/swagger/swagger.yaml")));
fs.writeFileSync(
path.join(__dirname,"../yourjsonfile.json"),
JSON.stringify(doc, null, " ")
);
done();
});
//Watches for changes
gulp.task('watch', function() {
gulp.watch('api/swagger/swagger.yaml', gulp.series('swagger'));
});
onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).
Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.
In your onCreate:
yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
yourSeekBar.setOnSeekBarChangeListener(new yourListener());
Your listener:
private class yourListener implements SeekBar.OnSeekBarChangeListener {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// Log the progress
Log.d("DEBUG", "Progress is: "+progress);
//set textView's text
yourTextView.setText(""+progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onStopTrackingTouch(SeekBar seekBar) {}
}
Please share some code and the Log results for furter help.
In case your data are stored as a Pandas DataFrame
, you can use remove_stopwords
from textero that use the NLTK stopwords list by default.
import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])
I found that (at least in Visual Studio 2010) you need to set the output verbosity to at least Detailed to be able to spot the problem.
It might be that my problem was a reference that was previously a GAC reference, but that was no longer the case after my machine's reinstall.
In this scenario, the outer <div>
has a width and height of 90%. The inner div>
has a width of 100% of its parent. Both scale when re-sizing the window.
HTML
<div>
<div>Hello there</div>
</div>
CSS
html, body {
width: 100%;
height: 100%;
}
body > div {
width: 90%;
height: 100%;
background: green;
}
body > div > div {
width: 100%;
background: red;
}
Demo
I have made some researches on this subject recently. The way to implement it has to be different if the field is a TEXT field, a non unique field.
I have made some tests with a TEXT field. Considering the fact that we have a table with 1M entries. 37 entries are equal to 'something':
SELECT * FROM test WHERE text LIKE '%something%' LIMIT 1
with
mysql_num_rows()
: 0.039061069488525s. (FASTER)SELECT count(*) as count FROM test WHERE text LIKE '%something%
:
16.028197050095s.SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%')
:
0.87045907974243s.SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%' LIMIT 1)
: 0.044898986816406s.But now, with a BIGINT PK field, only one entry is equal to '321321' :
SELECT * FROM test2 WHERE id ='321321' LIMIT 1
with
mysql_num_rows()
: 0.0089840888977051s.SELECT count(*) as count FROM test2 WHERE id ='321321'
: 0.00033879280090332s.SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321')
: 0.00023889541625977s.SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321' LIMIT 1)
: 0.00020313262939453s. (FASTER)Might just be for Visual Studio '15, if you right-click on source code, there's an option for insert comment
This puts summary
tags around your comment section, but it does give the indentation that you want.
>>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
>>> list(reduce(lambda x, y: x + y, a.items()))
['foo', 'bar', 'baz', 'quux', 'hello', 'world']
To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.
To turn a string into an array I usually use split()
> var s = ",'first string','more','even more'"
> s.split("','")
[",'first string", "more", "even more'"]
This is almost what you want. Now you just have to strip the first two and the last character:
> s.slice(2, s.length-1)
"first string','more','even more"
> s.slice(2, s.length-2).split("','");
["first string", "more", "even more"]
To extract a substring from a string I usually use slice()
but substr()
and substring()
also do the job.
Requirement: Function to find a string in an array.
This is a slight simplification of DevSolar's solution in that it uses the arguments passed rather than copying them.
myarray=('foobar' 'foxbat')
function isInArray() {
local item=$1
shift
for one in $@; do
if [ $one = $item ]; then
return 0 # found
fi
done
return 1 # not found
}
var='foobar'
if isInArray $var ${myarray[@]}; then
echo "$var found in array"
else
echo "$var not found in array"
fi
You can use the dynamic object ViewBag
to pass data from Controllers to Views.
Add the following to your controller:
ViewBag.MyList = myList;
Then you can acces it from your view:
@ViewBag.MyList
// e.g.
@foreach (var item in ViewBag.MyList) { ... }
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
Acording to docker documentation https://docs.docker.com/engine/reference/commandline/rename/
docker rename CONTAINER NEW_NAME
You can use pytz as well..
import datetime
import pytz
def utcnow():
return datetime.datetime.now(tz=pytz.utc)
utcnow()
datetime.datetime(2020, 8, 15, 14, 45, 19, 182703, tzinfo=<UTC>)
utcnow().isoformat()
'
2020-08-15T14:45:21.982600+00:00'
As the solutions above do not consider the possible overflow of doing max-min
when min
is negative, here another solution (similar to the one of kerouac)
public static int getRandom(int min, int max) {
if (min > max) {
throw new IllegalArgumentException("Min " + min + " greater than max " + max);
}
return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}
this works even if you call it with:
getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE)
But I cannot explain myself how it works? Because in the while statement, we use
getchar() != '\n'
, that means read any single character except'\n'
?? if so, in the input buffer still remains the'\n'
character??? Am I misunderstanding something??
The thing you may not realize is that the comparison happens after getchar()
removes the character from the input buffer. So when you reach the '\n'
, it is consumed and then you break out of the loop.
As everyone else said, but remember CultureInfo.InvariantCulture
!
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)
OR escape the '/'.
If you'd prefer to do it in SQL, enter this query into the query window:
CREATE SCHEMA Test
Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.
That's not quite true. E.g. for HTTP Windows supports URL based port sharing, allowing multiple processes to use the same IP address and Port.
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
you can use 'capture.output' like below. This allows you to use the data later:
log <- capture.output({
test <- CensReg.SMN(cc=cc,x=x,y=y, nu=NULL, type="Normal")
})
test$betas
As I faced this error, somewhere in your code your funcs or libraries that used run on different threads, so try to call all code on the same thread , it fixed my problem.
If you call methods on WebView from any thread other than your app's UI thread, it can cause unexpected results. For example, if your app uses multiple threads, you can use the runOnUiThread() method to ensure your code executes on the UI thread:
The solucion that work for me is the following
$filter('filter')(data, {'id':10})
This should work:
SELECT field,CONVERT(SUBSTRING_INDEX(field,'-',-1),UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;
Unfortunately - it could be many things - and lots of app servers and other java 'wrappers' are prone to play with properties and their 'own' take on keychains and what not. So it may be looking at something totally different.
Short of truss-ing - I'd try:
java -Djavax.net.debug=all -Djavax.net.ssl.trustStore=trustStore ...
to see if that helps. Instead of 'all' one can also set it to 'ssl', key manager and trust manager - which may help in your case. Setting it to 'help' will list something like below on most platforms.
Regardless - do make sure you fully understand the difference between the keystore (in which you have the private key and cert you prove your own identity with) and the trust store (which determines who you trust) - and the fact that your own identity also has a 'chain' of trust to the root - which is separate from any chain to a root you need to figure out 'who' you trust.
all turn on all debugging
ssl turn on ssl debugging
The following can be used with ssl:
record enable per-record tracing
handshake print each handshake message
keygen print key generation data
session print session activity
defaultctx print default SSL initialization
sslctx print SSLContext tracing
sessioncache print session cache tracing
keymanager print key manager tracing
trustmanager print trust manager tracing
pluggability print pluggability tracing
handshake debugging can be widened with:
data hex dump of each handshake message
verbose verbose handshake message printing
record debugging can be widened with:
plaintext hex dump of record plaintext
packet print raw SSL/TLS packets
Source: # See http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#Debug
Mac Users please execute the below command from terminal to disable the certificate warning.
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null
Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.
This also could be happening if you're copying code from another document (like a PDF) into your console and trying to run it.
I was trying to run some example code out of a Javascript book I'm reading and was surprised it didn't run in the console.
Apparently, copying from the PDF introduces some unexpected, illegal, and invisible characters into the code.
There are several ways to get a string length:
package main
import (
"bytes"
"fmt"
"strings"
"unicode/utf8"
)
func main() {
b := "?????"
len1 := len([]rune(b))
len2 := bytes.Count([]byte(b), nil) -1
len3 := strings.Count(b, "") - 1
len4 := utf8.RuneCountInString(b)
fmt.Println(len1)
fmt.Println(len2)
fmt.Println(len3)
fmt.Println(len4)
}
In addition to Fuji's response, we can make the handler reusable turning it into an attached property:
public static class HyperlinkExtensions
{
public static bool GetIsExternal(DependencyObject obj)
{
return (bool)obj.GetValue(IsExternalProperty);
}
public static void SetIsExternal(DependencyObject obj, bool value)
{
obj.SetValue(IsExternalProperty, value);
}
public static readonly DependencyProperty IsExternalProperty =
DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged));
private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var hyperlink = sender as Hyperlink;
if ((bool)args.NewValue)
hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
else
hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
}
private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
And use it like this:
<TextBlock>
<Hyperlink NavigateUri="https://stackoverflow.com"
custom:HyperlinkExtensions.IsExternal="true">
Click here
</Hyperlink>
</TextBlock>
You are most likely pushing a string 'NULL'
to the table, rather then an actual NULL
, but other things may be going on as well, an illustration:
mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)
mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)
mysql> show warnings;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
| NULL |
+------------+
2 rows in set (0.00 sec)
I had the EXACT same issue as the OP. My configuration and situation were identical. I finally narrowed it down to being an issue in WCFStorm after creating a service reference in a test project in Visual Studio and confirming that the service was working. In Storm you need to click on the "Config" settings option (NOT THE "Client Config"). After clicking on that, click on the "Security" tab on the dialog that pops up. Make sure "Authentication Type" is set to "None" (The default is "Windows Authentication"). Presto, it works! I always test out my methods in WCFStorm as I'm building them out, but have never tried using it to connect to one that has already been set up on SSL. Hope this helps someone!
I have faced the same issue. I almost wasted almost couple of weeks to resolved this issue. Finally I had on doubt on myself and tried to create another project by copy and paste some startup files like SplashScreen & LoginScreen.
But with the same code still i was getting SPAN_EXCLUSIVE_EXCLUSIVE.
Then i have removed the handler code from splash screen and tried again and Wow its working. I am not getting SPAN_EXCLUSIVE_EXCLUSIVE issue in logcat.
I wondering, why it is? till the time did not get any other solution but by removing handler from splash screen it is working.
Try and update here if it is resolved or not.
In my case, the only option was to remove the VM and download it again. No re-configuration of the host-only adapter did not help, I used different addressing of DHCP. Virtual Box I updated to version 4.3.4 and Genymotion to 2.0.2
Try the Join-Path cmdlet:
Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
Join-Path -Path $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)"
}
YES YOU CAN.
In your stored procedure, you fill the table @tbRetour
.
At the very end of your stored procedure, you write:
SELECT * FROM @tbRetour
To execute the stored procedure, you write:
USE [...]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'
GO
You can use HttpPost, there are methods to add Header to the Request.
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
HttpResponse response = httpclient.execute(httpPost);
This solves the problem:
df['newcolumn'] = df.A * df.B
You could also do:
def fab(row):
return row['A'] * row['B']
df['newcolumn'] = df.apply(fab, axis=1)
//form/descendant::input[@type='submit']
This question is pretty old but I'll add the solution I found the be the simplest at present.
library(reshape2)
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
newColNames <- c("type1", "type2")
newCols <- colsplit(before$type, "_and_", newColNames)
after <- cbind(before, newCols)
after$type <- NULL
after
You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html()
call will not serialize the event.
Check out this code... hope ur happy :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<style type="text/css">
*{margin:0;padding:0;}
select {font: normal 13px Arial, SansSerif, Verdana; color: black;}
.wrapper{width:198px; position: relative; height: 20px; overflow: hidden; border-top:1px solid #dddddd; border-left:1px solid #dddddd;}
.Select{color: black; background: #fff;position: absolute; width: 200px; top: -2px; left: -2px;}
optgroup{background-color:#0099CC;color:#ffffff;}
</style>
</head>
<body>
<div class="wrapper">
<select class="Select">
<optgroup label="WebDevelopment"></optgroup>
<option>ASP</option>
<option>PHP</option>
<option>ColdFusion</option>
<optgroup label="Web Design"></optgroup>
<option>Adobe Photoshop</option>
<option>DreamWeaver</option>
<option>CSS</option>
<option>Adobe Flash</option>
</select>
</div>
</body>
</html>
Sajay
First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *
Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.
I would just clean things up a bit:
SELECT t.PhoneNumber1, t.PhoneNumber2,
t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2
What i did:
*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.
If you are just trying to see if a string is empty or not (checking for length of 0), Swift offers a simple boolean test method on String
myString.isEmpty
The other side of this coin was people asking in ObjectiveC how to ask if a string was empty where the answer was to check for a length of 0:
I recently came across Python 3 interpreter at CompileOnline.
The thought process here is that you spend most of your time in development
. When in development, you create a feature
branch (off of development
), complete the feature, and then merge back into development
. This can then be added to the final production version by merging into production
.
See A Successful Git Branching Model for more detail on this approach.
You have to make one ajax call to get the required result, in this case you can use Google API to get the same
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false
Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level
Not sure why no one is using semicolons. This is how it works for me:
=CONCATENATE(LEFT(A1;1); B1)
Solutions with comma produce an error in Excel.
For android 2.2+ (api level8), you can use ScaleGestureDetector.
you need a member:
private ScaleGestureDetector mScaleDetector;
in your constructor (or onCreate()) you add:
mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
return false;
}
});
You override onTouchEvent:
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
return true;
}
If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().
If you are using jQuery you can easily check the type of any element.
function(elementID){
var type = $(elementId).attr('type');
if(type == "text") //inputBox
console.log("input text" + $(elementId).val().size());
}
similarly you can check the other types and take appropriate action.
Another option to stream images from a webcam to a browser is via mjpeg. This is just a series of jpeg images that most modern browsers support as part of the tag. Here's a sample server written in c#:
https://www.codeproject.com/articles/371955/motion-jpeg-streaming-server
This works well over a LAN, but not as well over the internet as mjpeg is not as effcient as other video codecs (h264, VP8 etc..)
Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.
return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();
Where CustomerGroupingKey takes the group keys:
private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}
public string Country { get; }
public string Gender { get; }
}
CREATE OR REPLACE PACKAGE BODY TEST AS
FUNCTION GET_UPS(
TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
STARTING_DATE_IN DATE,
ENDING_DATE_IN DATE
)RETURN MEASURE_TABLE IS
T MEASURE_TABLE;
BEGIN
**SELECT MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
PERIOD,VALUE ) BULK COLLECT INTO T
FROM ...**
;
RETURN T;
END GET_UPS;
END TEST;
Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem.
If you are in Eclipse, you can do this by going through
Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)
Here's a straightforward way to do this:
First, create a history table for each data table you want to track (example query below). This table will have an entry for each insert, update, and delete query performed on each row in the data table.
The structure of the history table will be the same as the data table it tracks except for three additional columns: a column to store the operation that occured (let's call it 'action'), the date and time of the operation, and a column to store a sequence number ('revision'), which increments per operation and is grouped by the primary key column of the data table.
To do this sequencing behavior a two column (composite) index is created on the primary key column and revision column. Note that you can only do sequencing in this fashion if the engine used by the history table is MyISAM (See 'MyISAM Notes' on this page)
The history table is fairly easy to create. In the ALTER TABLE query below (and in the trigger queries below that), replace 'primary_key_column' with the actual name of that column in your data table.
CREATE TABLE MyDB.data_history LIKE MyDB.data;
ALTER TABLE MyDB.data_history MODIFY COLUMN primary_key_column int(11) NOT NULL,
DROP PRIMARY KEY, ENGINE = MyISAM, ADD action VARCHAR(8) DEFAULT 'insert' FIRST,
ADD revision INT(6) NOT NULL AUTO_INCREMENT AFTER action,
ADD dt_datetime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER revision,
ADD PRIMARY KEY (primary_key_column, revision);
And then you create the triggers:
DROP TRIGGER IF EXISTS MyDB.data__ai;
DROP TRIGGER IF EXISTS MyDB.data__au;
DROP TRIGGER IF EXISTS MyDB.data__bd;
CREATE TRIGGER MyDB.data__ai AFTER INSERT ON MyDB.data FOR EACH ROW
INSERT INTO MyDB.data_history SELECT 'insert', NULL, NOW(), d.*
FROM MyDB.data AS d WHERE d.primary_key_column = NEW.primary_key_column;
CREATE TRIGGER MyDB.data__au AFTER UPDATE ON MyDB.data FOR EACH ROW
INSERT INTO MyDB.data_history SELECT 'update', NULL, NOW(), d.*
FROM MyDB.data AS d WHERE d.primary_key_column = NEW.primary_key_column;
CREATE TRIGGER MyDB.data__bd BEFORE DELETE ON MyDB.data FOR EACH ROW
INSERT INTO MyDB.data_history SELECT 'delete', NULL, NOW(), d.*
FROM MyDB.data AS d WHERE d.primary_key_column = OLD.primary_key_column;
And you're done. Now, all the inserts, updates and deletes in 'MyDb.data' will be recorded in 'MyDb.data_history', giving you a history table like this (minus the contrived 'data_columns' column)
ID revision action data columns..
1 1 'insert' .... initial entry for row where ID = 1
1 2 'update' .... changes made to row where ID = 1
2 1 'insert' .... initial entry, ID = 2
3 1 'insert' .... initial entry, ID = 3
1 3 'update' .... more changes made to row where ID = 1
3 2 'update' .... changes made to row where ID = 3
2 2 'delete' .... deletion of row where ID = 2
To display the changes for a given column or columns from update to update, you'll need to join the history table to itself on the primary key and sequence columns. You could create a view for this purpose, for example:
CREATE VIEW data_history_changes AS
SELECT t2.dt_datetime, t2.action, t1.primary_key_column as 'row id',
IF(t1.a_column = t2.a_column, t1.a_column, CONCAT(t1.a_column, " to ", t2.a_column)) as a_column
FROM MyDB.data_history as t1 INNER join MyDB.data_history as t2 on t1.primary_key_column = t2.primary_key_column
WHERE (t1.revision = 1 AND t2.revision = 1) OR t2.revision = t1.revision+1
ORDER BY t1.primary_key_column ASC, t2.revision ASC
Edit: Oh wow, people like my history table thing from 6 years ago :P
My implementation of it is still humming along, getting bigger and more unwieldy, I would assume. I wrote views and pretty nice UI to look at the history in this database, but I don't think it was ever used much. So it goes.
To address some comments in no particular order:
I did my own implementation in PHP that was a little more involved, and avoided some of the problems described in comments (having indexes transferred over, signifcantly. If you transfer over unique indexes to the history table, things will break. There are solutions for this in the comments). Following this post to the letter could be an adventure, depending on how established your database is.
If the relationship between the primary key and the revision column seems off it usually means the composite key is borked somehow. On a few rare occasions I had this happen and was at a loss to the cause.
I found this solution to be pretty performant, using triggers as it does. Also, MyISAM is fast at inserts, which is all the triggers do. You can improve this further with smart indexing (or lack of...). Inserting a single row into a MyISAM table with a primary key shouldn't be an operation you need to optimize, really, unless you have significant issues going on elsewhere. In the entire time I was running the MySQL database this history table implementation was on, it was never the cause of any of the (many) performance problems that came up.
if you're getting repeated inserts, check your software layer for INSERT IGNORE type queries. Hrmm, can't remember now, but I think there are issues with this scheme and transactions which ultimately fail after running multiple DML actions. Something to be aware of, at least.
It's important that the fields in the history table and the data table match up. Or, rather, that your data table doesn't have MORE columns than the history table. Otherwise, insert/update/del queries on the data table will fail, when the inserts to the history tables put columns in the query that don't exist (due to d.* in the trigger queries), and the trigger fails. t would be awesome if MySQL had something like schema-triggers, where you could alter the history table if columns were added to the data table. Does MySQL have that now? I do React these days :P
So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:
>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"
Ensure they are being called in the php.ini file
If the PDO is displayed in the list of currently installed php modules, you will want to check the php.ini file in the relevant folder to ensure they are being called. Somewhere in the php.ini file you should see the following:
extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so
If they are not present, simply add the lines above to the bottom of the php.ini file and save it.
Two more (similar) approaches with one generalized example:
1) first approach - removing field in save() method, e.g. (not tested ;) ):
def save(self, *args, **kwargs):
for fname in self.readonly_fields:
if fname in self.cleaned_data:
del self.cleaned_data[fname]
return super(<form-name>, self).save(*args,**kwargs)
2) second approach - reset field to initial value in clean method:
def clean_<fieldname>(self):
return self.initial[<fieldname>] # or getattr(self.instance, fieldname)
Based on second approach I generalized it like this:
from functools import partial
class <Form-name>(...):
def __init__(self, ...):
...
super(<Form-name>, self).__init__(*args, **kwargs)
...
for i, (fname, field) in enumerate(self.fields.iteritems()):
if fname in self.readonly_fields:
field.widget.attrs['readonly'] = "readonly"
field.required = False
# set clean method to reset value back
clean_method_name = "clean_%s" % fname
assert clean_method_name not in dir(self)
setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))
def _clean_for_readonly_field(self, fname):
""" will reset value to initial - nothing will be changed
needs to be added dynamically - partial, see init_fields
"""
return self.initial[fname] # or getattr(self.instance, fieldname)
$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0){
$import="INSERT into importing(text,number)values('".$data[0]."','".$data[1]."')";
mysql_query($import) or die(mysql_error());
}
$i=1;
}
Here's how I do file upload in react using axios
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:
public interface Predicate<ARGTYPE>
{
public boolean evaluate(ARGTYPE arg);
}
And then you might have an implementation such as:
public class Tautology<E> implements Predicate<E>
{
public boolean evaluate(E arg){
return true;
}
}
To get a better conceptual understanding, you might want to read about first-order logic.
Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.
Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true
to a function instead of defining a named Tautology subclass like the above.
REST stands for REpresentational State Transfer and goes a little something like this:
We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.
the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.
For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/
RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful
Many of the answers above are opaque. In my opinion the author of this question simply wants to know where session variables are stored by default. According to this:https://canvas.seattlecentral.edu/courses/937693/pages/10-advanced-php-sessions they are simply stored on the server by default. Hopefully, others will find this contribution meaningful.
We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.
So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.
String input = null;
// we have to store the string, which can only be read one time, because when the
// servlet awakens an AsyncContext, it reposts the request and returns here empty handed
if ((input = (String) request.getAttribute("com.xp.input")) == null) {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while((line = reader.readLine()) != null){
buffer.append(line);
}
// reqBytes = buffer.toString().getBytes();
input = buffer.toString();
request.setAttribute("com.xp.input", input);
}
if (input == null) {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
}
You can also use min-height and max-height. It was very useful for me
Depends on what your are doing.
If you have SPA (Single-Page Application) the you can use:
<input id="txtName" type="text" />
Otherwise using Html helpers is recommended, to get your controls bound with your model.
REST is a specific way of approaching the design of big systems (like the web).
It's a set of 'rules' (or 'constraints').
HTTP is a protocol that tries to obey those rules.
This error was showing up in the logs sometimes when I was using a buggy/crashy Cordova iOS version. It went away when I upgraded or downgraded cordova iOS.
The server I was connecting to was using TLSv1.2 SSL so I knew that was not the problem.
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) {
// do something
}
Starting with C# 7.3 (available with Visual Studio 2017 = v15.7), this code is now completely valid:
public static TEnum Parse<TEnum>(string value)
where TEnum : struct, Enum
{
...
}
You can have a real compiler enforced enum constraint by abusing constraint inheritance. The following code specifies both a class
and a struct
constraints at the same time:
public abstract class EnumClassUtils<TClass>
where TClass : class
{
public static TEnum Parse<TEnum>(string value)
where TEnum : struct, TClass
{
return (TEnum) Enum.Parse(typeof(TEnum), value);
}
}
public class EnumUtils : EnumClassUtils<Enum>
{
}
Usage:
EnumUtils.Parse<SomeEnum>("value");
Note: this is specifically stated in the C# 5.0 language specification:
If type parameter S depends on type parameter T then: [...] It is valid for S to have the value type constraint and T to have the reference type constraint. Effectively this limits T to the types System.Object, System.ValueType, System.Enum, and any interface type.
Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern
it will create 0 byte file and not write anything:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false"/>
<param name="maxFileSize" value="1GB"/>
<param name="maxBackupIndex" value="2"/>
<param name="file" value="/tmp/bd.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<logger name="com.example.mypackage" additivity="false">
<level value="debug"/>
<appender-ref ref="bdfile"/>
</logger>
<root>
<priority value="info"/>
<appender-ref ref="bdfile"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>
Remove android-support-v4.jar
file from the libs folder from your project.
You should really post:
Here is my code, which works:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
If your table is already working with tabular
, then easiest is to switch it to longtable
, remembering to add
\usepackage{longtable}
For example:
\begin{longtable}{ll}
2014--2015 & Something cool\footnote{first footnote} \\
2016-- & Something cooler\footnote{second footnote}
\end{longtable}
Or if you're using EnterpriseLibrary rather than standard ADO.NET...
Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
db.ExecuteNonQuery(cmd);
var result = (int)cmd.Parameters["RetVal"].Value;
}
You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.
Here's a sample of reading JSON using Newtonsoft.Json:
JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}
Why not making your form a dialogue box:
myForm.ShowDialog();
Just discovered that AlertDialogs
's boolean cancel(...);
I've been using everywhere actually does nothing. Great.
So...
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
private final ProgressDialog progressDialog;
public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});
}
@Override
protected void onPreExecute() {
progressDialog.show();
}
@Override
protected void onCancelled() {
running = false;
}
@Override
protected Void doInBackground(Void... params) {
while (running) {
// does the hard work
}
return null;
}
// ...
}
You can do by xlwings as well
import xlwings as xw
for book in xlwings.books:
print(book)
It looks like regex /\r\n|\r|\n/
handles CR, LF, and CRLF line endings, their mixed sequences, and keeps all the empty lines inbetween. Try that!
function splitLines(t) { return t.split(/\r\n|\r|\n/); }
// single newlines
console.log(splitLines("AAA\rBBB\nCCC\r\nDDD"));
// double newlines
console.log(splitLines("EEE\r\rFFF\n\nGGG\r\n\r\nHHH"));
// mixed sequences
console.log(splitLines("III\n\r\nJJJ\r\r\nKKK\r\n\nLLL\r\n\rMMM"));
_x000D_
You should get these arrays as a result:
[ "AAA", "BBB", "CCC", "DDD" ]
[ "EEE", "", "FFF", "", "GGG", "", "HHH" ]
[ "III", "", "JJJ", "", "KKK", "", "LLL", "", "MMM" ]
You can also teach that regex to recognize other legit Unicode line terminators by adding |\xHH
or |\uHHHH
parts, where H
's are hexadecimal digits of the additional terminator character codepoint (as seen in Wikipedia article as U+HHHH
).
Add 'justified' class to 'ul'.
<ul class="nav navbar-nav justified">
CSS:
.justified {
position:absolute;
left:50%;
}
Now, calculate its 'margin-left' in order to align it to center
.
// calculating margin-left to align it to center;
var width = $('.justified').width();
$('.justified').css('margin-left', '-' + (width / 2)+'px');
There are some good answers already with explanations of why the mixture of the non-static Context
method getText()
can't be used with your static final String
.
A good question to ask is: why do you want to do this? You are attempting to load a String
from your strings
resource, and populate its value into a public static
field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context
into your other classes and call context.getText(R.string.TTT)
from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity
:
NonActivity.doStuff(this);
This will allow you to access your String
resource without needing to use a public static
field.
Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.
Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.
public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {
List<Type> list = new List<Type>();
IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
while (enumerator.MoveNext()) {
try {
Type[] types = ((Assembly) enumerator.Current).GetTypes();
if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
IEnumerator enumerator2 = types.GetEnumerator();
while (enumerator2.MoveNext()) {
Type current = (Type) enumerator2.Current;
if (type.IsInterface) {
if (current.GetInterface(type.FullName) != null) {
list.Add(current);
}
} else if (current.IsSubclassOf(type)) {
list.Add(current);
}
}
}
} catch {
}
}
return list;
}
It's not pretty, I'll admit.
You should be able to set these via the attr()
or prop()
functions in jQuery as shown below:
jQuery (< 1.7):
// This will disable just the div
$("#dcacl").attr('disabled','disabled');
or
// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");
jQuery (>= 1.7):
// This will disable just the div
$("#dcacl").prop('disabled',true);
or
// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);
or
// disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);
Javascript:
// This will disable just the div
document.getElementById("dcalc").disabled = true;
or
// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
nodes[i].disabled = true;
}
Several things here.
First off, you're defining your CSS in 3 places!
In line, in the head and externally. I suggest you only choose one. I'm going to suggest externally.
I suggest you update your code in your ASP form from
<td style="background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;"
class="style6">
to this:
<td class="style6">
And then update your css too
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
This removes the inline.
Now, to move it from the head of the webForm.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AR Toolbox</title>
<link rel="Stylesheet" href="css/master.css" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
<tr>
<td class="style6">
<asp:Menu ID="Menu1" runat="server">
<Items>
<asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
<asp:MenuItem Text="About" Value="About"></asp:MenuItem>
<asp:MenuItem Text="Compliance" Value="Compliance">
<asp:MenuItem Text="Item 1" Value="Item 1"></asp:MenuItem>
<asp:MenuItem Text="Item 2" Value="Item 2"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Tools" Value="Tools"></asp:MenuItem>
<asp:MenuItem Text="Contact" Value="Contact"></asp:MenuItem>
</Items>
</asp:Menu>
</td>
</tr>
<tr>
<td class="style6">
<img alt="South University'" class="style7"
src="file:///C:/Users/jnewnam/Documents/Visual%20Studio%202010/WebSites/WebSite1/img/suo_n_seal_hor_pantone.png" /></td>
</tr>
<tr>
<td class="style2">
<table class="style3">
<tr>
<td>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="color: #FFFFFF; background-color: #A3A3A3">
This is the footer.</td>
</tr>
</table>
</form>
</body>
</html>
Now, in a new file called master.css (in your css folder) add
ul {
list-style-type:none;
margin:0;
padding:0;
}
li {
display:inline;
padding:20px;
}
.style1
{
width: 100%;
}
.style2
{
height: 459px;
}
.style3
{
width: 100%;
height: 100%;
}
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
.style7
{
width: 345px;
height: 73px;
}
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
Read the bytes from String
using ByteArrayInputStream
and wrap it with BufferedReader
which is Char Stream instead of Byte Stream which converts the byte data to String.
package com.cs.sajal;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class TestCls {
public static void main(String[] args) {
String s=new String("Sajal is a good boy");
try
{
ByteArrayInputStream bis;
bis=new ByteArrayInputStream(s.getBytes("UTF-8"));
BufferedReader br=new BufferedReader(new InputStreamReader(bis));
System.out.println(br.readLine());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output is:
Sajal is a good boy
I prefer to upgrade all homebrew formulae and homebrew cask formulae.
I added a Bourne shell function to my environment for this one (I load a .bashrc)
function updatebrew() {
set -x;
brew update;
brew cleanup;
brew cask upgrade --greedy
)
}
set -x
for transparency: So that the terminal outputs whatever Homebrew is doing in the background.brew update
to update homebrew formulasbrew cleanup
to remove any change left over after installationsbrew cask upgrade --greedy
will install all casks; both those with versioning information and those withoutWhy would you need any other way? Comparing an Object
reference with null
is the least-verbose way to check if it's null.
public static String getManufacturerSerialNumber() {
String serial = null;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class, String.class);
serial = (String) get.invoke(c, "ril.serialnumber", "unknown");
} catch (Exception ignored) {}
return serial;
}
Works on API 29 and 30, tested on Samsung galaxy s7 s9 Xcover
If you've upgraded from an older MVC version make sure you don't have
<add key="owin:AutomaticAppStartup" value="false" />
in your web.config
. It will suppress calling the startup logic.
Instead change it to true
<add key="owin:AutomaticAppStartup" value="true" />
I realize you already mentioned this but sometimes people (like me) don't read the whole question and just jump to the answers...
Somewhere along the line - when I upgraded to MVC 5 this got added and I never saw it until today.
Also there is mongoexport for that, but I'm not sure since which version it is available.
Example:
mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json
I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.
You can do it like what I did with my website:
background-repeat: no-repeat;
background-size: cover;
As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.
It's better to run the subquery once, in the FROM clause, to get the max date per control number.
SELECT n.*
FROM tblpm n
INNER JOIN (
SELECT control_number, MAX(date_updated) AS date_updated
FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);
I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:
//Bad code.
var btn = document.createElement('button');
btn.onClick = function() { console.log("hey"); }
to this:
//Working Code. I don't like it, but it works.
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);
document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){ console.log("hey"); }
I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.
What eventually worked for me, after lot's of confusing manuals and confusing tutorials, since Docker is obviously at time of my writing at peek of inflated expectations, is:
docker save image_name > image_name.tar
cat image_name.tar | docker load
Export and import, as proposed in another answers does not export ports and variables, which might be required for your container to run. And you might end up with stuff like "No command specified" etc... When you try to load it on another machine.
So, difference between save and export is that save command saves whole image with history and metadata, while export command exports only files structure (without history or metadata).
Needless to say is that, if you already have those ports taken on the docker hyper-visor you are doing import, by some other docker container, you will end-up in conflict, and you will have to reconfigure exposed ports.
Note: In order to move data with docker, you might be having persistent storage somewhere, which should also be moved alongside with containers.
There are two parts in building barcode scanning feature, one capturing barcode image using camera and second extracting barcode value from the image.
Barcode image can be captured from your app using camera app and barcode value can be extracted using Firebase Machine Learning Kit barcode scanning API.
Here is an example app https://www.zoftino.com/android-barcode-scanning-example
The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.
My understanding is that this is actually very simple:
So, to work through some of your examples:
function f(a,b,c) {
// Argument a is re-assigned to a new value.
// The object or primitive referenced by the original a is unchanged.
a = 3;
// Calling b.push changes its properties - it adds
// a new property b[b.length] with the value "foo".
// So the object referenced by b has been changed.
b.push("foo");
// The "first" property of argument c has been changed.
// So the object referenced by c has been changed (unless c is a primitive)
c.first = false;
}
var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false
Example 2:
var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4"; // a is now ["1", "4", {foo:"bar"}]; b still has the value
// it had at the time of assignment
a[2] = "5"; // a is now ["1", "4", "5"]; c still has the value
// it had at the time of assignment, i.e. a reference to
// the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"
Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
As of October 2015, WP 4.3.1 I have found only two plugins actually affecting image locations as in “folders & subfolders”:
Custom Upload Dir, but as the name says, just on upload. You can work from your %post_slug% or %categories%, upload your images in the context of these post/pages, and this tool will form subfolders from it. Which is great, SEO-wise.
Or you just even ignore all that and mandate under “Build a path template” i.e. travels/france/paris-at-night
to upload to that subdir of your WP-Uploads folder. (Of course you'd have to keep changing for the uploads to follow. Limiting my overall faith, that this is a stable long-term tool, despite 10.000+ active installs).
Media File Manager allows to move already uploaded images and changes the paths in posts and pages using them accordingly. Its interface reminds of “Norton Commander 1.0” but it does the job. (Except for folder renames and deletes. So if you want to rename, better move images to a newly namend folder, then manually deleting the old.)
All of the following do NOT do the job:
WP Media Folder is NOT changing actual direcory location, thus not actually changing paths to your images thus also not affecting image URLs. Despite its name, Folder is just their visualisation of yet-another-taxonomy. I invested $19 to learn that.
Enhance Media Library is big, free and very popular (wordpress counts 40.000 installs) but is also not changing physical location and (thus) URLs. ? Thus the accepted answer is in my opinion wrong.
Media File Manager advanced appears gone and is deemed dangerous!
that is the right behavior.
if you set @item1
to a value the below expression will be true
IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
Anyway in SQL Server there is not a such function but you can create your own:
CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
RETURN 0
ELSE
RETURN 1
END
The main
method is the entry point of a Java application.
Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java
application launcher), it will look for the main
method with the signature of public static void main(String[])
.
From Sun's java
command page:
The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
The method must be declared public and static, it must not return any value, and it must accept a
String
array as a parameter. The method declaration must look like the following:public static void main(String args[])
For additional resources on how an Java application is executed, please refer to the following sources:
The run
method is the entry point for a new Thread
or an class implementing the Runnable
interface. It is not called by the Java Virutal Machine when it is started up by the java
command.
As a Thread
or Runnable
itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start()
method. This can be accomplished by instantiating a Thread
and calling its start
method in the main
method of the application:
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Hello World!");
}
public static void main(String[] args)
{
new Thread(new MyRunnable()).start();
}
}
For more information and an example of how to start a subclass of Thread
or a class implementing Runnable
, see Defining and Starting a Thread from the Java Tutorials.
The init
method is the first method called in an Applet or JApplet.
When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init
method. Any initializations that are required to use the applet should be executed here. After the init
method is complete, the start
method is called.
For more information about when the init
method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.
See also: How to Make Applets from the Java Tutorial.
This works too. The below statement rounds to two decimal places.
SELECT ROUND(92.258,2) from dual;
Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.
I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.
Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.
This is to remove double quotes in a string.
str1 = str.replace(/"/g, "");
alert(str1);
Move doSomething
definition outside of its class declaration and after B
and also make add
accessible to A
by public
-ing it or friend
-ing it.
class B;
class A
{
void doSomething(B * b);
};
class B
{
public:
void add() {}
};
void A::doSomething(B * b)
{
b->add();
}
Here is what I'm using:
if (mySQLConnection.State != ConnectionState.Open)
{
mySQLConnection.Close();
mySQLConnection.Open();
}
The reason I'm not simply using:
if (mySQLConnection.State == ConnectionState.Closed)
{
mySQLConnection.Open();
}
Is because the ConnectionState can also be:
Broken, Connnecting, Executing, Fetching
In addition to
Open, Closed
Additionally Microsoft states that Closing, and then Re-opening the connection "will refresh the value of State." See here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.state(v=vs.110).aspx
It may be because you are not stopping your tomcat service properly. To do that, Open your task manager there you can see a javaw.exe
service. First stop that service. Now restart your tomcat it works fine.
Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml
to read your $_POST. You can use file_get_contents('php://input')
to get the raw post data as plain XML.
I encounter into a more generic problem: getting different (and not necessarily known) datetime formats and insert them into datetime column. I've solved it using this statement, which was finally became a scalar function (relevant for ODBC canonical, american, ANSI and british\franch date style - can be expanded):
insert into <tableName>(<dateTime column>) values(coalesce
(TRY_CONVERT(datetime, <DateString, 121), TRY_CONVERT(datetime, <DateString>,
101), TRY_CONVERT(datetime, <DateString>, 102), TRY_CONVERT(datetime,
<DateString>, 103)))
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
You're looking for
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
((TextBox)x).Text = String.Empty;
}
}
Very simple :)
<a href="#" id="blob" class="btn large primary" rel="popover">hover for popover</a>
var img = '<img src="https://si0.twimg.com/a/1339639284/images/three_circles/twitter-bird-white-on-blue.png" />';
$("#blob").popover({ title: 'Look! A bird!', content: img, html:true });
{ }
-->
defines scope, so if(a==1) { int b = 10; }
says, you are defining int b, for {}- this scope. For
if(a==1)
int b =10;
there is no scope. And you will not be able to use b
anywhere.
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
Import numpy as np
FOR INDEX
S=[11,2,44,55,66,0,10,3,33]
r=np.argsort(S)
[output]=array([5, 1, 7, 6, 0, 8, 2, 3, 4])
argsort Returns the indices of S in sorted order
FOR VALUE
np.sort(S)
[output]=array([ 0, 2, 3, 10, 11, 33, 44, 55, 66])
Just make a new list to populate, if the item for your list is not yet in the new list input it, else just move on to the next item in your original list.
for i in mylist:
if i not in newlist:
newlist.append(i)
I think this is the correct syntax, but my python is a bit shaky, I hope you at least get the idea.
public class Factorial2 {
public static long factorial(long x) {
if (x < 0)
throw new IllegalArgumentException("x must be >= 0");
if (x <= 1)
return 1; // Stop recursing here
else
return x * factorial(x-1); // Recurse by calling ourselves
}
}
Here is what I did and it worked, created a session in PHP and used xmlhhtprequest to check if session is set whenever an HTML page loads and it worked for Cordova.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<rotate
android:fromDegrees="45"
android:pivotX="135%"
android:pivotY="1%"
android:toDegrees="45">
<shape android:shape="rectangle">
<stroke
android:width="-60dp"
android:color="@android:color/transparent" />
<solid android:color="@color/orange" />
</shape>
</rotate>
</item>
</layer-list>
Swift 2.0
This is how to check if the file exists using Swift
func isFileExistsInDirectory() -> Bool {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")
return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}
I suggest to use utf8mb4_unicode_ci
, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.