this is due to again and again creating view ,best option is clear cache before setting adapter
recyclerview.setItemViewCacheSize(your array.size());
There is no trigger to perform code when the app is deleted from the device. Access to the keychain is dependant on the provisioning profile that is used to sign the application. Therefore no other applications would be able to access this information in the keychain.
It does not help with you aim to remove the password in the keychain when the user deletes application from the device but it should give you some comfort that the password is not accessible (only from a re-install of the original application).
using LINQ query expression
IEnumerable<SelectListItem> stores =
from store in database.Stores
where store.CompanyID == curCompany.ID
select new SelectListItem { Value = store.Name, Text = store.ID };
ViewBag.storeSelector = stores;
or using LINQ extension methods with lambda expressions
IEnumerable<SelectListItem> stores = database.Stores
.Where(store => store.CompanyID == curCompany.ID)
.Select(store => new SelectListItem { Value = store.Name, Text = store.ID });
ViewBag.storeSelector = stores;
FormatDateTime(Now, DateFormat.ShortDate)
As others have stated, you can use escape characters. You can use my header in order to make it easier:
#ifndef _COLORS_
#define _COLORS_
/* FOREGROUND */
#define RST "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST
#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST
#endif /* _COLORS_ */
An example using the macros of the header could be:
#include <iostream>
#include "colors.h"
using namespace std;
int main()
{
cout << FBLU("I'm blue.") << endl;
cout << BOLD(FBLU("I'm blue-bold.")) << endl;
return 0;
}
I was taught that for arrays, length is not retrieved through a method due to the following fear: programmers would just assign the length to a local variable before entering a loop (think a for loop where the conditional uses the array's length.) The programmer would supposedly do so to trim down on function calls (and thereby improve performance.) The problem is that the length might change during the loop, and the variable wouldn't.
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
If you want to have your own nice looking wpf MessageBox: Create new Wpf Windows
here is xaml :
<Window x:Class="popup.MessageboxNew"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:popup"
mc:Ignorable="d"
Title="" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity="1"
>
<Window.Resources>
</Window.Resources>
<Border x:Name="MainBorder" Margin="10" CornerRadius="8" BorderThickness="0" BorderBrush="Black" Padding="0" >
<Border.Effect>
<DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="20" ShadowDepth="3" Opacity="0.6" />
</Border.Effect>
<Border.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="ShadowDepth" From="0" To="3" Duration="0:0:1" AutoReverse="False" />
<DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="BlurRadius" From="0" To="20" Duration="0:0:1" AutoReverse="False" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Border.Triggers>
<Grid Loaded="FrameworkElement_OnLoaded">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border Name="Mask" CornerRadius="8" Background="White" />
<Grid x:Name="Grid" Background="White">
<Grid.OpacityMask>
<VisualBrush Visual="{Binding ElementName=Mask}"/>
</Grid.OpacityMask>
<StackPanel Name="StackPanel" >
<TextBox Style="{DynamicResource MaterialDesignTextBox}" Name="TitleBar" IsReadOnly="True" IsHitTestVisible="False" Padding="10" FontFamily="Segui" FontSize="14"
Foreground="Black" FontWeight="Normal"
Background="Yellow" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="Auto" HorizontalContentAlignment="Center" BorderThickness="0"/>
<DockPanel Name="ContentHost" Margin="0,10,0,10" >
<TextBlock Margin="10" Name="Textbar"></TextBlock>
</DockPanel>
<DockPanel Name="ButtonHost" LastChildFill="False" HorizontalAlignment="Center" >
<Button Margin="10" Click="ButtonBase_OnClick" Width="70">Yes</Button>
<Button Name="noBtn" Margin="10" Click="cancel_Click" Width="70">No</Button>
</DockPanel>
</StackPanel>
</Grid>
</Grid>
</Border>
</Window>
for cs of this file :
public partial class MessageboxNew : Window
{
public MessageboxNew()
{
InitializeComponent();
//second time show error solved
if (Application.Current == null) new Application();
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
{
this.MouseDown += delegate { DragMove(); };
}
}
then create a class to use this :
public class Mk_MessageBox
{
public static bool? Show(string title, string text)
{
MessageboxNew msg = new MessageboxNew
{
TitleBar = {Text = title},
Textbar = {Text = text}
};
msg.noBtn.Focus();
return msg.ShowDialog();
}
}
now you can create your message box like this:
var result = Mk_MessageBox.Show("Remove Alert", "This is gonna remove directory from host! Are you sure?");
if (result == true)
{
// whatever
}
copy this to App.xaml inside
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<!-- Accent and AppTheme setting -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
<!--two new guys-->
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.LightBlue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Green.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
-------------------------------
My Refrence : https://www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/
Simple solution that hasn't been mentioned on this question: restart your computer after you declare the path variable.
I always have to restart - the path never updates until I do. And when I do restart, the path always is updated.
Saty described the differences between them. For your practice, you can use datetime
in order to keep the output of NOW()
.
For example:
CREATE TABLE Orders
(
OrderId int NOT NULL,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (OrderId)
)
You can read more at w3schools.
For your reference:
Note: I had no experience on them.
Thanks to Sam Stokes. According to his answer you can solve the problem with different way (I used this way). After updating your develop directory you should reinitialize it
git init
Then you can commit and push updates to master
Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.
Thus:
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
End Function
get-pip.py
.python get-pip.py
, python3 get-pip.py
or python3.6 get-pip.py
, depending on which version of Python you want to install pip
Old answer (still valid)
Try:
python -m ensurepip
It's probably the easiest way to install pip on any system.
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
An alternative approach is to use numpy.resize()
as in:
In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)
# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True
What do you want to do with the text? Is the file small enough to fit into memory? I would try to find the simplest way to handle the file for your needs. The FileUtils library is very handle for this.
for(String line: FileUtils.readLines("my-text-file"))
System.out.println(line);
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'
You can also set the global option:
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
I keep hitting this answer. But none of them list the easiest solution for xsltproc (and probably most XSLT 1.0 processors):
<xsl:stylesheet
version="1.0"
xmlns:str="http://exslt.org/strings"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:value-of select="str:replace(., ' ', '')"/>
For SwiftUI
Think of @EnvironmentObject
as a smarter, simpler way of using @ObservedObject
on lots of views. Rather than creating some data in view A, then passing it to view B, then view C, then view D before finally using it, you can create it in view and put it into the environment so that views B, C, and D will automatically have access to it.
Note: Environment objects must be supplied by an ancestor view – if SwiftUI can’t find an environment object of the correct type you’ll get a crash. This applies for previews too, so be careful.
As an example, here’s an observable object that stores user settings:
class UserSettings: ObservableObject {
@Published var score = 0
}
If you already have yarn 1.x
and you want to upgrade to yarn 2. You need to do something a bit different:
yarn set version berry
Where berry
is the code name for yarn version 2. See this migration guide here for more info.
you just need to go to python console and type->
import nltk
press enter and retype->
nltk.download()
and then a interface will come. Just search for download button and press it. It will install all the required items and will take time. Give the time and just try it again. Your problem will get solved
There is a lot of options to store your data and Android offers you to chose anyone Your data storage options are the following:
Shared Preferences Store private primitive data in key-value pairs. Internal Storage Store private data on the device memory. External Storage Store public data on the shared external storage. SQLite Databases Store structured data in a private database. Network Connection Store data on the web with your own network server
Check here for examples and tuto
Try this:
concat(left(datefield,10),left(timefield,8))
10 char on date field based on full date yyyy-MM-dd
.
8 char on time field based on full time hh:mm:ss
.
It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.
Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.
As @snapshoe says
flush()
sends your SQL statements to the database
commit()
commits the transaction.
When session.autocommit == False
:
commit()
will call flush()
if you set autoflush == True
.
When session.autocommit == True
:
You can't call commit()
if you haven't started a transaction (which you probably haven't since you would probably only use this mode to avoid manually managing transactions).
In this mode, you must call flush()
to save your ORM changes. The flush effectively also commits your data.
If anyone has a problem to import a Bacpac of a DB that uses Azure SQL Sync, Sandrino Di Mattia developed a great simple application to solve this.
I don't believe there is anything builtin to do it. For more than you ever wanted to see on the subject, see Perlmonks on Detecting Numeric
How about creating a template to mimic the behavior of C#.
template<class T> class StaticConstructor
{
bool m_StaticsInitialised = false;
public:
typedef void (*StaticCallback)(void);
StaticConstructor(StaticCallback callback)
{
if (m_StaticsInitialised)
return;
callback();
m_StaticsInitialised = true;
}
}
template<class T> bool StaticConstructor<T>::m_StaticsInitialised;
class Test : public StaticConstructor<Test>
{
static std::vector<char> letters_;
static void _Test()
{
for (char c = 'a'; c <= 'z'; c++)
letters_.push_back(c);
}
public:
Test() : StaticConstructor<Test>(&_Test)
{
// non static stuff
};
};
UPDATE:
Thank you for the quick response. open http://localhost/
opened that domain in my default browser on my Mac.
I ended up writing this alias, did the trick:
# Opens git file's localhost; ${PWD##*/} is the current directory's name
alias lcl='open "http://localhost/${PWD##*/}/"'
Thank you again!
Try withColumn
with the function when
as follows:
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`
val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
.toDF("A", "B", "C")
val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))
newDf.show()
shows
+---+----+---+---+
| A| B| C| D|
+---+----+---+---+
| 4|blah| 2| 1|
| 2| | 3| 0|
| 56| foo| 3| 1|
|100|null| 5| 0|
+---+----+---+---+
I added the (100, null, 5)
row for testing the isNull
case.
I tried this code with Spark 1.6.0
but as commented in the code of when
, it works on the versions after 1.4.0
.
I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join
helper=1
for i in df1.index:
df1.loc[i,'helper']=helper
helper=helper+1
for i in df2.index:
df2.loc[i,'helper']=helper
helper=helper+1
df1.merge(df2,on='helper',how='outer')
I Just came across to a similar to this question solution with included some performance statistics.
It seems that example below is faster:
document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');
_x000D_
InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.
Reference: 1) Performance stats 2) API - insertAdjacentHTML
I hope this will help.
You can implement startForeground
for the service and even if it dies you can restart it by using START_STICKY
on startCommand()
. Not sure though this is the right implementation.
Shouldn't you have:
DELETE FROM tableA WHERE entitynum IN (...your select...)
Now you just have a WHERE with no comparison:
DELETE FROM tableA WHERE (...your select...)
So your final query would look like this;
DELETE FROM tableA WHERE entitynum IN (
SELECT tableA.entitynum FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
)
You might want to look into the DirectoryInfo
.Parent
property.
Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.
Copy-pasted from a recipe written by "Adrián Santalla" on androidcookbook.com: https://www.androidcookbook.com/Recipe.seam?recipeId=3307
1. Create an XML file that represents the button states
Create an xml into drawable called 'button.xml' to name the button states:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="@drawable/button_disabled" />
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/button_pressed" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/button_focused" />
<item
android:state_enabled="true"
android:drawable="@drawable/button_enabled" />
</selector>
2. Create an XML file that represents each button state
Create one xml file for each of the four button states. All of them should be under drawables folder. Let's follow the names set in the button.xml file.
button_enabled.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#00CCFF"
android:centerColor="#0000CC"
android:endColor="#00CCFF"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_focused.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#F7D358"
android:centerColor="#DF7401"
android:endColor="#F7D358"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_pressed.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#0000CC"
android:centerColor="#00CCFF"
android:endColor="#0000CC"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_disabled.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#F2F2F2"
android:centerColor="#A4A4A4"
android:endColor="#F2F2F2"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
3. Create an XML file that represents the button style
Once you have created the files mentioned above, it's time to create your application button style. Now, you need to create a new XML file, called styles.xml (if you don't have it yet) where you can include more custom styles, into de values directory.
This file will contain the new button style of your application. You need to set your new button style features in it. Note that one of those features, the background of your new style, should be set with a reference to the button (button.xml) drawable that was created in the first step. To refer to the new button style we use the name attribute.
The example below show the content of the styles.xml file:
<resources>
<style name="button" parent="@android:style/Widget.Button">
<item name="android:gravity">center_vertical|center_horizontal</item>
<item name="android:textColor">#FFFFFFFF</item>
<item name="android:shadowColor">#FF000000</item>
<item name="android:shadowDx">0</item>
<item name="android:shadowDy">-1</item>
<item name="android:shadowRadius">0.2</item>
<item name="android:textSize">16dip</item>
<item name="android:textStyle">bold</item>
<item name="android:background">@drawable/button</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
</style>
</resources>
4. Create an XML with your own custom application theme
Finally, you need to override the default Android button style. For that, you need to create a new XML file, called themes.xml (if you don't have it yet), into the values directory and override the default Android button style.
The example below show the content of the themes.xml:
<resources>
<style name="YourApplicationTheme" parent="android:style/Theme.NoTitleBar">
<item name="android:buttonStyle">@style/button</item>
</style>
</resources>
Hope you guys can have the same luck as I had with this, when I was looking for custom buttons. Enjoy.
You should try using isinstance()
if isinstance(object, list):
## DO what you want
In your case
if isinstance(tmpDict[key], list):
## DO SOMETHING
To elaborate:
x = [1,2,3]
if type(x) == list():
print "This wont work"
if type(x) == list: ## one of the way to see if it's list
print "this will work"
if type(x) == type(list()):
print "lets see if this works"
if isinstance(x, list): ## most preferred way to check if it's list
print "This should work just fine"
The difference between isinstance()
and type()
though both seems to do the same job is that isinstance()
checks for subclasses in addition, while type()
doesn’t.
0 */2 * * *
The answer is from https://crontab.guru/every-2-hours. It is interesting.
After reading the docs, I have to pass the name of the connection string instead:
var db = new NerdDinners("NerdDinnerDb");
The $(document).ready()
is a jQuery event which occurs when the HTML document has been fully loaded, while the window.onload
event occurs later, when everything including images on the page loaded.
Also window.onload is a pure javascript event in the DOM, while the $(document).ready()
event is a method in jQuery.
$(document).ready()
is usually the wrapper for jQuery to make sure the elements all loaded in to be used in jQuery...
Look at to jQuery source code to understand how it's working:
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
Also I have created the image below as a quick references for both:
If you are working in WordPress and are like me and simply need to check for an empty field (and there are a copious amount of random html entities in what seems like a blank string) then take a look at:
sanitize_title_with_dashes( string $title, string $raw_title = '', string $context = 'display' )
Link to wordpress function page
For people not working on WordPress, I found this function REALLY useful to create my own sanitizer, take a look at the full code and it's really in depth!
Use this PHP script:
$version = apache_get_version();
echo "$version\n";
I'd recommend event.key
currently. MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
event.KeyCode
and event.which
both have nasty deprecated warnings at the top of their MDN pages:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
For alphanumeric keys, event.key
appears to be implemented identically across all browsers. For control keys (tab, enter, escape, etc), event.key
has the same value across Chrome/FF/Safari/Opera but a different value in IE10/11/Edge (IEs apparently use an older version of the spec but match each other as of Jan 14 2018).
For alphanumeric keys a check would look something like:
event.key === 'a'
For control characters you'd need to do something like:
event.key === 'Esc' || event.key === 'Escape'
I used the example here to test on multiple browsers (I had to open in codepen and edit to get it to work with IE10): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code
event.code
is mentioned in a different answer as a possibility, but IE10/11/Edge don't implement it, so it's out if you want IE support.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// ...
Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
I understand that the answer has already been given here. But I still think, some basics about the inversion of control have to be discussed here in length for future readers.
Inversion of Control (IoC) has been built on a very simple principle called Hollywood Principle. And it says that,
Don't call us, we'll call you
What it means is that don't go to the Hollywood to fulfill your dream rather if you are worthy then Hollywood will find you and make your dream comes true. Pretty much inverted, huh?
Now when we discuss about the principle of IoC, we use to forget about the Hollywood. For IoC, there has to be three element, a Hollywood, you and a task like to fulfill your dream.
In our programming world, Hollywood represent a generic framework (may be written by you or someone else), you represent the user code you wrote and the task represent the thing you want to accomplish with your code. Now you don't ever go to trigger your task by yourself, not in IoC! Rather you have designed everything in such that your framework will trigger your task for you. Thus you have built a reusable framework which can make someone a hero or another one a villain. But that framework is always in charge, it knows when to pick someone and that someone only knows what it wants to be.
A real life example would be given here. Suppose, you want to develop a web application. So, you create a framework which will handle all the common things a web application should handle like handling http request, creating application menu, serving pages, managing cookies, triggering events etc.
And then you leave some hooks in your framework where you can put further codes to generate custom menu, pages, cookies or logging some user events etc. On every browser request, your framework will run and executes your custom codes if hooked then serve it back to the browser.
So, the idea is pretty much simple. Rather than creating a user application which will control everything, first you create a reusable framework which will control everything then write your custom codes and hook it to the framework to execute those in time.
Laravel and EJB are examples of such a frameworks.
Reference:
I'm assuming you're using express
, given the logs you have in your question. The key is to set the timeout
property on server (the following sets the timeout to one second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;
If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:
var http = require('http');
var server = http.createServer(function (req, res) {
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}, 200);
}).listen(1337, '127.0.0.1');
server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');
There is a necessary step which is not detailed:
ADB must be running (it is not because it is installed that it will run to establish the connection)
For an unknown reason to open "developer tools" on chrome (canary) will not necessarily launch the run of ADB with good parameters. Then you will not see on the smartphone the question "Confirm remote connection with 'your pc address' " while on PC you can see on the connection panel "pending unknown connection". Then necessarily if this not happens the connection will not be established. Note that some other tools launches ADB but what important is to launch ADB and establish the connection.
When you run ">ADB connect 'IPofYourSmartphone port' " or ADB is run by a soft to get right connection, ADB sends the request which show the panel confirmation on your Smartphone
This is too valid for USB or Wifi connection. If you use on android a tool like "ADB wireless by Henry" you will get a full guide to get a wifi debugging remote connection.
Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:
todos = [do_something] * N
for doit in todos:
doit()
Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.
This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:
If you do not want to change the display format permanently, and perhaps apply a new format later on, I personally favour the use of a resource manager (the with
statement in Python). In your case you could do something like this:
with pd.option_context('display.float_format', '${:0.2f}'.format):
print(df)
If you happen to need a different format further down in your code, you can change it by varying just the format in the snippet above.
Another option is of course to just use vanilla JavaScript:
document.getElementById("a_link").click()
On many devices (such as the iPhone), it prevents the user from using the browser's zoom. If you have a map and the browser does the zooming, then the user will see a big ol' pixelated image with huge pixelated labels. The idea is that the user should use the zooming provided by Google Maps. Not sure about any interaction with your plugin, but that's what it's there for.
More recently, as @ehfeng notes in his answer, Chrome for Android (and perhaps others) have taken advantage of the fact that there's no native browser zooming on pages with a viewport tag set like that. This allows them to get rid of the dreaded 300ms delay on touch events that the browser takes to wait and see if your single touch will end up being a double touch. (Think "single click" and "double click".) However, when this question was originally asked (in 2011), this wasn't true in any mobile browser. It's just added awesomeness that fortuitously arose more recently.
The parent directory of an included file would be
dirname(getcwd())
e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php
then by calling /file/index.php
getcwd() is /var/www/html/folder
__DIR__ is /var/www/html/folder/inc
so dirname(__DIR__) is /var/www/html/folder
but what we want is /var/www/html which is dirname(getcwd())
My two liners... generally Interviewer wanted the below answer.
Hashing is one way . You can not convert your data/ string from a hash code.
Encryption is 2 way - you can decrypt again the encrypted string if you have the key with you.
awk '{ tmp = $1; sub(/^[^ ]+ +/, ""); print $0, tmp }'
It is a very simple and easy way to create an enumerable for your object. The compiler creates a class that wraps your method and that implements, in this case, IEnumerable<object>. Without the yield keyword, you'd have to create an object that implements IEnumerable<object>.
Be careful with that.
But you can use the rebase command
git rebase -i HEAD~2
A vi
will open and all you have to do is delete the line with the commit. Also can read instructions that were shown in proper edition @ vi
. A couple of things can be performed on this mode.
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
There is no way to set all elements in an array as a single operation, UNLESS, that value is the element types default value.
Eg, if it is an array of integers you can set them all to zero with a single operation, like so:
Array.Clear(...)
CountRows = ThisWorkbook.Worksheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
As mentioned in other answers you can use:
>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.
An even faster method is:
>> tic; x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.
For a search routine you should look to use Find
, AutoFilter
or variant array approaches. Range loops are nomally too slow, worse again if they use Select
The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2
which you can then further process
Option Explicit
Const strText As String = "%"
Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
With Application
lAppCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
If Not cel1 Is Nothing Then
Set rng2 = cel1
strFirstAddress = cel1.Address
Do
Set cel1 = rng1.FindNext(cel1)
Set rng2 = Union(rng2, cel1)
Loop While strFirstAddress <> cel1.Address
End If
If Not rng2 Is Nothing Then
For Each cel2 In rng2
Debug.Print cel2.Address & " contained " & strText
Next
Else
MsgBox "No " & strText
End If
With Application
.ScreenUpdating = True
.Calculation = lAppCalc
End With
End Sub
On Bootstrap5
Like noticed in the docu you can use the "data-bs-parent=.." attribute
If parent is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior - this is dependent on the card class). The attribute has to be set on the target collapsible area.
Express 3.x no longer support partial. According to the post ejs 'partial is not defined', you can use "include" keyword in EJS to replace the removed partial functionality.
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
Just set the background of the canvas to transparent.
#canvasID{
background:transparent;
}
You can use:
Usage:
string txt = " i am a string ";
char[] charsToTrim = { ' ' };
txt = txt.Trim(charsToTrim)); // txt = "i am a string"
EDIT:
txt = txt.Replace(" ", ""); // txt = "iamastring"
As already mentioned in other answers, use BufferedInputStreams.
After that, I guess the buffer size does not really matter. Either the program is I/O bound, and growing buffer size over BIS default, will not make any big impact on performance.
Or the program is CPU bound inside the MessageDigest.update(), and majority of the time is not spent in the application code, so tweaking it will not help.
(Hmm... with multiple cores, threads might help.)
As an addition to the Gerold Broser's answer, here an example of mocking a static method with arguments:
class Buddy {
static String addHello(String name) {
return "Hello " + name;
}
}
...
@Test
void testMockStaticMethods() {
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(() -> Buddy.addHello("John")).thenReturn("Guten Tag John");
assertThat(Buddy.addHello("John")).isEqualTo("Guten Tag John");
}
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
}
try {
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
while (namingEnum.hasMore ()) {
SearchResult result = (SearchResult) namingEnum.next ();
Attributes attrs = result.getAttributes ();
System.out.println(attrs.get("cn"));
}
namingEnum.close();
} catch (Exception e) {
e.printStackTrace();
}
private SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
//String[] attrIDs = {"objectGUID"};
//searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
Here's my take on Carpetsmoker's answer (which I liked due to it being dynamic), cleaned up and updated for select2 v4:
$('#selectField').on('select2:open', function (e) {
var container = $(this).select('select2-container');
var position = container.offset().top;
var availableHeight = $(window).height() - position - container.outerHeight();
var bottomPadding = 50; // Set as needed
$('ul.select2-results__options').css('max-height', (availableHeight - bottomPadding) + 'px');
});
I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :
String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String
this method :
str.getClass().getSimpleName();
value:String
now example:
Object o = 1;
o.getClass().getSimpleName();
value:Integer
Here is my workaround,
In your example you can add a third element
with "same styles" of .one & .two elements, but without the absolute position and with hidden visibility:
HTML
<article>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</article>
CSS
.three{
height: 30px;
z-index: -1;
visibility: hidden;
}
This feature was added in Compose 1.6.
Reference: https://docs.docker.com/compose/compose-file/#args
services:
web:
build:
context: .
args:
FOO: foo
It's usually based on significant figures of both the exponent and significand in base 2, not base 10. From what I can tell in the C99 standard, however, there is no specified precision for floats and doubles (other than the fact that 1 and 1 + 1E-5
/ 1 + 1E-7
are distinguishable [float
and double
repsectively]). However, the number of significant figures is left to the implementer (as well as which base they use internally, so in other words, an implementation could decide to make it based on 18 digits of precision in base 3). [1]
If you need to know these values, the constants FLT_RADIX
and FLT_MANT_DIG
(and DBL_MANT_DIG
/ LDBL_MANT_DIG
) are defined in float.h.
The reason it's called a double
is because the number of bytes used to store it is double the number of a float (but this includes both the exponent and significand). The IEEE 754 standard (used by most compilers) allocate relatively more bits for the significand than the exponent (23 to 9 for float
vs. 52 to 12 for double
), which is why the precision is more than doubled.
1: Section 5.2.4.2.2 ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf )
Here is one solution :
public static boolean containsAny(String str, String[] words)
{
boolean bResult=false; // will be set, if any of the words are found
//String[] words = {"word1", "word2", "word3", "word4", "word5"};
List<String> list = Arrays.asList(words);
for (String word: list ) {
boolean bFound = str.contains(word);
if (bFound) {bResult=bFound; break;}
}
return bResult;
}
Here in this snippet, we will see a volley method, add below dependency in-app level gradle file
Dummy URL -> https://jsonplaceholder.typicode.com/users (HTTP GET Method Request)
public void getdata(){
Response.Listener<String> response_listener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Response",response);
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0).getJSONObject("address").getJSONObject("geo");
Log.e("lat",jsonObject.getString("lat");
Log.e("lng",jsonObject.getString("lng");
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener response_error_listener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//TODO
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
}
};
StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://jsonplaceholder.typicode.com/users",response_listener,response_error_listener);
getRequestQueue().add(stringRequest);
}
public RequestQueue getRequestQueue() {
//requestQueue is used to stack your request and handles your cache.
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
Visit https://github.com/JainaTrivedi/AndroidSnippet-/blob/master/Snippets/VolleyActivity.java
Here's a function I wrote for another answer: Javascript Image Url Verify. I don't know if it's exactly what you need, but it uses the various techniques that you would use which include handlers for onload
, onerror
, onabort
and a general timeout.
Because image loading is asynchronous, you call this function with your image and then it calls your callback sometime later with the result.
rising_edge is defined as:
FUNCTION rising_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
RETURN (s'EVENT AND (To_X01(s) = '1') AND
(To_X01(s'LAST_VALUE) = '0'));
END;
FUNCTION To_X01 ( s : std_ulogic ) RETURN X01 IS
BEGIN
RETURN (cvt_to_x01(s));
END;
CONSTANT cvt_to_x01 : logic_x01_table := (
'X', -- 'U'
'X', -- 'X'
'0', -- '0'
'1', -- '1'
'X', -- 'Z'
'X', -- 'W'
'0', -- 'L'
'1', -- 'H'
'X' -- '-'
);
If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.
Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk)
to be more descriptive than the (clk'event and clk = '1')
variant.
PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp://
for protocol, e.g.
file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');
or - when also using the ssh2 extension
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
See http://php.net/manual/en/wrappers.ssh2.php
On a side note, there is also quite a bunch of questions about this topic already:
Use CSS:
<input type="text" class="bigText" name=" item" align="left" />
.bigText {
height:30px;
}
Dreamweaver is a poor testing tool. It is not a browser.
In my case simply restarting the WiFi router helped.
If you want to ignore seconds for example you can use
func isDate(Date, equalTo: Date, toUnitGranularity: NSCalendar.Unit) -> Bool
Example compare if it's the same day:
Calendar.current.isDate(date1, equalTo: date2, toGranularity: .day)
I think killing the process which is uses that port is more easy to handle than changing the ports in config files. Here is how to do it in Windows. You can follow same procedure to Linux but different commands. Run command prompt as Administrator. Then type below command to find out all of processes using the port.
netstat -ano
There will be plenty of processes using various ports. So to get only port we need use findstr
like below (here I use port 80)
netstat -ano | findstr 80
this will gave you result like this
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 7964
Last number is the process ID of the process. so what we have to do is kill the process using PID we can use taskkill
command for that.
taskkill /PID 7964 /F
Run your server again. This time it will be able to run. This can uses for Mysql server too.
Note that there is a very simple solution.
Download the software from http://www.microsoft.com/en-us/download/details.aspx?id=44266 and install it.
Find the installing directory, it is something like "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python"
Change the directory name "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0" to "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC"
Add a new environment variable "VS90COMNTOOLS" and its value is "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC\VC"
Now everything is OK.
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
Then provided your button is showing and the click event is being fired you can call the following in your click event:
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag");
ft.commit();
and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.
ft.addToBackStack(null);
Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.
You can use this way to format your currency needing.
var xx = new Intl.NumberFormat(‘en-US’, {
style: ‘currency’,
currency: ‘USD’,
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
xx.format(123456.789); // ‘$123,456.79’
For more info you can access this link.
https://www.justinmccandless.com/post/formatting-currency-in-javascript/
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:
this.$refs.childMethod()
And from the another child I've called the root method:
this.$root.theRootMethod()
It worked for me.
In JavaScript try:
encodeURIComponent()
and in PHP:
urldecode($_POST['field']);
I know this question is old, but now we can achieve the same result without WRITE_EXTERNAL_STORAGE
permission. Instead of we can use File provider.
private fun storeBitmap(bitmap: Bitmap, file: File){
requireContext().getUriForFile(file)?.run {
requireContext().contentResolver.openOutputStream(this)?.run {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, this)
close()
}
}
}
How to retrieve file from provider ?
fun Context.getUriForFile(file: File): Uri? {
return FileProvider.getUriForFile(
this,
"$packageName.fileprovider",
file
)
}
Also do not forget register your provider
in Android manifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
This means that the first parameter you passed is a boolean (true or false).
The first parameter is $result
, and it is false
because there is a syntax error in the query.
" ... WHERE PartNumber = $partid';"
You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)
You should escape the variable:
" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"
Or better, use Prepared Statements
.
Why not use a media query range.
I'm currently working on a responsive layout for my employer and the ranges I'm using are as follows:
You have your main desktop styles in the body of the CSS file (1024px and above) and then for specific screen sizes I'm using:
@media all and (min-width:960px) and (max-width: 1024px) {
/* put your css styles in here */
}
@media all and (min-width:801px) and (max-width: 959px) {
/* put your css styles in here */
}
@media all and (min-width:769px) and (max-width: 800px) {
/* put your css styles in here */
}
@media all and (min-width:569px) and (max-width: 768px) {
/* put your css styles in here */
}
@media all and (min-width:481px) and (max-width: 568px) {
/* put your css styles in here */
}
@media all and (min-width:321px) and (max-width: 480px) {
/* put your css styles in here */
}
@media all and (min-width:0px) and (max-width: 320px) {
/* put your css styles in here */
}
This will cover pretty much all devices being used - I would concentrate on getting the styling correct for the sizes at the end of the range (i.e. 320, 480, 568, 768, 800, 1024) as for all the others they will just be responsive to the size available.
Also, don't use px anywhere - use em's or %.
Okay, since everyone is ignoring my actual question, heh, I'll post mine too! Here's what I have:
location.querystring = (function() {
// The return is a collection of key/value pairs
var queryStringDictionary = {};
// Gets the query string, starts with '?'
var querystring = unescape(location.search);
// document.location.search is empty if no query string
if (!querystring) {
return {};
}
// Remove the '?' via substring(1)
querystring = querystring.substring(1);
// '&' seperates key/value pairs
var pairs = querystring.split("&");
// Load the key/values of the return collection
for (var i = 0; i < pairs.length; i++) {
var keyValuePair = pairs[i].split("=");
queryStringDictionary[keyValuePair[0]] = keyValuePair[1];
}
// Return the key/value pairs concatenated
queryStringDictionary.toString = function() {
if (queryStringDictionary.length == 0) {
return "";
}
var toString = "?";
for (var key in queryStringDictionary) {
toString += key + "=" + queryStringDictionary[key];
}
return toString;
};
// Return the key/value dictionary
return queryStringDictionary;
})();
And the tests:
alert(window.location.querystring.toString());
for (var key in location.querystring) {
alert(key + "=" + location.querystring[key]);
}
Mind you thought, JavaScript isn't my native tongue.
Anyway, I'm looking for a JavaScript library (e.g. jQuery, Prototype) that already has one written. :)
One more solution is
Rails.application.routes.routes
http://hackingoff.com/blog/generate-rails-sitemap-from-routes/
Use var
instead of int
for your clicks
variable generation and onClick
instead of click
as your function name:
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
In JavaScript variables are declared with the var
keyword. There are no tags like int
, bool
, string
... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.
And the name 'click' is reserved by JavaScript for function names so you have to use something else.
$date = strtotime("+1 day");
echo date('m-d-y',$date);
For anyone having this problem with docker-compose
.
When you have more than one project (i.e. in different folders) with similar services you need to run docker-compose stop
in each of your other projects.
In Ubuntu 18.04, and for php7.0
$ sudo apt-get install php7.0-mcrypt
$ sudo systemctl reload apache2
var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();
From the Bootstrap Docs:
<!--Activate a modal without writing JavaScript. Set data-toggle="modal" on a
controller element, like a button, along with a data-target="#foo" or href="#foo"
to target a specific modal to toggle.-->
<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>
you can write .WorkbookConnection.Delete after .Refresh BackgroundQuery:=False this will delete text file external connection.
i've used the $templateCache to accomplish something similar. i put several ng-templates in a single html file, which i reference using the directive's templateUrl. that ensures the html is available to the template cache. then i can simply select by id to get the ng-template i want.
template.html:
<script type="text/ng-template" id=“foo”>
foo
</script>
<script type="text/ng-template" id=“bar”>
bar
</script>
directive:
myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {
var getTemplate = function(data) {
// use data to determine which template to use
var templateid = 'foo';
var template = $templateCache.get(templateid);
return template;
}
return {
templateUrl: 'views/partials/template.html',
scope: {data: '='},
restrict: 'E',
link: function(scope, element) {
var template = getTemplate(scope.data);
element.html(template);
$compile(element.contents())(scope);
}
};
}]);
An alternative is simply to join the commands together with &&
so that the first one to fail prevents the remainder from executing:
command1 &&
command2 &&
command3
This isn't the syntax you asked for in the question, but it's a common pattern for the use case you describe. In general the commands should be responsible for printing failures so that you don't have to do so manually (maybe with a -q
flag to silence errors when you don't want them). If you have the ability to modify these commands, I'd edit them to yell on failure, rather than wrap them in something else that does so.
Notice also that you don't need to do:
command1
if [ $? -ne 0 ]; then
You can simply say:
if ! command1; then
And when you do need to check return codes use an arithmetic context instead of [ ... -ne
:
ret=$?
# do something
if (( ret != 0 )); then
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
If you're using the command-line tools, running git --version
should give you the version number.
Just install "wheel".
pip install wheel
Yes , Jared and Kelly Orr are right. I use the following code like in edit exception.
foreach (var issue in dinner.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
in stead of
ModelState.AddRuleViolations(dinner.GetRuleViolations());
You may also want to use Rake::FileList
(provided you have rake
dependency):
FileList.new('lib/*') do |file|
p file
end
According to the API:
FileLists are lazy. When given a list of glob patterns for possible files to be included in the file list, instead of searching the file structures to find the files, a FileList holds the pattern for latter use.
Thanks to the magic of new css options this is now possible natively:
a {
text-decoration: underline;
text-decoration-thickness: 5px;
text-decoration-skip-ink: auto;
text-underline-offset: 3px;
}
As of yet support is relatively poor. But it'll land in other browsers than ff eventually.
IIS now has
Idle Time-out Action : Suspend
setting
Suspending is just freezes the process and it is much more efficient than the destroying the process.
I needed to extract a few lines in a log file and this post was helpful in solving my issue, so i thought of adding it here. If someone needs to extract muliple lines, you can use the script to get the index of the a word matching that string (i'm searching for "Root") and extract content in all lines.
$File_content = Get-Content "Path of the text file"
$result = @()
foreach ($val in $File_content){
$Index_No = $val.IndexOf("Root")
$result += $val.substring($Index_No)
}
$result | Select-Object -Unique
Cheers..!
The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.
So, introducing $items as $items = array();
is what you really wanted.
DISTINCT
is always a right choice to get unique values. Also you can do it alternatively without using it. That's GROUP BY
. Which has simply add at the end of the query and followed by the column name.
SELECT * FROM buy GROUP BY date,description
the html:
<a class="xyz">your content</a>
the css:
.xyz{
display: block;
}
This will make the anchor be a block level element like a div.
The simplest way to get a list of methods of any object is to use the help()
command.
%help(object)
It will list out all the available/important methods associated with that object.
For example:
help(str)
Here is my attempt.
List<object> list = new List<object> { new { Id = 10, Name = "Testing1" }, new {Id =2, Name ="Testing2" }};
I came up with this when I wrote something similar for making a Anonymous List for a custom type.
You can do it this way in python3:
print(a,b,end=" ")
I believe this answer is better:
https://unix.stackexchange.com/questions/12593/how-to-remove-all-the-files-in-a-directory
If your top-level directory is called
images
, then runrm -r images/*
. This uses the shell glob operator*
to runrm -r
on every file or directory within images.
basically you go up one level, and then say delete everything inside X directory. This way you are still specifying what folder should have its content deleted, which is safer than just saying 'delete everything here", while preserving the original folder, (which sometimes you want to because you aren't allowed or just don't want to modify the folder's existing permissions)
The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.
I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)
echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service
Output:
1
----------
1
Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.
my rule of thumb is:
rebase
for branches with the same name,merge
otherwise.
examples for same names would be master
, origin/master
and otherRemote/master
.
if develop
exists only in the local repository, and it is always based on a recent origin/master
commit, you should call it master
, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master
branch.
if develop
is shared, it should not be rebased on master
, just merged back into it with --no-ff
. you are developing on develop
. master
and develop
have different names, because we want them to be different things, and stay separate. do not make them same with rebase
.
$.ajax({
type: 'POST',
url: 'data.asmx/getText',
data: {'argInput' : 'input arg(s)'},
complete: function(xData, status) {
$('#txt').html($(xData.responseXML).text()); // result
}
});
The python-espeak package is available in Debian, Ubuntu, Redhat, and other Linux distributions. It has recent updates, and works fine.
from espeak import espeak
espeak.synth("Hello world.")
Jonathan Leaders notes that it also works on Windows, and you can install the mbrola voices as well. See the espeak website at http://espeak.sourceforge.net
You can extract the different parts out quite neatly using a regex pattern:
In [11]: df.row.str.extract('(?P<fips>\d{5})((?P<state>[A-Z ]*$)|(?P<county>.*?), (?P<state_code>[A-Z]{2}$))')
Out[11]:
fips 1 state county state_code
0 00000 UNITED STATES UNITED STATES NaN NaN
1 01000 ALABAMA ALABAMA NaN NaN
2 01001 Autauga County, AL NaN Autauga County AL
3 01003 Baldwin County, AL NaN Baldwin County AL
4 01005 Barbour County, AL NaN Barbour County AL
[5 rows x 5 columns]
To explain the somewhat long regex:
(?P<fips>\d{5})
\d
) and names them "fips"
.The next part:
((?P<state>[A-Z ]*$)|(?P<county>.*?), (?P<state_code>[A-Z]{2}$))
Does either (|
) one of two things:
(?P<state>[A-Z ]*$)
*
) of capital letters or spaces ([A-Z ]
) and names this "state"
before the end of the string ($
),or
(?P<county>.*?), (?P<state_code>[A-Z]{2}$))
.*
) thenstate_code
before the end of the string ($
).In the example:
Note that the first two rows hit the "state" (leaving NaN in the county and state_code columns), whilst the last three hit the county, state_code (leaving NaN in the state column).
If you want to find the last populated cell in a particular column, the best method is:
Range("A" & Rows.Count).End(xlUp).Row
This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.
(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});
I tried $('#'+id).off().on(...)
, but it wouldn't work to reset the onClick attribute every time it was called to be reset.
I use .on('click',function(){...});
to stay away from having to quote block all my javascript functions.
The O.P. could now use:
$(this).removeAttr('onclick').off('click').on('click', function(){
displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this);
});
Where this came through for me is when my div was set with the onClick attribute set statically:
<div onclick = '...'>
Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});
.
Without the off('click') my onClick listeners were being appended not replaced.
This may be fairly obvious, but it tripped me up just now:
If you are taking a tail-log backup, this issue can also be caused by having this option checked in the SSMS Restore wizard - "Leave source database in the restoring state (WITH NORECOVERY)"
List.stream().mapToDouble(a->a).average()
The problem id because of inp.read();
method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.
What you can do simply
for(int i=0;i<T;i++) {
String s= inp.readLine();
String[] intValues = inp.readLine().split(" ");
int[] m= new int[2];
m[0]=Integer.parseInt(intValues[0]);
m[1]=Integer.parseInt(intValues[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
}
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
A very simple solution is to add the database name with your table name like if your DB name is DBMS
and table is info
then it will be DBMS.info
for any query.
If your query is
select * from STUDENTREC where ROLL_NO=1;
it might show an error but
select * from DBMS.STUDENTREC where ROLL_NO=1;
it doesn't because now actually your table is found.
When you go to a stream url, you get offered a file. feed this file to a parser to extract the contents out of it. the file is (usually) plain text and contains the url to play.
This simply means that either tree
, tree[otu]
, or tree[otu][0]
evaluates to None
, and as such is not subscriptable. Most likely tree[otu]
or tree[otu][0]
. Track it down with some simple debugging like this:
def Ancestors (otu,tree):
try:
tree[otu][0][0]
except TypeError:
print otu, tre[otu]
raise
#etc...
or pdb
I've found a couple other ways you can write these which are a bit more readable IMHO.
- name: check out a git repository
local_action:
module: git
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
OR
- name: check out a git repository
local_action: git
args:
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
As Ayman farhat mentioned you can use the simple method len(matrix) to get the length of rows and get the length of the first row to get the no. of columns using len(matrix[0]) :
>>> a=[[1,5,6,8],[1,2,5,9],[7,5,6,2]]
>>> len(a)
3
>>> len(a[0])
4
Also you can use a library that helps you with matrices "numpy":
>>> import numpy
>>> numpy.shape(a)
(3,4)
I changed scrollable div to be with absolute position, and everything works for me
div.sidebar {
overflow: hidden;
background-color: green;
padding: 5px;
position: fixed;
right: 20px;
width: 40%;
top: 30px;
padding: 20px;
bottom: 30%;
}
div#fixed {
background: #76a7dc;
color: #fff;
height: 30px;
}
div#scrollable {
overflow-y: scroll;
background: lightblue;
position: absolute;
top:55px;
left:20px;
right:20px;
bottom:10px;
}
function EnableHyperLink(id) {
$('#' + id).attr('onclick', 'Pagination("' + id + '")');//onclick event which u
$('#' + id).addClass('enable-link');
$('#' + id).removeClass('disable-link');
}
function DisableHyperLink(id) {
$('#' + id).addClass('disable-link');
$('#' + id).removeClass('enable-link');
$('#' + id).removeAttr('onclick');
}
.disable-link
{
text-decoration: none !important;
color: black !important;
cursor: default;
}
.enable-link
{
text-decoration: underline !important;
color: #075798 !important;
cursor: pointer !important;
}
$?
is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep
command succeeded.
The grep
manpage states:
The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)
So in this case it's checking whether any ERROR lines were found.
If you want to use straight PowerShell check out the below code.
$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
Write-Host $line
}
Android Studio is based on IntelliJ, and it comes with support for SVN (along with git and mercurial) bundled in. Check http://www.jetbrains.com/idea/features/version_control.html for more info.
Using $emit and $broadcast, (as mentioned by walv in the comments above)
To fire an event upwards (from child to parent)
$scope.$emit('myTestEvent', 'Data to send');
To fire an event downwards (from parent to child)
$scope.$broadcast('myTestEvent', {
someProp: 'Sending you some data'
});
and finally to listen
$scope.$on('myTestEvent', function (event, data) {
console.log(data);
});
For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
Enjoy :)
<html>
<head>
<title>Row Click</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function test(){
alert('test');
}
$(document).ready(function(){
var row='<tr onclick="test()"><td >Value 4</td><td>Value 5</td><td>Value 6</td></tr>';
$("#myTable").append(row);
});
</script>
</head>
<table id="myTable" >
<th>Column 1</th><th>Column 2</th><th>Column 3</th>
<tr onclick="test()">
<td >Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
</tr>
</table>
</html>
If you don't need to use the information in the selected cell then clearing selection works but if you need to still use the information in the selected cell you can do this to make it appear there is no selection and the back color will still be visible.
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView.SelectedRows)
{
dataGridView.RowsDefaultCellStyle.SelectionBackColor = row.DefaultCellStyle.BackColor;
}
}
There is no direct string compare function in SQL Server
CASE
WHEN str1 = str2 THEN 0
WHEN str1 < str2 THEN -1
WHEN str1 > str2 THEN 1
ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END
Notes
Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."
With that in mind, then the function given in the second link you posted should do exactly what you need:
function mres($value)
{
$search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
$replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
return str_replace($search, $replace, $value);
}
You can use HttpEntity to read both Body and Headers.
@RequestMapping(value = "/restURL")
public String serveRest(HttpEntity<String> httpEntity){
MultiValueMap<String, String> headers =
httpEntity.getHeaders();
Iterator<Map.Entry<String, List<String>>> s =
headers.entrySet().iterator();
while(s.hasNext()) {
Map.Entry<String, List<String>> obj = s.next();
String key = obj.getKey();
List<String> value = obj.getValue();
}
String body = httpEntity.getBody();
}
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent)
which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent)
-- Used to launch a new activity.
So suppose you have two Activity class and on a button click's OnClickListener()
you wanna move from one Activity to another then --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move (It may contain anything like you are saying dialog box).
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
This exmple is related to button click you can use the code anywhere which is written inside button click's OnClickListener()
at any place where you want to switch between your activities.
Here's a picture explaining the difference between pageY
and clientY
.
Same for pageX
and clientX
, respectively.
pageX/Y
coordinates are relative to the top left corner of the whole rendered page (including parts hidden by scrolling),
while clientX/Y
coordinates are relative to the top left corner of the visible part of the page, "seen" through browser window.
You'll probably never need screenX/Y
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
Here is an interesting blog entry about numbers / limitations of Excel 2007. According to the author the new limit is approximately one million rows.
Sounds like you have a pre-Excel 2007 workbook open in Excel 2007 in compatibility mode (look in the title bar and see if it says compatibility mode). If so, the workbook has 65,536 rows, not 1,048,576. You can save the workbook as an Excel workbook which will be in Excel 2007 format, close the workbook and re-open it.
The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'
That statement is false. That's just how Enterprise Manager or SQL Server chooses to show the date. Internally it's a 8-byte binary value, which is why some of the functions posted by Andrew will work so well.
Kibbee makes a valid point as well, and in a perfect world I would agree with him. However, sometimes you want to bind query results directly to display control or widgets and there's really not a chance to do any formatting. And sometimes the presentation layer lives on a web server that's even busier than the database. With those in mind, it's not necessarily a bad thing to know how to do this in SQL.
'
) and double quotes ("
) with hex and octal charsIf using something like echo
, I've had some really complicated and really weird and hard-to-escape (think: very nested) cases where the only thing I could get to work was using octal or hex codes!
Here are some examples:
'
is escaped with hex \x27
or octal \047
(its corresponding ASCII code):# 1. hex
$ echo -e "Let\x27s get coding!"
Let's get coding!
# 2. octal
$ echo -e "Let\047s get coding!"
Let's get coding!
"
is escaped with hex \x22
or octal \042
(its corresponding ASCII code).Note: bash
is nuts! Sometimes even the !
char has special meaning, and must either be removed from within the double quotes and then escaped "like this"\!
or put entirely within single quotes 'like this!'
, rather than within double quotes.
# 1. hex; escape `!` by removing it from within the double quotes
# and escaping it with `\!`
$ echo -e "She said, \x22Let\x27s get coding"\!"\x22"
She said, "Let's get coding!"
# OR put it all within single quotes:
$ echo -e 'She said, \x22Let\x27s get coding!\x22'
She said, "Let's get coding!"
# 2. octal; escape `!` by removing it from within the double quotes
$ echo -e "She said, \042Let\047s get coding"\!"\042"
She said, "Let's get coding!"
# OR put it all within single quotes:
$ echo -e 'She said, \042Let\047s get coding!\042'
She said, "Let's get coding!"
# 3. mixed hex and octal, just for fun
# escape `!` by removing it from within the double quotes when it is followed by
# another escape sequence
$ echo -e "She said, \x22Let\047s get coding! It\x27s waaay past time to begin"\!"\042"
She said, "Let's get coding! It's waaay past time to begin!"
# OR put it all within single quotes:
$ echo -e 'She said, \x22Let\047s get coding! It\x27s waaay past time to begin!\042'
She said, "Let's get coding! It's waaay past time to begin!"
Note that if you don't properly escape !
, when needed, as I've shown two ways to do above, you'll get some weird errors, like this:
$ echo -e "She said, \x22Let\047s get coding! It\x27s waaay past time to begin!\042"
bash: !\042: event not found
OR:
$ echo -e "She said, \x22Let\x27s get coding!\x22"
bash: !\x22: event not found
One simple but elegant way is to create a config.php
file (or whatever you call it) that just returns an array:
<?php
return array(
'host' => 'localhost',
'username' => 'root',
);
And then:
$configs = include('config.php');
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
Since C++11 you could use std::put_time
from iomanip
header:
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}
std::put_time
is a stream manipulator, therefore it could be used together with std::ostringstream
in order to convert the date to a string:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
auto str = oss.str();
std::cout << str << std::endl;
}
#include <math.h>
printf ("%d", (int) pow (3, 4));
$(info your_text)
: Information. This doesn't stop the execution.
$(warning your_text)
: Warning. This shows the text as a warning.
$(error your_text)
: Fatal Error. This will stop the execution.
This code checks to make sure the app is installed, but also checks to make sure it's enabled.
private boolean isAppInstalled(String packageName) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
return pm.getApplicationInfo(packageName, 0).enabled;
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
If you want to change the table default character set
and all character columns to a new character set, use a statement like this:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;
So query will be:
ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;
I had the exact same problem, found that I was missing
<mdb>
<resource-adapter-ref resource-adapter-name="hornetq-ra"/>
<bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>
</mdb>
under
<subsystem xmlns="urn:jboss:domain:ejb3:1.2">
in standalone/configuration/standalone.xml
Tested in Kafka 0.8.2, for the quick-start example: First, Add one line to server.properties file under config folder:
delete.topic.enable=true
then, you can run this command:
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test
include script manager
code behind function
ScriptManager.RegisterStartupScript(this, this.GetType(), "HideConfirmBox", "javascript:HideAAConfirmBox(); ", true);
You can declare the array in C++ in these type of ways.
If you know the array size then you should declare the array for:
integer: int myArray[array_size];
Double: double myArray[array_size];
Char and string : char myStringArray[array_size];
The difference between char and string is as follows
char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";
If you don't know the size of array then you should leave the array blank like following.
integer: int myArray[array_size];
Double: double myArray[array_size];
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
SimpleConfigFile is a library that does exactly what you require and it is very simple to use.
# File file.cfg
url = http://example.com
file = main.exe
true = 0
The following program reads the previous configuration file:
#include<iostream>
#include<string>
#include<vector>
#include "config_file.h"
int main(void)
{
// Variables that we want to read from the config file
std::string url, file;
bool true_false;
// Names for the variables in the config file. They can be different from the actual variable names.
std::vector<std::string> ln = {"url","file","true"};
// Open the config file for reading
std::ifstream f_in("file.cfg");
CFG::ReadFile(f_in, ln, url, file, true_false);
f_in.close();
std::cout << "url: " << url << std::endl;
std::cout << "file: " << file << std::endl;
std::cout << "true: " << true_false << std::endl;
return 0;
}
The function CFG::ReadFile
uses variadic templates. This way, you can pass the variables you want to read and the corresponding type is used for reading the data in the appropriate way.
I think you want this:
Dim filename As String
filename = Application.GetOpenFilename
Dim cell As Range
cell = Application.Range("A1")
cell.Value = filename
finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * theCell = (UITableViewCell *)[tableView
cellForRowAtIndexPath:indexPath];
CGPoint tableViewCenter = [tableView contentOffset];
tableViewCenter.y += myTable.frame.size.height/2;
[tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
[tableView reloadData];
}
Here's a solution I used (it needs #include <time.h>
):
int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();
do {
/*
* Do something to busy the CPU just here while you drink a coffee
* Be sure this code will not take more than `trigger` ms
*/
clock_t difference = clock() - before;
msec = difference * 1000 / CLOCKS_PER_SEC;
iterations++;
} while ( msec < trigger );
printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
msec/1000, msec%1000, iterations);
Based on the comments above, here is a simple test:
isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
isset() { [ -z "$(isunset "$1")" ] && echo 1; }
Example:
$ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's unset
$ foo= ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
$ foo=bar ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
On my machine the Nuget dependency wasn't downloaded correctly, the lib folder inside the nuget package didn't exist, hence the error.
Before
I renamed the Nuget Package in the packages folder and Nuget redownloaded it correctly with the necessary lib folder.
EDIT: Consider looking at and upvoting Malvineous's answer on this page. Netmasks are a much more elegant solution.
Simply use a percent sign as a wildcard in the IP address.
From http://dev.mysql.com/doc/refman/5.1/en/grant.html
You can specify wildcards in the host name. For example,
user_name@'%.example.com'
applies touser_name
for any host in theexample.com
domain, anduser_name@'192.168.1.%'
applies touser_name
for any host in the192.168.1
class C subnet.
Maybe the following helps you.
arraylistname.get(position);
When I have a python script running on a linux terminal, CTRL + \ works. (not CRTL + C or D)
No Tracking LINQ to Entities queries
Usage of AsNoTracking() is recommended when your query is meant for read operations. In these scenarios, you get back your entities but they are not tracked by your context.This ensures minimal memory usage and optimal performance
Pros
- Improved performance over regular LINQ queries.
- Fully materialized objects.
- Simplest to write with syntax built into the programming language.
Cons
- Not suitable for CUD operations.
- Certain technical restrictions, such as: Patterns using DefaultIfEmpty for OUTER JOIN queries result in more complex queries than simple OUTER JOIN statements in Entity SQL.
- You still can’t use LIKE with general pattern matching.
More info available here:
You don't have any example code but I assume you want to do something like this?
@View({
directives: [NgClass],
styles: [`
.${TodoModel.COMPLETED} {
text-decoration: line-through;
}
.${TodoModel.STARTED} {
color: green;
}
`],
template: `<div>
<span [ng-class]="todo.status" >{{todo.title}}</span>
<button (click)="todo.toggle()" >Toggle status</button>
</div>`
})
You assign ng-class
to a variable which is dynamic (a property of a model called TodoModel
as you can guess).
todo.toggle()
is changing the value of todo.status
and there for the class of the input is changing.
This is an example for class name but actually you could do the same think for css properties.
I hope this is what you meant.
This example is taken for the great egghead tutorial here.
If you use the new Xcode4 Workspaces, you can change the Derived Data Location under File -> Workspace settings...
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
I think this should be a simple example:
$('#item1 span').text();
or
$('#item1 span').html();
My preference is to multiline the args, this is simplest and easiest to read. Also, the script can be changed without affecting the image, just need to restart the pod. For example, for a mysql dump, the container spec could be something like this:
containers:
- name: mysqldump
image: mysql
command: ["/bin/sh", "-c"]
args:
- echo starting;
ls -la /backups;
mysqldump --host=... -r /backups/file.sql db_name;
ls -la /backups;
echo done;
volumeMounts:
- ...
The reason this works is that yaml actually concatenates all the lines after the "-" into one, and sh runs one long string "echo starting; ls... ; echo done;".
You can put that method call inside the render function. Or inside the life cycle method, componentDidUpdate
Here is a list of what can be pickled. In particular, functions are only picklable if they are defined at the top-level of a module.
This piece of code:
import multiprocessing as mp
class Foo():
@staticmethod
def work(self):
pass
if __name__ == '__main__':
pool = mp.Pool()
foo = Foo()
pool.apply_async(foo.work)
pool.close()
pool.join()
yields an error almost identical to the one you posted:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 505, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 315, in _handle_tasks
put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
The problem is that the pool
methods all use a mp.SimpleQueue
to pass tasks to the worker processes. Everything that goes through the mp.SimpleQueue
must be pickable, and foo.work
is not picklable since it is not defined at the top level of the module.
It can be fixed by defining a function at the top level, which calls foo.work()
:
def work(foo):
foo.work()
pool.apply_async(work,args=(foo,))
Notice that foo
is pickable, since Foo
is defined at the top level and foo.__dict__
is picklable.
Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile
Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);
If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:
<a href="viewpdf.aspx" target="_blank">View PDF</a>
You're thinking too complicated. It's actually just $('#'+openaddress)
.
SET session_replication_role = replica;
also dosent work for me in Postgres 9.1. i use the two function described by bartolo-otrit with some modification. I modified the first function to make it work for me because the namespace or the schema must be present to identify the table correctly. The new code is :
CREATE OR REPLACE FUNCTION disable_triggers(a boolean, nsp character varying)
RETURNS void AS
$BODY$
declare
act character varying;
r record;
begin
if(a is true) then
act = 'disable';
else
act = 'enable';
end if;
for r in select c.relname from pg_namespace n
join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
where n.nspname = nsp
loop
execute format('alter table %I.%I %s trigger all', nsp,r.relname, act);
end loop;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION disable_triggers(boolean, character varying)
OWNER TO postgres;
then i simply do a select query for every schema :
SELECT disable_triggers(true,'public');
SELECT disable_triggers(true,'Adempiere');
CAUTION: commit any work you wish to retain first.
You may reset your workspace (and recover the deleted files)
git checkout ./*
"nevets1219" is right about Google docs, however if you simply "import" the file it often does not convert it to UTF-8.
But if you import the CSV into an existing Google spreadsheet it does convert to UTF-8.
Here's a recipe:
The resulting file will be in UTF-8
Here is the simple arraylist example for insertion at specific index
ArrayList<Integer> str=new ArrayList<Integer>();
str.add(0);
str.add(1);
str.add(2);
str.add(3);
//Result = [0, 1, 2, 3]
str.add(1, 11);
str.add(2, 12);
//Result = [0, 11, 12, 1, 2, 3]
def solve(s):
names = list(s.split(" "))
return " ".join([i.capitalize() for i in names])
Takes a input like your name: john doe
Returns the first letter capitalized.(if first character is a number, then no capitalization occurs)
works for any name length
I saw this somewhere else. I am using 2016 Excel. What worked for me was to use YYYY Quarters (I was looking for quarterly data). So, I had the source data sorted as YYYY xQ. 2016 1Q, 2016 2Q, 2016 3Q, 2016, 4Q, 2017 1Q, 2017 2Q... You get the idea.
Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.
Just do
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('id').value='1988-01-01'");
Use:
function sortArguments() {
return arguments.length === 1 ? [arguments[0]] :
Array.apply(null, arguments).sort();
}
Array(arg1, arg2, ...)
returns [arg1, arg2, ...]
Array(str1)
returns [str1]
Array(num1)
returns an array that has num1
elements
You must check number of arguments!
Array.slice
version (slower):
function sortArguments() {
return Array.prototype.slice.call(arguments).sort();
}
Array.push
version (slower, faster than slice):
function sortArguments() {
var args = [];
Array.prototype.push.apply(args, arguments);
return args.sort();
}
Move version (slower, but small size is faster):
function sortArguments() {
var args = [];
for (var i = 0; i < arguments.length; ++i)
args[i] = arguments[i];
return args.sort();
}
Array.concat
version (slowest):
function sortArguments() {
return Array.prototype.concat.apply([], arguments).sort();
}
Given an array you can use the Array.ConvertAll
method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray
call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
If you are looking for sending color data from backend
def color():
color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
return color
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
Plenty of info available here
Here is a good summary:
A Stored Procedure:
A View: