VB.net, Desktop application. If you need lapsed time in milliseconds:
Dim starts As Integer = My.Computer.Clock.TickCount
Dim ends As Integer = My.Computer.Clock.TickCount
Dim lapsed As Integer = ends - starts
You can also use PreviewKeyDown in WPF:
<TextBox PreviewKeyDown="EnterClicked" />
or in C#:
myTextBox.PreviewKeyDown += EnterClicked;
And then in the attached class:
void EnterClicked(object sender, KeyEventArgs e) {
if(e.Key == Key.Return) {
DoSomething();
e.Handled = true;
}
}
Instead of override you can add another class to the element and then you have an extra abilities. for example:
HTML
<div class="style1 style2"></div>
CSS
//only style for the first stylesheet
.style1 {
width: 100%;
}
//only style for second stylesheet
.style2 {
width: 50%;
}
//override all
.style1.style2 {
width: 70%;
}
You can press q to exit.
git hist
is using a pager tool so you can scroll up and down the results before returning to the console.
Edit: Advise: This answer is old and a better solution can be found in this same page. This answer referred to MySQL Workbench 6.3 and is outdated. If you are using a new version (8.0 as today) look for @VSingh comment in this very page.
Original answer:
Just a copy of Gaston's answer, but with Monokai theme colors.
<!--
dark-gray: #282828;
brown-gray: #49483E;
gray: #888888;
light-gray: #CCCCCC;
ghost-white: #F8F8F0;
light-ghost-white: #F8F8F2;
yellow: #E6DB74;
blue: #66D9EF;
pink: #F92672;
purple: #AE81FF;
brown: #75715E;
orange: #FD971F;
light-orange: #FFD569;
green: #A6E22E;
sea-green: #529B2F;
-->
<style id="32" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- STYLE_DEFAULT !BACKGROUND! -->
<style id="33" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- STYLE_LINENUMBER -->
<style id= "0" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DEFAULT -->
<style id= "1" fore-color="#999999" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id= "2" fore-color="#999999" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id= "3" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id= "4" fore-color="#66D9EF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id= "5" fore-color="#66D9EF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id= "6" fore-color="#AE81FF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id= "7" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id= "8" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id= "9" fore-color="#9B859D" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="10" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="11" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="12" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="13" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="14" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="15" fore-color="#9B859D" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="16" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="17" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="18" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="19" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="20" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="21" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="22" fore-color="#909090" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color="#999999" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id="66" fore-color="#999999" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id="67" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id="68" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id="69" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id="70" fore-color="#AE81FF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id="71" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id="72" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id="73" fore-color="#9B859D" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="74" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="75" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="76" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="77" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="78" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="79" fore-color="#9B859D" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="80" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="81" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="82" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="83" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="84" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="85" fore-color="#66D9EF" back-color="#888888" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="86" fore-color="#AAAAAA" back-color="#888888" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
Based on a feature mentioned in this answer to another question I have found a very generally applicable solution for placing labels on a bar chart.
Other solutions unfortunately do not work in many cases, because the spacing between label and bar is either given in absolute units of the bars or is scaled by the height of the bar. The former only works for a narrow range of values and the latter gives inconsistent spacing within one plot. Neither works well with logarithmic axes.
The solution I propose works independent of scale (i.e. for small and large numbers) and even correctly places labels for negative values and with logarithmic scales because it uses the visual unit points
for offsets.
I have added a negative number to showcase the correct placement of labels in such a case.
The value of the height of each bar is used as a label for it. Other labels can easily be used with Simon's for rect, label in zip(rects, labels)
snippet.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
def add_value_labels(ax, spacing=5):
"""Add labels to the end of each bar in a bar chart.
Arguments:
ax (matplotlib.axes.Axes): The matplotlib object containing the axes
of the plot to annotate.
spacing (int): The distance between the labels and the bars.
"""
# For each bar: Place a label
for rect in ax.patches:
# Get X and Y placement of label from rect.
y_value = rect.get_height()
x_value = rect.get_x() + rect.get_width() / 2
# Number of points between bar and label. Change to your liking.
space = spacing
# Vertical alignment for positive values
va = 'bottom'
# If value of bar is negative: Place label below bar
if y_value < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
va = 'top'
# Use Y value as label and format number with one decimal place
label = "{:.1f}".format(y_value)
# Create annotation
ax.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(0, space), # Vertically shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
ha='center', # Horizontally center label
va=va) # Vertically align label differently for
# positive and negative values.
# Call the function above. All the magic happens there.
add_value_labels(ax)
plt.savefig("image.png")
Edit: I have extracted the relevant functionality in a function, as suggested by barnhillec.
This produces the following output:
And with logarithmic scale (and some adjustment to the input data to showcase logarithmic scaling), this is the result:
Bro, I had the same problem. Thing is I built a query builder, quite an complex one that build his predicates dynamically pending on what parameters had been set and cached the queries. Anyways, before I built my query builder, I had a non object oriented procedural code build the same thing (except of course he didn't cache queries and use parameters) that worked flawless. Now when my builder tried to do the very same thing, my PostgreSQL threw this fucked up error that you received too. I examined my generated SQL code and found no errors. Strange indeed.
My search soon proved that it was one particular predicate in the WHERE clause that caused this error. Yet this predicate was built by code that looked like, well almost, exactly as how the procedural code looked like before this exception started to appear out of nowhere.
But I saw one thing I had done differently in my builder as opposed to what the procedural code did previously. It was the order of the predicates he put in the WHERE clause! So I started to move this predicate around and soon discovered that indeed the order of predicates had much to say. If I had this predicate all alone, my query worked (but returned an erroneous result-match of course), if I put him with just one or the other predicate it worked sometimes, didn't work other times. Moreover, mimicking the previous order of the procedural code didn't work either. What finally worked was to put this demonic predicate at the start of my WHERE clause, as the first predicate added! So again if I haven't made myself clear, the order my predicates where added to the WHERE method/clause was creating this exception.
VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.
You can set an individual font size for the legend by adjusting the prop
keyword.
plot.legend(loc=2, prop={'size': 6})
This takes a dictionary of keywords corresponding to matplotlib.font_manager.FontProperties
properties. See the documentation for legend:
Keyword arguments:
prop: [ None | FontProperties | dict ] A matplotlib.font_manager.FontProperties instance. If prop is a dictionary, a new instance will be created with prop. If None, use rc settings.
It is also possible, as of version 1.2.1, to use the keyword fontsize
.
This is what the code would look like in a batch file(tested, works):
powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"
Based on the information from:
http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/
Try from tensorflow.python import keras
with this, you can easily change keras dependent code to tensorflow in one line change.
You can also try from tensorflow.contrib import keras
. This works on tensorflow 1.3
Edited: for tensorflow 1.10 and above you can use import tensorflow.keras as keras
to get keras in tensorflow.
I heard of RTM (The RT FAQ Manager). Never used it, however.
The easiest way I found (just I use eval() to convert string gotten from input to tuple to read again for form instance or other place)
This trick works very well
#model.py
class ClassName(models.Model):
field_name = models.CharField(max_length=100)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.field_name:
self.field_name= eval(self.field_name)
#form.py
CHOICES = [('pi', 'PI'), ('ci', 'CI')]
class ClassNameForm(forms.ModelForm):
field_name = forms.MultipleChoiceField(choices=CHOICES)
class Meta:
model = ClassName
fields = ['field_name',]
For Swift 3 & Swift 4 :
Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3
let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
//Do whatever you want here
})
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
Deprecated :
This is the swift version inspired by the checked response :
Display AlertView :
let alert = UIAlertView(title: "No network connection",
message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
alert.delegate = self
alert.show()
Add the delegate to your view controller :
class AgendaViewController: UIViewController, UIAlertViewDelegate
When user click on button, this code will be executed :
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
}
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
I solved it by doing like that:
var return_first = (function () {
var tmp = $.ajax({
'type': "POST",
'dataType': 'html',
'url': "ajax.php?first",
'data': { 'request': "", 'target': arrange_url, 'method':
method_target },
'success': function (data) {
tmp = data;
}
}).done(function(data){
return data;
});
return tmp;
});
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?
remove one y form the format provide to:
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
It should be:
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
Swift 3.0
With Swift 3, the name of NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Swift 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
I had luck with this:
<Route
path="/example"
component={() => {
global.window && (global.window.location.href = 'https://example.com');
return null;
}}
/>
I also had this problem, and I solved it by editing the settings.xml
file in my .m2
folder.
My settings.xml
is like this now:
<settings>
<proxies>
<proxy>
<id>genproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>proxyHost</host>
<port>3128</port>
<username>username</username>
<password>password</password>
</proxy>
</proxies>
</settings>
I encountered this error even though the Project Facets were set appropriately. The problem was that the "Runtime Environment" property was not set on the server:
It simply needed to be set to the appropriate Runtime:
Yes, you can definitely do this. Just use something like
.parent:hover .child {
/* ... */
}
According to this page it's supported by all major browsers.
I think we can you use verbatim tag, as in this tag we use any of the HTML tags
If you use JDK version from 9+, you should select
Run > Edit Configurations... > Select JUnit template.
Then, select @argfile (Java 9+) as in the image below. Please try it. Good luck friends.
I use MSYS2 from http://www.msys2.org/
It provides many utilities like patch
, which
, git
, tree
, and many more.
After installing MSYS2 simply run the package manager to install patch
:
pacman -S patch
vars(obj) returns the attributes of an object.
There isn't a last()
or first()
method in a Collection interface. For getting the last method, you can either do get(size() - 1)
on a List or reverse the List and do get(0)
. I don't see a need to have last()
method in any Collection API unless you are dealing with Stacks
or Queues
import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
public static void main(String [] args){
int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
Map map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < arrayToCheckFrom.length; i++){
int sum = 0;
for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
sum += 1;
}
map.put(arrayToCheckFrom[i], sum);
}
System.out.println(getMaxValue(map));
}
public static Integer getMaxValue( Map<Integer,Integer> map){
Map.Entry<Integer,Integer> maxEntry = null;
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
maxEntry = pair;
}
}
return maxEntry.getKey();
}
}
Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.
Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.
A better approach from the correct solution here in order to not alter target:
function extend(){
let sources = [].slice.call(arguments, 0), result = {};
sources.forEach(function (source) {
for (let prop in source) {
result[prop] = source[prop];
}
});
return result;
}
<item name="editTextColor">@color/white</item>
<item name="android:textColor">@color/white</item>
<item name="android:textColorHint">@color/gray</item>
<item name="android:textColorPrimary">@color/gray</item>
<item name="colorControlNormal">@color/gray</item>
<item name="colorControlActivated">@color/white</item>
<item name="colorControlHighlight">#30FFFFFF</item>
See here: Cross Browser favicon
Thats the way to go:
<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
$matches = preg_grep('/hello/i', $haystack);
print_r($matches);
Output
Array
(
[1] => say hello
[2] => hello stackoverflow
[3] => hello world
)
I know this is an old post, in SQL Server:
select isnull(town,'TOTAL') Town, count(*) cnt
from user
group by town WITH ROLLUP
Town cnt
Copenhagen 58
NewYork 58
Athens 58
TOTAL 174
First of All you should download the Android SDK.
Download here:
http://developer.android.com/sdk/index.html
Then, as stated in the SDK README:
The Android SDK archive now only contains the tools. It no longer comes populated with a specific Android platform or Google add-on. Instead you use the SDK Manager to install or update SDK components such as platforms, tools, add-ons, and documentation.
You need to implement the equals() method in your MyClass
.
The reason that ==
didn't work is this is checking that they refer to the same instance. Since you did new
for each, each one is a different instance.
The reason that equals()
didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==
.
Note that you should also implement hashcode()
if you're going to implement equals()
because a lot of java.util Collections expect that.
You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
The best solution is on the "comments and discussions", see the "No need for static Create methods".
From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.
#ifndef FACTORY_H
#define FACTORY_H
#include <QMap>
#include <QString>
template <typename T>
class Factory
{
public:
template <typename TDerived>
void registerType(QString name)
{
static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
_createFuncs[name] = &createFunc<TDerived>;
}
T* create(QString name) {
typename QMap<QString,PCreateFunc>::const_iterator it = _createFuncs.find(name);
if (it != _createFuncs.end()) {
return it.value()();
}
return nullptr;
}
private:
template <typename TDerived>
static T* createFunc()
{
return new TDerived();
}
typedef T* (*PCreateFunc)();
QMap<QString,PCreateFunc> _createFuncs;
};
#endif // FACTORY_H
Sample usage:
Factory<BaseClass> f;
f.registerType<Descendant1>("Descendant1");
f.registerType<Descendant2>("Descendant2");
Descendant1* d1 = static_cast<Descendant1*>(f.create("Descendant1"));
Descendant2* d2 = static_cast<Descendant2*>(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");
Using this JavaScript
code you can check image is successfully loaded or not.
document.onready = function(e) {
var imageobj = new Image();
imageobj.src = document.getElementById('img-id').src;
if(!imageobj.complete){
alert(imageobj.src+" - Not Found");
}
}
Try out this
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id
(int), image
(blob) and image_name
(varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string()
, otherwise it will result in a syntax error.
For anyone who has SQL 2012 or later, I was able to accomplish this with stored procedures that aren't dynamic and have the same columns output each time.
The general idea is I build the dynamic query to create, insert into, select from, and drop the temp table, and execute this after it's all generated. I dynamically generate the temp table by first retrieving column names and types from the stored procedure.
Note: there are much better, more universal solutions that will work with fewer lines of code if you're willing/able to update the SP or change configuration and use OPENROWSET
. Use the below if you have no other way.
DECLARE @spName VARCHAR(MAX) = 'MyStoredProc'
DECLARE @tempTableName VARCHAR(MAX) = '#tempTable'
-- might need to update this if your param value is a string and you need to escape quotes
DECLARE @insertCommand VARCHAR(MAX) = 'INSERT INTO ' + @tempTableName + ' EXEC MyStoredProc @param=value'
DECLARE @createTableCommand VARCHAR(MAX)
-- update this to select the columns you want
DECLARE @selectCommand VARCHAR(MAX) = 'SELECT col1, col2 FROM ' + @tempTableName
DECLARE @dropCommand VARCHAR(MAX) = 'DROP TABLE ' + @tempTableName
-- Generate command to create temp table
SELECT @createTableCommand = 'CREATE TABLE ' + @tempTableName + ' (' +
STUFF
(
(
SELECT ', ' + CONCAT('[', name, ']', ' ', system_type_name)
FROM sys.dm_exec_describe_first_result_set_for_object
(
OBJECT_ID(@spName),
NULL
)
FOR XML PATH('')
)
,1
,1
,''
) + ')'
EXEC( @createTableCommand + ' '+ @insertCommand + ' ' + @selectCommand + ' ' + @dropCommand)
It has been mentioned in earlier answers that using dependency walker is the way to go, in my case (my application keeps failing with the error code), dependency walker showed a few dll that are NOT relevant!
Finally figured out that I can run profiling by going to "profile" menu and it will run the application and stop at the exact dll that's cause the problem! I found out a 32bit dll was picked because of path and fixed it.
Creating an Empty Dataframe with known Column Name:
Names = ['Col1','ActivityID','TransactionID']
df = pd.DataFrame(columns = Names)
Creating a dataframe from csv:
df = pd.DataFrame('...../file_name.csv')
Creating a dynamic filter to subset a dtaframe
:
i = 12
df[df['ActivitiID'] <= i]
Creating a dynamic filter to subset required columns of dtaframe
df[df['ActivityID'] == i][['TransactionID','ActivityID']]
One example: you want to center the main content area of a page, but in order to contain the floats inside it, it needs to be floated. There is no "float: center" in CSS.
That is not the only way to "contain the floats" inside a centred element. So, not a good argument at all!
In a way, it's a false premise, the "divs vs tables" thing.
Quick-and-dirty division of a page into three columns? Tables are easier, to be honest. But no professional uses them any more for layout, because they lock the positioning of page elements into the page.
The real argument is "positioning done by CSS (hopefully in a remote file)" as opposed to "positioning done by HTML in the page". Surely everyone can see the benefits of the former as opposed to the latter?
Consider this:
[ picture ] [ picture ] [ picture ]
[ caption ] [ caption ] [ caption ]
which represents two rows of a table with 6 cells. Someone who can see the 2-D table layout will see a caption under each picture. But using speech synthesis, or a PDA, and for a search engine spider, that's
picture picture picture caption caption caption
and the relationship, which is obvious with the table in place, disappears.
Are DIVs and CSS better for the task of simply laying out rectangles on an HTML page to achieve a given design in the shortest possible time? No, they're probably not. But I'm not in the business of quickly laying out rectangles to achieve a given design. I'm thinking of a much bigger picture.
Try the Leaflet.awesome-markers lib -- it allows you to set colors and other styles.
I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine()
method before each call to nextLine()
, make sure the correct encoding is passed to the Scanner
constructor, e.g.:
Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
It seems Subclipse only allows you to add a top-level folder to ignore list and not any sub folders under it. Not sure why it works this way. However, I found out by trial and error that if you directly add a sub-folder to version control, then it will allow you to add another folder at the same level to the ignore list.
For example, refer fig above, when I wanted to ignore the webapp folder without adding src, subclipse was not allowing me to do so. But when I added the java folder to version control, the "add to svn:ignore..." was enabled for webapp.
for update: event: React.ChangeEvent
for submit: event: React.FormEvent
for click: event: React.MouseEvent
You could use:
cordova plugins list | awk '{print $1}' | xargs cordova plugins rm
and use cordova plugins list
to verify if plugins are all removed.
You can Try this, After starting Service of elasticsearch Type below line in your browser.
localhost:9200
It will give Output Something like that,
{
"status" : 200,
"name" : "Hypnotia",
"cluster_name" : "elasticsearch",
"version" : {
"number" : "1.7.1",
"build_hash" : "b88f43fc40b0bcd7f173a1f9ee2e97816de80b19",
"build_timestamp" : "2015-07-29T09:54:16Z",
"build_snapshot" : false,
"lucene_version" : "4.10.4"
},
"tagline" : "You Know, for Search"
}
Remove the public
keyword from int[] locations={1,2,3};
. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.
If your goal is to use this reference in many a method, you might want to move the declaration outside the method.
The difference between this two tables ItemBack1
and #ItemBack1
is that the first on is persistent (permanent) where as the other is temporary.
Now if take a look at your question again
Is it necessary to Use # for creating temp table in sql server?
The answer is Yes, because without this preceding #
the table will not be a temporary table, it will be independent of all sessions and scopes.
You want to treat dot (.
) like comma (,
). So, replace
if (double.TryParse(values[i, j], out tmp))
with
if (double.TryParse(values[i, j].Replace('.', ','), out tmp))
Looks like the image is too big and the window simply doesn't fit the screen.
Create window with the cv2.WINDOW_NORMAL
flag, it will make it scalable. Then you can resize it to fit your screen like this:
from __future__ import division
import cv2
img = cv2.imread('1.jpg')
screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)
cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
According to the OpenCV documentation CV_WINDOW_KEEPRATIO
flag should do the same, yet it doesn't and it's value not even presented in the python module.
This caused me issues, as I was doing everything listed here, but was still getting errors thrown. It turns out that calling req.abort() actually throws an error, with a code of ECONNRESET, so you actually have to catch that in your error handler.
req.on('error', function(err) {
if (err.code === "ECONNRESET") {
console.log("Timeout occurs");
return;
}
//handle normal errors
});
You can use from root directory:
RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html
Or:
RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');
The below solution solved my problem and also kept the default values
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).find('input[type="text"],input[type="email"],textarea,select').each(function() {
if (this.defaultValue != '' || this.value != this.defaultValue) {
this.value = this.defaultValue;
} else { this.value = ''; }
});
});
Here is a version of Carlo's answer that can be used in a class:
class Formatter
{
public function objectToArray($data)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(array($this, 'objectToArray'), $data);
}
return $data;
}
}
You can use this class simply:
public class DoodleCanvas extends View{
private Paint mPaint;
private Path mPath;
public DoodleCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
mPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
mPath.moveTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(event.getX(), event.getY());
invalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
I extends the SimpleJpaRepository:
public class ExtendedRepositoryImpl<T extends EntityBean> extends SimpleJpaRepository<T, Long>
implements ExtendedRepository<T> {
private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em;
public ExtendedRepositoryImpl(final JpaEntityInformation<T, ?> entityInformation,
final EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.em = entityManager;
}
}
and adds this class to @EnableJpaRepositoryries repositoryBaseClass.
@ordered = {}
@unordered.keys.sort.each do |key|
@ordered[key] = @unordered[key]
end
Here's working example with anonymous output record, if you have any questions place a comment below:
public partial class Form1 : Form
{
DataTable table;
public Form1()
{
InitializeComponent();
#region TestData
table = new DataTable();
table.Clear();
for (int i = 1; i < 12; ++i)
table.Columns.Add("Col" + i);
for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
{
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; ++i)
row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
table.Rows.Add(row);
}
#endregion
bind();
}
public void bind()
{
var filtered = from t in table.AsEnumerable()
select new
{
col1 = t.Field<string>(0),//column of index 0 = "Col1"
col2 = t.Field<string>(1),//column of index 1 = "Col2"
col3 = t.Field<string>(5),//column of index 5 = "Col6"
col4 = t.Field<string>(6),//column of index 6 = "Col7"
col5 = t.Field<string>(4),//column of index 4 = "Col3"
};
filteredData.AutoGenerateColumns = true;
filteredData.DataSource = filtered.ToList();
}
}
Using javascript URL:
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;
The FOR-LOOP generally works, but there are some issues. The FOR doesn't accept empty lines and lines with more than ~8190 are problematic. The expansion works only reliable, if the delayed expansion is disabled.
Detection of CR/LF versus single LF seems also a little bit complicated.
Also NUL characters are problematic, as a FOR-Loop immediatly cancels the reading.
Direct binary reading seems therefore nearly impossible.
The problem with empty lines can be solved with a trick. Prefix each line with a line number, using the findstr command, and after reading, remove the prefix.
@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
echo(!var!
ENDLOCAL
)
Toggling between enable and disabled delayed expansion is neccessary for the safe working with strings, like !
or ^^^xy!z
.
That's because the line set "var=%%a"
is only safe with DisabledDelayedExpansion, else exclamation marks are removed and the carets are used as (secondary) escape characters and they are removed too.
But using the variable var
is only safe with EnabledDelayedExpansion, as even a call %%var%%
will fail with content like "&"&
.
EDIT: Added set/p variant
There is a second way of reading a file with set /p
, the only disadvantages are that it is limited to ~1024 characters per line and it removes control characters at the line end.
But the advantage is, you didn't need the delayed toggling and it's easier to store values in variables
@echo off
setlocal EnableDelayedExpansion
set "file=%~1"
for /f "delims=" %%n in ('find /c /v "" %file%') do set "len=%%n"
set "len=!len:*: =!"
<%file% (
for /l %%l in (1 1 !len!) do (
set "line="
set /p "line="
echo(!line!
)
)
For reading it "binary" into a hex-representation
You could look at SO: converting a binary file to HEX representation using batch file
I use max function:
max(None, '') #Returns blank
max("Hello",'') #Returns Hello
Works like a charm ;) Just put your string in the first parameter of the function.
You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink
Assuming you have foo.conf in sites-available
Try
cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l
Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf
Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.
If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.
ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf
Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:
lrwxrwxrwx 1 root root 26 Jun 24 21:06 000-default -> ../sites-available/default
See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).
Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.
Dependency Management allows to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. This is especially useful when you have a set of projects (i.e. more than one) that inherits a common parent.
Another extremely important use case of dependencyManagement
is the control of versions of artifacts used in transitive dependencies. This is hard to explain without an example. Luckily, this is illustrated in the documentation.
In Android file system, "system.img" and "userdata.img" are VMS Alpha executable. "system.img" and "userdata.img" have the contents of /system and /data directory on root file system. They are mapped on NAND devices with yaffs2 file system. Now, yaffs2 image file can not be mounted on linux PC. If you can, maybe you got some rom that not packed in yaffs2 file system. You can check those rom file by execute the command:
file <system.img/userdata.img>
If it show "VMS Alpha executable" then you can use "unyaffs" to extract it.
Since the hosts is blocked. try connect it from other host and execute the mysqladmin flush-hosts command.
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
If you want to call the incremented number directly in a function, this solution works bettter:
Function inc(ByRef data As Integer)
data = data + 1
inc = data
End Function
for example:
Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))
If the function inc()
returns no value, the above line will generate an error.
Use this,
var currentDirectory = System.IO.Directory.GetCurrentDirectory();
You can use this as well.
var currentDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
In some cases, I'd like kill processes simutaneously like this way:
? ~ sleep 1000 & [1] 25410 ? ~ sleep 1000 & [2] 25415 ? ~ sleep 1000 & [3] 25421 ? ~ pidof sleep 25421 25415 25410 ? ~ kill `pidof sleep` [2] - 25415 terminated sleep 1000 [1] - 25410 terminated sleep 1000 [3] + 25421 terminated sleep 1000
But, I think it is a little bit inappropriate in your case.(May be there are running python a, python b, python x...in the background.)
Split creates an array . You can access the individual values by using a index.
var result=$(row).val().split('|')[2]
alert(result);
OR
var result=$(row).val().split('|');
alert(result[2]);
If it's input element then you need to use $(row).val()
to get the value..
Otherwise you would need to use $(row).text()
or $(row).html()
The following is my preferred way to assign a multi-line string to a variable (I think it looks nice).
read -r -d '' my_variable << \
_______________________________________________________________________________
String1
String2
String3
...
StringN
_______________________________________________________________________________
The number of underscores is the same (here 80) in both cases.
They really make you run around the barn to do it with the GUI:
Make sure your column does not violate the unique constraint before you begin.
alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);
Changes take effect immediately:
Command(s) completed successfully.
FormName.WindowState = FormWindowState.Minimized;
Isnull() syntax is built in for this kind of thing.
declare @Int int = null;
declare @Values table ( id int, def varchar(8) )
insert into @Values values (8, 'I am 8');
-- fails
select *
from @Values
where id = @Int
-- works fine
select *
from @Values
where id = isnull(@Int, 8);
For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.
declare @Int int = null;
declare @Values table ( id int, def varchar(16) )
insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');
select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')
I need to add my 5 cents. I see everybody use [
or [[
, but it worth to mention that they are not part of if syntax.
For arithmetic comparisons, use ((...))
instead.
((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.
See: ArithmeticExpression
My solution is very silly. I had tried all the solutions above and wasted so many hours. Then I found out the solution when I browsed developer options. I didn't check mark the "USB debugging" option. The silly me assumed turns on developer options mean turns on USB debugging, but I was wrong.
No previous solution worked for me.
I've installed both by apt-get
and manually downloading the tessdata, moved around /usr
and so on and no one worked even if i exported the variable thousand times.
Finally, on a last try before start to cry i've tried to pass the path directly to the instance of Tesseract().
In Python: tr = Tesseract("/usr/local/share/tesseract-ocr/")
and now it works. To clarify, im using tesserwrap
module.
Try to use the new '@supports' feature, here is one good hack that you might like:
* UPDATE!!! * Microsoft Edge and Safari 9 both added support for the @supports feature in Fall 2015, Firefox also -- so here is my updated version for you:
/* Chrome 29+ (Only) */
@supports (-webkit-appearance:none) and (not (overflow:-webkit-marquee))
and (not (-ms-ime-align:auto)) and (not (-moz-appearance:none)) {
.selector { color:red; }
}
More info on this here (the reverse... Safari but not Chrome): [ is there a css hack for safari only NOT chrome? ]
The previous CSS Hack [before Edge and Safari 9 or newer Firefox versions]:
/* Chrome 28+ (now also Microsoft Edge, Firefox, and Safari 9+) */
@supports (-webkit-appearance:none) { .selector { color:red; } }
This worked for (only) chrome, version 28 and newer.
(The above chrome 28+ hack was not one of my creations. I found this on the web and since it was so good I sent it to BrowserHacks.com recently, there are others coming.)
August 17th, 2014 update: As I mentioned, I have been working on reaching more versions of chrome (and many other browsers), and here is one I crafted that handles chrome 35 and newer.
/* Chrome 35+ */
_::content, _:future, .selector:not(*:root) { color:red; }
In the comments below it was mentioned by @BoltClock about future, past, not... etc... We can in fact use them to go a little farther back in Chrome history.
So then this is one that also works but not 'Chrome-only' which is why I did not put it here. You still have to separate it by a Safari-only hack to complete the process. I have created css hacks to do this however, not to worry. Here are a few of them, starting with the simplest:
/* Chrome 26+, Safari 6.1+ */
_:past, .selector:not(*:root) { color:red; }
Or instead, this one which goes back to Chrome 22 and newer, but Safari as well...
/* Chrome 22+, Safari 6.1+ */
@media screen and (-webkit-min-device-pixel-ratio:0)
and (min-resolution:.001dpcm),
screen and(-webkit-min-device-pixel-ratio:0)
{
.selector { color:red; }
}
The block of Chrome versions 22-28 (more complicated but works nicely) are also possible to target via a combination I worked out:
/* Chrome 22-28 (Only!) */
@media screen and(-webkit-min-device-pixel-ratio:0)
{
.selector {-chrome-:only(;
color:red;
);}
}
Now follow up with this next couple I also created that targets Safari 6.1+ (only) in order to still separate Chrome and Safari. Updated to include Safari 8
/* Safari 6.1-7.0 */
@media screen and (-webkit-min-device-pixel-ratio:0) and (min-color-index:0)
{
.selector {(; color:blue; );}
}
/* Safari 7.1+ */
_::-webkit-full-page-media, _:future, :root .selector { color:blue; }
So if you put one of the Chrome+Safari hacks above, and then the Safari 6.1-7 and 8 hacks in your styles sequentially, you will have Chrome items in red, and Safari items in blue.
Suppose you want to print the SQL query of the following statements.
$user = User::find(5);
You just need to do as follows:
DB::enableQueryLog();//enable query logging
$user = User::find(5);
print_r(DB::getQueryLog());//print sql query
This will print the last executed query in Laravel.
You can't use it from the XML.
You need to extend the widget you are using in the XML and add the logic to set the text using what's mentioned on Konstantin Burov's answer.
If the space on that page is not disabled then put your button inside a div.
<div id="a1">
<button>Click here</button>
</div>
Using Jquery:
<script language="javascript">
$("#a1").hide();
</script>
Using JS:
<script language="javascript">
document.getElementById("a1").style.visibility = "hidden";
document.getElementById("a1").style.display = "none";
</script>
I've tried out many answers on this page, none really worked:
So instead of writing readable code, I decided to use the simple and workable approach mentioned in the question instead.
Hopefully another solution will come up.
The below function would return '0' if there is no match and a 'positive integer' in case of matching:
Function IsInArray(stringToBeFound As String, arr As Variant) As Integer
IsInArray = InStr(Join(arr, ""), stringToBeFound)
End Function
______________________________________________________________________________
Note: the function first concatenates the entire array content to a string using 'Join' (not sure if the join method uses looping internally or not) and then checks for a macth within this string using InStr.
EDIT: Changed to fit other feedback.
I understood you to mean that if there is no decimal point, then there shouldn't be two more digits. So this should be it:
\d{0,2}(\.\d{1,2})?
That should do the trick in most implementations. If not, you can use:
[0-9]?[0-9]?(\.[0-9][0-9]?)?
And that should work on every implementation I've seen.
If @Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.
clickHandler = function(event){
if (click++ == 49)
canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);
Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:
Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll
. MAKE SURE "Verify the file exists" IS NOT CHECKED!
Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
Here's a simplified version, for MacVim, using the the Wikia article examples (cf. link from gun's comment).
" Move selection up/down (add =gv to reindent after move)
:vmap <D-S-Up> :m-2<CR>gv
:vmap <D-S-Down> :m'>+<CR>gv
I'm using only the block selection variant, because all it takes is Shift-V to select the current line, and optionally cursor up/down to select some more lines.
According to the shortcuts above, pressing Cmd-Shift-Up/Down will shift the block selection up/down. "D" is the Command key in MacVim, for Windows try "C" (Control), or "A" (Alt) (eg. <C-A-f> would be Control Alt f).
The Wikia article adds "=gv" to these, which has the effect to adjust the indentation of the block after the move, based on surrounding text. This is confusing so I removed it, and added shortcuts for quickly indenting the selection instead.
" Indent selection left/right (Cmd Shift Left/Right is used for Tab switching)
:vmap <D-A-Left> <gv
:vmap <D-A-Right> >gv
Mind, the same can be done with << and >> but the selection would be lost, so these shortcuts above allow to indent multiple times and still move the block around because the selection is maintained.
My MacVim is configured to switch Tabs with Cmd-Shift-Left/Right so I used Cmd-Alt-Left/Right.
Here's the Tab switching for MacVim (put in .gvimrc with the rest above):
:macm Window.Select\ Previous\ Tab key=<D-S-Left>
:macm Window.Select\ Next\ Tab key=<D-S-Right>
const times = 4;
new Array(times).fill().map(() => console.log('test'));
This snippet will console.log
test
4 times.
Another possible solution which I think is more semantically correct is to change the floated inner elements to be 'display: inline'. This example and what I was working on when I came across this page both use floated divs in much exactly the same way that a span would be used. Instead of using divs, switch to span, or if you are using another element which is by default 'display: block' instead of 'display: inline' then change it to be 'display: inline'. I believe this is the 100% semantically correct solution.
Solution 1, floating the parent, is essentially to change the entire document to be floated.
Solution 2, setting an explicit height, is like drawing a box and saying I want to put a picture here, i.e. use this if you are doing an img tag.
Solution 3, adding a spacer to clear float, is like adding an extra line below your content and will mess with surrounding elements too. If you use this approach you probably want to set the div to be height: 0px.
Solution 4, overflow: auto, is acknowledging that you don't know how to lay out the document and you are admitting that you don't know what to do.
Because it's all just about memory, in the end all the numerical values are stored in binary.
A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.
When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.
You can also try following,
long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
Yarn
I had the problem when running: yarn start
It was fixed with running first: yarn install
I have been passing down setter methods from the parent to one of its children through a binding, calling that method with the data from the child component, meaning that the parent component is updated and can then update its second child component with the new data. It does require binding 'this' or using an arrow function though.
This has the benefit that the children aren't so coupled to each other as they don't need a specific shared service.
I am not entirely sure that this is best practice, would be interesting to hear others views on this.
It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:
Code:
Array.prototype.findFirstSubstring = function(s) {
for(var i = 0; i < this.length;i++)
{
if(this[i].indexOf(s) !== -1)
return i;
}
return -1;
};
Usage:
i.findFirstSubstring('height');
Returns:
-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2
)
Is something like this what you're looking for?
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
Usage:
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
IE8 defaults to standards mode for the intERnet and quirks mode for the intRAnet. The HTML meta tag is ignored if you have the doctype set to xhtml transitional. The solution is to add an HTTP header in code. This worked for us. Now our intranet site is forcing IE8 to render the app in standards mode.
Added to PageInit of the base page class (ASP.net C#):
Response.AddHeader("X-UA-Compatible", "IE=EmulateIE8");
reference: http://ilia.ws/archives/196-IE8-X-UA-Compatible-Rant.html
This code will accept all country code with + sign
<input type="text" pattern="[0-9]{5}[-][0-9]{7}[-][0-9]{1}"/>
Some countries allow a single "0" character instead of "+" and others a double "0" character instead of the "+". Neither are standard.
div.test td, div.test caption, div.test th
works for me.
The child selector > does not work in IE6.
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
In case there are any morons out there like me, I had this frustrating problem because I forgot a simple
new
keyword before instantiating a new object.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);
Should work.
Here's a working example:
Excerpt:
function loadIframe(iframeName, url) {
var $iframe = $('#' + iframeName);
if ($iframe.length) {
$iframe.attr('src',url);
return false;
}
return true;
}
Thanks for the above codes! - I tried several options and this was the ticket. I had problems in that preventDefault was preventing scrolling on the ipad - I am now testing for draggable items and it works great so far.
if (event.target.id == 'draggable_item' ) {
event.preventDefault();
}
If you want to iterate over a list and create a new list with "transformed" objects, you should use the map()
function of stream + collect()
. In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.
public class Test {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("e1", "l1"),
new Person("e2", "l1"),
new Person("e3", "l2"),
new Person("e4", "l2")
);
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.map(p -> new Employee(p.getName(), p.getLastName(), 1000))
.collect(Collectors.toList());
System.out.println(employees);
}
}
class Person {
private String name;
private String lastName;
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
// Getter & Setter
}
class Employee extends Person {
private double salary;
public Employee(String name, String lastName, double salary) {
super(name, lastName);
this.salary = salary;
}
// Getter & Setter
}
As an Anaconda user, I wanted to find one or two appropriate commands to solve the problem. Fortunately, this answer helped. For conda 4.5.11 (use conda -V
to check Anaconda version) I have performed next steps:
# Python version does not matter, most likely, check yourself
conda create -n myenv python=3.6
conda activate myenv
conda install -c menpo opencv
That will install OpenCV 2.4.11. Anaconda's another command conda install -c menpo opencv3
will install OpenCV3, but Python has to be downgraded to 2.7. To install OpenCV3 with Python3 use next (due to the first link):
conda create -n myenv python
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
Check the SIFT:
conda activate myenv
python
>>> cv2.xfeatures2d.SIFT_create()
<xfeatures2d_SIFT 000002A3478655B0>
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (df[[new1, new2]] = ...
), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as the columns you are creating).
Your syntax works fine for assigning scalar values to existing columns, and pandas is also happy to assign scalar values to a new column using the single-column syntax (df[new1] = ...
). So the solution is either to convert this into several single-column assignments, or create a suitable DataFrame for the right-hand side.
Here are several approaches that will work:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
Then one of the following:
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
DataFrame
conveniently expands a single row to match the index, so you can do this:df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
df = pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
)
], axis=1
)
join
instead of concat
(may be less efficient):df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
.assign()
with multiple column arguments.I like this variant on @zero's answer a lot, but like the previous one, the new columns will always be sorted alphabetically, at least with early versions of Python:
df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)
new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols) # add empty cols
df[new_cols] = new_vals # multi-column assignment works for existing cols
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3
Note: many of these options have already been covered in other answers: Add multiple columns to DataFrame and set them equal to an existing column, Is it possible to add several columns at once to a pandas DataFrame?, Add multiple empty columns to pandas DataFrame
Assuming that both data1()
and data2()
are in the same class, then another alternative is to make data1()
static.
private static void data1()
{
}
private static void data2()
{
data1();
}
It seems as though the "sr-only" element and its styles inside of the table are what's causing this bug. At least I had the same issue and after months of banging our head against the wall that's what we determined the cause was, though I still don't understand why. Adding left:0
to the "sr-only" styles fixed it.
Dumpbin.exe
of VS2005
generally presents in C:\Program Files\Microsoft Visual Studio 8\VC\bin
. If you would have installed VS2005
in drive other the C
, please search in that.
And then set that path in the system variable PATH
.
that's all! simple.
Working Example to Put Your File on Root ...........see its very simple
#!/bin/sh
HOST='ftp.users.qwest.net'
USER='yourid'
PASSWD='yourpw'
FILE='file.txt'
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
put $FILE
quit
END_SCRIPT
exit 0
I'm on a mac and I use postgres via Postgres.app
. I solved this problem just quitting and starting again the app.
Below query worked for me with default value false;
ALTER TABLE cti_contract_account ADD ready_to_audit BIT DEFAULT 0 NOT NULL;
either:
df['index1'] = df.index
or, .reset_index
:
df.reset_index(level=0, inplace=True)
so, if you have a multi-index frame with 3 levels of index, like:
>>> df
val
tick tag obs
2016-02-26 C 2 0.0139
2016-02-27 A 2 0.5577
2016-02-28 C 6 0.0303
and you want to convert the 1st (tick
) and 3rd (obs
) levels in the index into columns, you would do:
>>> df.reset_index(level=['tick', 'obs'])
tick obs val
tag
C 2016-02-26 2 0.0139
A 2016-02-27 2 0.5577
C 2016-02-28 6 0.0303
you can use
git pull --rebase <your_reponame> <your_branch>
this will help incase you have some changes not yet registered on your local repo. especially README.md
Try using the command: git status
PLease make sure to backup your changes before running these commmand in a separate folder
git checkout branch_name
Checkout on your branch
git merge --abort
Abort the merge
git status
Check status of the code after aborting the merge
git reset --hard origin/branch_name
these command will reset your changes and align your code with the branch_name (branch) code.
You can find all Chrome extensions in below location.
/Users/{mac_user}/Library/Application Support/Google/Chrome/Default/Extensions
You don't need JSON loader. Node provides ECMAScript Modules (ES6 Module support) with the --experimental-modules
flag, you can use it like this
node --experimental-modules myfile.mjs
Then it's very simple
import myJSON from './myJsonFile.json';
console.log(myJSON);
Then you'll have it bound to the variable myJSON
.
I'm guessing this will help.
When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type:
int x[]
or
int x[a]
. Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.
Here's one that looks very promising. It's a true combo - you see what you type. Has a cool feature I haven't seen elsewhere: paging results.
These three commands have entirely different purposes. They are not even remotely similar.
git revert
This command creates a new commit that undoes the changes from a previous commit. This command adds new history to the project (it doesn't modify existing history).
git checkout
This command checks-out content from the repository and puts it in your work tree. It can also have other effects, depending on how the command was invoked. For instance, it can also change which branch you are currently working on. This command doesn't make any changes to the history.
git reset
This command is a little more complicated. It actually does a couple of different things depending on how it is invoked. It modifies the index (the so-called "staging area"). Or it changes which commit a branch head is currently pointing at. This command may alter existing history (by changing the commit that a branch references).
If a commit has been made somewhere in the project's history, and you later decide that the commit is wrong and should not have been done, then git revert
is the tool for the job. It will undo the changes introduced by the bad commit, recording the "undo" in the history.
If you have modified a file in your working tree, but haven't committed the change, then you can use git checkout
to checkout a fresh-from-repository copy of the file.
If you have made a commit, but haven't shared it with anyone else and you decide you don't want it, then you can use git reset
to rewrite the history so that it looks as though you never made that commit.
These are just some of the possible usage scenarios. There are other commands that can be useful in some situations, and the above three commands have other uses as well.
With IntelliJ IDEA
you can create a Jar Application
runtime configuration, select the JAR
, the sources, the JRE
to run the Jar
with and start debugging. Here is the documentation.
That is taking the parameter by reference. So in the first case you are taking a pointer parameter by reference so whatever modification you do to the value of the pointer is reflected outside the function. Second is the simlilar to first one with the only difference being that it is a double pointer. See this example:
void pass_by_value(int* p)
{
//Allocate memory for int and store the address in p
p = new int;
}
void pass_by_reference(int*& p)
{
p = new int;
}
int main()
{
int* p1 = NULL;
int* p2 = NULL;
pass_by_value(p1); //p1 will still be NULL after this call
pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory
return 0;
}
A little late to the party, but this is how I did it for an insert:
DECLARE @ManagerID AS Varchar (25) = 'NA'
DECLARE @ManagerEmail AS Varchar (50) = 'NA'
Declare @RecordCount AS int = 0
SET @ManagerID = ?
SET @ManagerEmail = ?
SET @RecordCount = ?
INSERT INTO...
This should make it work in both cases
function onDateChange() {
// Do something here
}
$('#dpd1').bind('changeDate', onDateChange);
$('#dpd1').bind('input', onDateChange);
**multiple delete not working**
function delete_selection()
{
$id_array = array();
$selection = $this->input->post("selection", TRUE);
$id_array = explode("|", $selection);
foreach ($id_array as $item):
if ($item != ''):
//DELETE ROW
$this->db->where('entry_id', $item);
$this->db->delete('helpline_entry');
endif;
endforeach;
}
another version:
var yy = (new Date().getFullYear()+'').slice(-2);
Git offers a range of difftools pre-configured "out-of-the-box" (kdiff3, kompare, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, diffuse, opendiff, p4merge and araxis), and also allows you to specify your own. To use one of the pre-configured difftools (for example, "vimdiff"), you add the following lines to your ~/.gitconfig
:
[diff]
tool = vimdiff
Now, you will be able to run "git difftool" and use your tool of choice.
Specifying your own difftool, on the other hand, takes a little bit more work, see How do I view 'git diff' output with my preferred diff tool/ viewer?
I received the same error (SCRIPT7002: XMLHttpRequest: Network Error 0x80004004, Operation aborted
), in our case it was because of JavaScript's same origin policy.
Our web app was making a JQuery AJAX call to our server on Port 8080. The call was getting intercepted and re-routed over SSL (due to server rules mandating that incoming traffic use SSL).
Once we made our web app load through the SSL port the issue was fixed.
Dont know whether I should put this as answer or not...
I used @Zeeshan0026's solution to draw the path...and the problem was that if I draw path once, and then I do try to draw path once again, both two paths show and this continues...paths showing even when markers were deleted... while, ideally, old paths' shouldn't be there once new path is drawn / markers are deleted..
going through some other question over SO, I had the following solution
I add the following function in Zeeshan's class
public void clearRoute(){
for(Polyline line1 : polylines)
{
line1.remove();
}
polylines.clear();
}
in my map activity, before drawing the path, I called this function.. example usage as per my app is
private Route rt;
rt.clearRoute();
if (src == null) {
Toast.makeText(getApplicationContext(), "Please select your Source", Toast.LENGTH_LONG).show();
}else if (Destination == null) {
Toast.makeText(getApplicationContext(), "Please select your Destination", Toast.LENGTH_LONG).show();
}else if (src.equals(Destination)) {
Toast.makeText(getApplicationContext(), "Source and Destinatin can not be the same..", Toast.LENGTH_LONG).show();
}else{
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
}
you can use rt.clearRoute();
as per your requirements..
Hoping that it will save a few minutes of someone else and will help some beginner in solving this issue..
Complete Class Code
see on github
Edit: here is part of code from mainactivity..
case R.id.mkrbtn_set_dest:
Destination = selmarker.getPosition();
destmarker = selmarker;
desShape = createRouteCircle(Destination, false);
if (src == null) {
Toast.makeText(getApplicationContext(),
"Please select your Source first...",
Toast.LENGTH_LONG).show();
} else if (src.equals(Destination)) {
Toast.makeText(getApplicationContext(),
"Source and Destinatin can not be the same..",
Toast.LENGTH_LONG).show();
} else {
if (isNetworkAvailable()) {
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
src = null;
Destination = null;
} else {
Toast.makeText(
getApplicationContext(),
"Internet Connection seems to be OFFLINE...!",
Toast.LENGTH_LONG).show();
}
}
break;
Edit 2 as per comments
usage :
//variables as data members
GoogleMap mMap;
private Route rt;
static LatLng src;
static LatLng Destination;
//MapsMainActivity is my activity
//false for interim stops for traffic, google
// en language for html description returned
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
If by string you mean std::string
you can do it with this method:
QString QString::fromStdString(const std::string & str)
std::string str = "Hello world";
QString qstr = QString::fromStdString(str);
If by string you mean Ascii encoded const char *
then you can use this method:
QString QString::fromAscii(const char * str, int size = -1)
const char* str = "Hello world";
QString qstr = QString::fromAscii(str);
If you have const char *
encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:
QString QString::fromLocal8Bit(const char * str, int size = -1)
const char* str = "zazólc gesla jazn"; // latin2 source file and system encoding
QString qstr = QString::fromLocal8Bit(str);
If you have const char *
that's UTF8 encoded then you'll need to use this method:
QString QString::fromUtf8(const char * str, int size = -1)
const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
QString qstr = QString::fromUtf8(str);
There's also method for const ushort *
containing UTF16 encoded string:
QString QString::fromUtf16(const ushort * unicode, int size = -1)
const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
QString qstr = QString::fromUtf16(str);
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
WebDriver driver=new FirefoxDriver();
driver.get("http://www.java-examples.com/java-string-examples");
Thread.sleep(3000);
//Switch to nested frame
driver.switchTo().frame("aswift_2").switchTo().frame("google_ads_frame3");
For some reason
if (strictBounds.contains(map.getCenter())) return;
didnt work for me (maybe a southern hemisphere issue). I had to change it to:
function checkBounds() {
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if(x < minX || x > maxX || y < minY || y > maxY) {
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
}
}
Hope it will help someone.
var groupedCustomerList = CustomerList
.GroupBy(u => u.GroupID, u=>{
u.Name = "User" + u.Name;
return u;
}, (key,g)=>g.ToList())
.ToList();
If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:
public class Customer {
public int ID { get; set; }
public string Name { get; set; }
public int GroupID { get; set; }
public Customer CloneWithNamePrepend(string prepend){
return new Customer(){
ID = this.ID,
Name = prepend + this.Name,
GroupID = this.GroupID
};
}
}
//Then
var groupedCustomerList = CustomerList
.GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
.ToList();
I think you may want to display the Customer
differently without modifying the original data. If so you should design your class Customer
differently, like this:
public class Customer {
public int ID { get; set; }
public string Name { get; set; }
public int GroupID { get; set; }
public string Prefix {get;set;}
public string FullName {
get { return Prefix + Name;}
}
}
//then to display the fullname, just get the customer.FullName;
//You can also try adding some override of ToString() to your class
var groupedCustomerList = CustomerList
.GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
.ToList();
Setting the CSS property after you have used .show()
should work. Maybe you are targeting the wrong element on your HTML page.
$('#foo').css('display', 'inline-block');
But if you are not using any effects of .show(), .hide()
why don't you set those CSS properties manually like:
$('#foo').css('display','none');
$('#foo').css('display','inline-block');
[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
Here is how I have been able to generate multiple maps on the same page using Google Map API V3
. Kindly note that this is an off the cuff code that addresses the issue above.
The HTML bit
<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>
Javascript for map initialization
<script type="text/javascript">
var map, map2;
function initialize(condition) {
// create the maps
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(0.0, 0.0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script>
unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.
So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.
Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.
Group Join method is unnecessary to achieve joining of two data sets.
Inner Join:
var qry = Foos.SelectMany
(
foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id),
(foo, bar) => new
{
Foo = foo,
Bar = bar
}
);
For Left Join just add DefaultIfEmpty()
var qry = Foos.SelectMany
(
foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id).DefaultIfEmpty(),
(foo, bar) => new
{
Foo = foo,
Bar = bar
}
);
EF and LINQ to SQL correctly transform to SQL. For LINQ to Objects it is beter to join using GroupJoin as it internally uses Lookup. But if you are querying DB then skipping of GroupJoin is AFAIK as performant.
Personlay for me this way is more readable compared to GroupJoin().SelectMany()
Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:
"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png
You can try doing:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
Now the class is this
<img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
I tried a number of these and finally came up with the following that works for me with Select2 4.0.1. element is the <select>
element.
$.data(element).select2.on("focus", function (e) {
$(element).select2("open");
});
try this
<?php
$yesterday = date(“d.m.Y”, time()-86400);
echo $yesterday;
I know this is a way late, but I thought I'd add yet another way of doing this.
You can take advantage of the fact that the Text property can be set using "Runs", so you can set up multiple bindings using a Run for each one. This is useful if you don't have access to MultiBinding (which I didn't find when developing for Windows Phone)
<TextBlock>
<Run Text="Name = "/>
<Run Text="{Binding Name}"/>
<Run Text=", Id ="/>
<Run Text="{Binding Id}"/>
</TextBlock>
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)
You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.
Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.
I had a similar issue, but it turns out I was just referencing a cell which was off the page {i.e. cells(i,1).cut cells (i-1,2)
}
You can use:
string regExp = "\\W";
This is equivalent to Daniel's "[^a-zA-Z0-9]
"
\W matches any nonword character. Equivalent to the Unicode categories [^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]
.
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
For temporary solution just right click on Project => Properties => Java compiler => over there please select compiler compliance level 1.8 => .class compatibility 1.8 => source compatibility 1.8.
Then your code will start to execute on version 1.8.
In C#/.NET 3.5 you could write a little program to do:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}
This will list all the users in the current domain:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}
In the terminal, write mysql -u root -p
and hit Return.
Enter the current mysql password that you must have noted down.
And set the password
SET PASSWORD = PASSWORD('new_password');
Please refer to this documentation here for more details.
Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.
toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.
var fval = 4;
console.log(fval.toFixed(2)); // prints 4.00
You could require the type to be a reference type :
private static T ReadData<T>(XmlReader reader, string value) where T : class
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAsObject();
return (T)readData;
}
And then do another that uses value types and TryParse...
private static T ReadDataV<T>(XmlReader reader, string value) where T : struct
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAsObject();
int outInt;
if(int.TryParse(readData, out outInt))
return outInt
//...
}
import pylab as plb
plb.rcParams['font.size'] = 12
or
import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12
open bash profile in textEdit
open -e .bash_profile
Edit file or paste in front of PATH export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin:~/bin
save & close the file
*To open .bash_profile directly open textEdit > file > recent
In my case where I wanted to have something like this:
I had to follow the same thing as suggested by @Mdlc but probably slightly simpler (targeting only >= 21):
//kotlin
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val realSize = Point()
windowManager.defaultDisplay.getRealSize(realSize);
val usableRect = Rect()
windowManager.defaultDisplay.getRectSize(usableRect)
Toast.makeText(this, "Usable Screen: " + usableRect + " real:"+realSize, Toast.LENGTH_LONG).show()
window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
It works on landscape too:
Edit The above solution does not work correctly in multi-window mode where the usable rectangle is not smaller just due to the navigation bar but also because of custom window size. One thing that I noticed is that in multi-window the navigation bar is not hovering over the app so even with no changes to DecorView padding we have the correct behaviour:
Note the difference between how navigation bar is hovering over the bottom of the app in these to scenarios. Fortunately, this is easy to fix. We can check if app is multi window. The code below also includes the part to calculate and adjust the position of toolbar (full solution: https://stackoverflow.com/a/14213035/477790)
// kotlin
// Let the window flow into where window decorations are
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
// calculate where the bottom of the page should end up, considering the navigation bar (back buttons, ...)
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val realSize = Point()
windowManager.defaultDisplay.getRealSize(realSize);
val usableRect = Rect()
windowManager.defaultDisplay.getRectSize(usableRect)
Toast.makeText(this, "Usable Screen: " + usableRect + " real:" + realSize, Toast.LENGTH_LONG).show()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !isInMultiWindowMode) {
window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
// move toolbar/appbar further down to where it should be and not to overlap with status bar
val layoutParams = ConstraintLayout.LayoutParams(appBarLayout.layoutParams as ConstraintLayout.LayoutParams)
layoutParams.topMargin = getSystemSize(Constants.statusBarHeightKey)
appBarLayout.layoutParams = layoutParams
}
Result on Samsung popup mode:
EDIT
As pointed out by @Kwame , the below code does validate the url even if the
.com
or.co
etc are not present.also pointed out by @Blaise, URLs like https://www.google is a valid URL and you need to do a DNS check for checking if it resolves or not, separately.
This is simple and works:
So min_attr
contains the basic set of strings that needs to be present to define the validity of a URL,
i.e http://
part and google.com
part.
urlparse.scheme
stores http://
and
urlparse.netloc
store the domain name google.com
from urlparse import urlparse
def url_check(url):
min_attr = ('scheme' , 'netloc')
try:
result = urlparse(url)
if all([result.scheme, result.netloc]):
return True
else:
return False
except:
return False
all()
returns true if all the variables inside it return true.
So if result.scheme
and result.netloc
is present i.e. has some value then the URL is valid and hence returns True
.
you can use this http://www.md5decrypt.org/ or this http://md5.gromweb.com/ it will decrypt your md5 code
There is a Refactor --> Rename Bug in Visual Studio 2012 that wrongly renamed the "id" inside the literal string value of the url parameter in my RouteConfig.cs. This caused a 403.14 on a fresh and otherwise correct setup in both Windows Server 2012 and Windows Server 2008 R2.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
was changed to
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{renamed_text}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def
it's something like creating this instance with Object
(You can read more about def
here). And []
creates empty ArrayList
in this case.
So using def list = []
you can then append new items with add()
method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
Import and Export of a SQLite database on Android
Here is my function for export database into device storage
private void exportDB(){
String DatabaseName = "Sycrypter.db";
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
Here is my function for import database from device storage into android application
private void importDB(){
String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
File sd = new File(dir);
File data = Environment.getDataDirectory();
FileChannel source = null;
FileChannel destination = null;
String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
String currentDBPath = "Sycrypter.db";
File currentDB = new File(sd, currentDBPath);
File backupDB = new File(data, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
First of all check to see if your PHP installation supports CLI. Type: php -v
. You can execute PHP from the command line in 2 ways:
php yourfile.php
php -r 'print("Hello world");'
You can follow this tutorial on how to use Google Maps for testing on localhost.
- Click this link and follow the process (create new project, API key > Browser key, register 'localhost' domain): https://console.developers.google.com//flows/enableapi?apiid=maps_backend&keyType=CLIENT_SIDE&reusekey=true
- Generate the key
- Deploy Google Maps widget as described here: http://www2.microstrategy.com/producthelp/10/GISHelp/Lang_1033/GIS_Integration.htm
- Add your Google Maps API key to googleConfig.xml (as desribed in the previous link) ENTER_YOUR_KEY_HERE
- Restart Web Server
Check these related SO threads:
Hope this helps!
A simple ES6 way to get both the first key and remaining parts in a string would be:
const [key, ...rest] = "good_luck_buddy".split('_')
const value = rest.join('_')
console.log(key, value) // good, luck_buddy
If, for example, x = 5 and is stored as string, you can also just:
x = x + 0
and the new x would be stored as a numeric value.
In object oriented design, the amount of coupling refers to how much the design of one class depends on the design of another class. In other words, how often do changes in class A force related changes in class B? Tight coupling means the two classes often change together, loose coupling means they are mostly independent. In general, loose coupling is recommended because it's easier to test and maintain.
You may find this paper by Martin Fowler (PDF) helpful.
| 0000 0001 0010 0011 0100 0101 0110 0111 | ------> EAX
| 0100 0101 0110 0111 | ------> AX
| 0110 0111 | ------> AL
| 0100 0101 | ------> AH
More Suggestion
JavaScript:
$.ajax({
url: "http://FullUrl",
dataType: 'jsonp',
success: function (data) {
//Data from the server in the in the variable "data"
//In the form of an array
}
});
PHP CallBack:
<?php
$array = array(
'0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
'1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);
if(isset ($_GET['callback']))
{
header("Content-Type: application/json");
echo $_GET['callback']."(".json_encode($array).")";
}
?>
git rev-list --max-parents=0 HEAD
(from tiho's comment. As Chris Johnsen notices, --max-parents
was introduced after this answer was posted.)
Technically, there may be more than one root commit. This happens when multiple previously independent histories are merged together. It is common when a project is integrated via a subtree merge.
The git.git
repository has six root commits in its history graph (one each for Linus’s initial commit, gitk, some initially separate tools, git-gui, gitweb, and git-p4). In this case, we know that e83c516
is the one we are probably interested in. It is both the earliest commit and a root commit.
It is not so simple in the general case.
Imagine that libfoo has been in development for a while and keeps its history in a Git repository (libfoo.git
). Independently, the “bar” project has also been under development (in bar.git
), but not for as long libfoo (the commit with the earliest date in libfoo.git
has a date that precedes the commit with the earliest date in bar.git
). At some point the developers of “bar” decide to incorporate libfoo into their project by using a subtree merge. Prior to this merge it might have been trivial to determine the “first” commit in bar.git
(there was probably only one root commit). After the merge, however, there are multiple root commits and the earliest root commit actually comes from the history of libfoo, not “bar”.
You can find all the root commits of the history DAG like this:
git rev-list --max-parents=0 HEAD
For the record, if --max-parents
weren't available, this does also work:
git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$"
If you have useful tags in place, then git name-rev
might give you a quick overview of the history:
git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" | git name-rev --stdin
Use this often? Hard to remember? Add a git alias for quick access
git config --global alias.first "rev-list --max-parents=0 HEAD"
Now you can simply do
git first
You can add a reference to System.Configuration
in your project and then:
using System.Configuration;
then
string sValue = ConfigurationManager.AppSettings["BatchFile"];
with an app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BatchFile" value="blah.bat" />
</appSettings>
</configuration>
Here is another solution using Jquery I find it a little easier and neater than inline JS sometimes.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
/* if you prefer to functionize and use onclick= rather then the .on bind
function hide_show(){
$(this).hide();
$("#hidden-div").show();
}
*/
$(function(){
$("#chkbtn").on('click',function() {
$(this).hide();
$("#hidden-div").show();
});
});
</script>
<style>
.hidden-div {
display:none
}
</style>
</head>
<body>
<div class="reform">
<form id="reform" action="action.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="type" value="" />
<fieldset>
content here...
</fieldset>
<div class="hidden-div" id="hidden-div">
<fieldset>
more content here that is hidden until the button below is clicked...
</fieldset>
</form>
</div>
<span style="display:block; padding-left:640px; margin-top:10px;"><button id="chkbtn">Check Availability</button></span>
</div>
</body>
</html>
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
Try using Carbon
$d1 = \Carbon\Carbon::now()->subDays(92);
$d2 = \Carbon\Carbon::now()->subDays(10);
$days_btw = $d1->diffInDays($d2);
Also you can use
\Carbon\Carbon::parse('')
to create an object of Carbon date using given timestamp string.
This worked for me:
driver.findElement(yourElement).clear();
driver.findElement(yourelement).sendKeys("");
Assume that you have multiple properties you want to convert.
public class OrigType{
public string Prop1A {get;set;}
public string Prop1B {get;set;}
}
public class TargetType{
public string Prop2A {get;set;}
public string Prop2B {get;set;}
}
var list1 = new List<OrigType>();
var list2 = new List<TargetType>();
list1.ConvertAll(x => new OrigType { Prop2A = x.Prop1A, Prop2B = x.Prop1B })
https://github.com/reoxey/benchmark
benchmark
speed comparison of MySQL & MongoDB in GOLANG1.6 & PHP5
system used for benchmark: DELL cpu i5 4th gen 1.70Ghz * 4 ram 4GB GPU ram 2GB
Speed comparison of RDBMS vs NoSQL for INSERT, SELECT, UPDATE, DELETE executing different number of rows 10,100,1000,10000,100000,1000000
Language used to execute is: PHP5 & Google fastest language GO 1.6
________________________________________________
GOLANG with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 1.195444ms
100 6.075053ms
1000 47.439699ms
10000 483.999809ms
100000 4.707089053s
1000000 49.067407174s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 872.709µs
SELECT & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 20.717354746s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 2.309209968s
100000 257.411502ms
10000 26.73954ms
1000 3.483926ms
100 915.17µs
10 650.166µs
DELETE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 6.065949ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
GOLANG with MongoDB
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 2.067094ms
100 8.841597ms
1000 106.491732ms
10000 998.225023ms
100000 8.98172825s
1000000 1m 29.63203158s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 5.251337439s
FIND & DISPLAY (with index declared)
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 21.540603252s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1 1.330954ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
PHP5 with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 0.0040680000000001s
100 0.011595s
1000 0.049718s
10000 0.457164s
100000 4s
1000000 42s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 <1s
SELECT & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 20s
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
PHP5 with MongoDB
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 0.065744s
100 0.190966s
1000 0.2163s
10000 1s
100000 8s
1000000 78s
FIND
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 <1s
FIND & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 7s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 9s
If you want statically make columns not sortable. You can do this way
Simplest Way with Jquery -
var finalObj = $.extend(obj1, obj2);
Without Jquery -
var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];
if you are using themeroller:
.dataTables_wrapper .fg-toolbar { display: none; }
Here is a noise-free version of the solution which is to use with_items:
- name: add lines
lineinfile:
dest: fruits.txt
line: '{{ item }}'
with_items:
- 'Orange'
- 'Apple'
- 'Banana'
For each item, if the item exists in fruits.txt no action is taken.
If the item does not exist it will be appended to the end of the file.
Easy-peasy.
import java.util.*
You can gethour and minute using calendar and formatter class. Calendar cal = Calendar.getInstance()
and Formatter fmt=new Formatter()
and set a format for display hour and minute fmt.format("%tl:%M",cal,cal)
and print System.out.println(fmt)
output shows like 10:12
I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.
Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.
vue-moment
very nice plugin for vue project and works very smoothly with the components and existing code. Enjoy the moments...
// in your main.js
Vue.use(require('vue-moment'));
// and use in component
{{'2019-10-03 14:02:22' | moment("calendar")}}
// or like this
{{created_at | moment("calendar")}}
Your first problem was you weren't using your compare symbols correctly.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
To answer your other questions; get the condition to work on every cell in the column and what about blanks?
What about blanks?
Add an extra IF
condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())
Condition on every cell in column
You need a terminal multiplexer like either tmux or GNU screen
I'm surprised that a small comment by Ryan Amos' to the original question is the only mention of a solution far preferable to all the others on offer, no matter how clever the python trickery may be and how many upvotes they've received. Further to Ryan's comment, tmux is a nice alternative to GNU screen.
But the principle is the same: if you ever find yourself wanting to leave a terminal job running while you log-out, head to the cafe for a sandwich, pop to the bathroom, go home (etc) and then later, reconnect to your terminal session from anywhere or any computer as though you'd never been away, terminal multiplexers are the answer. Think of them as VNC or remote desktop for terminal sessions. Anything else is a workaround. As a bonus, when the boss and/or partner comes in and you inadvertently ctrl-w / cmd-w your terminal window instead of your browser window with its dodgy content, you won't have lost the last 18 hours-worth of processing!