Actually, it is possible without C# code. The key is to use interactions:
<Button Content="Close">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
In order for this to work, just set the x:Name
of your window to "window", and add these two namespaces:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions
.
In case you don't have Blend, the SDK can be downloaded here.
You want the --stat
option of git diff
, or if you're looking to parse this in a script, the --numstat
option.
git diff --stat <commit-ish> <commit-ish>
--stat
produces the human-readable output you're used to seeing after merges; --numstat
produces a nice table layout that scripts can easily interpret.
I somehow missed that you were looking to do this on multiple commits at the same time - that's a task for git log
. Ron DeVera touches on this, but you can actually do a lot more than what he mentions. Since git log
internally calls the diff machinery in order to print requested information, you can give it any of the diff stat options - not just --shortstat
. What you likely want to use is:
git log --author="Your name" --stat <commit1>..<commit2>
but you can use --numstat
or --shortstat
as well. git log
can also select commits in a variety other ways - have a look at the documentation. You might be interested in things like --since
(rather than specifying commit ranges, just select commits since last week) and --no-merges
(merge commits don't actually introduce changes), as well as the pretty output options (--pretty=oneline, short, medium, full...
).
Here's a one-liner to get total changes instead of per-commit changes from git log (change the commit selection options as desired - this is commits by you, from commit1 to commit2):
git log --numstat --pretty="%H" --author="Your Name" commit1..commit2 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}'
(you have to let git log print some identifying information about the commit; I arbitrarily chose the hash, then used awk to only pick out the lines with three fields, which are the ones with the stat information)
Try this:
let jsonArr = [
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}
]
let idModified = jsonArr.map(
obj => {
return {
"id" : obj._id,
"email":obj.email,
"image":obj.image,
"name":obj.name
}
}
);
console.log(idModified);
as per @anaximander s answer but your signup action should look more like
[HttpPost]
public ActionResult SignUp(Account account)
{
if(ModelState.IsValid){
//do something with account
return RedirectToAction("Index");
}
return View("SignUp");
}
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
var div2 = document.createElement('div');
div2.className = 'block-2';
iDiv.appendChild(div2);
Node* insert_node_at_nth_pos(Node *head, int data, int position)
{
/* current node */
Node* cur = head;
/* initialize new node to be inserted at given position */
Node* nth = new Node;
nth->data = data;
nth->next = NULL;
if(position == 0){
/* insert new node at head */
head = nth;
head->next = cur;
return head;
}else{
/* traverse list */
int count = 0;
Node* pre = new Node;
while(count != position){
if(count == (position - 1)){
pre = cur;
}
cur = cur->next;
count++;
}
/* insert new node here */
pre->next = nth;
nth->next = cur;
return head;
}
}
I've been struggling with this problem in one form or another for AGES, thank you, Thank You, THANK YOU.... :)
I just wanted to point out that you can get a generalizable solution from what Bob Lee's done by just extending View and overriding onMeasure. That way you can use this with any drawable you want, and it won't break if there's no image:
public class CardImageView extends View {
public CardImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CardImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CardImageView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable bg = getBackground();
if (bg != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * bg.getIntrinsicHeight() / bg.getIntrinsicWidth();
setMeasuredDimension(width,height);
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
I was also running the same problem when I updated to xcode 5 it removed older sdk. But I taken the copy of older SDK from another computer and the same you can download from following link.
http://www.4shared.com/zip/NlPgsxz6/iPhoneOS61sdk.html
(www.4shared.com test account [email protected]/test)
There are 2 ways to work with.
1) Unzip and paste this folder to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs & restart the xcode.
But this might again removed by Xcode if you update xcode.
2) Another way is Unzip and paste where you want and go to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs and create a symbolic link here, so that the SDK will remain same even if you update the Xcode.
Another change I made, Build Setting > Architectures > standard (not 64) so list all the versions of Deployment Target
No need to download the zip if you only wanted to change the deployment target.
Here are some screenshots.
We can also use ReentrantLock to achieve the synchronization for static variables.
public class Test {
private static int count = 0;
private static final ReentrantLock reentrantLock = new ReentrantLock();
public void foo() {
reentrantLock.lock();
count = count + 1;
reentrantLock.unlock();
}
}
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it check only the email
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
what about
$(parentSelect).nextAll().fadeOut(200, function() {
$(this).remove();
}).one(function(){
myfunction();
});
Pattern.compile()
allow to reuse a regex multiple times (it is threadsafe). The performance benefit can be quite significant.
I did a quick benchmark:
@Test
public void recompile() {
var before = Instant.now();
for (int i = 0; i < 1_000_000; i++) {
Pattern.compile("ab").matcher("abcde").matches();
}
System.out.println("recompile " + Duration.between(before, Instant.now()));
}
@Test
public void compileOnce() {
var pattern = Pattern.compile("ab");
var before = Instant.now();
for (int i = 0; i < 1_000_000; i++) {
pattern.matcher("abcde").matches();
}
System.out.println("compile once " + Duration.between(before, Instant.now()));
}
compileOnce was between 3x and 4x faster.
I guess it highly depends on the regex itself but for a regex that is often used, I go for a static Pattern pattern = Pattern.compile(...)
To execute a funtion or code after a delay use the next method
DispatchQueue.main.asyncAfter(deadline: .now() + 'secondsOfDelay') {
your code here...
}
Example - In this example the funtion getShowMovies
will be executed after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.getShowMovies()
}
My regex of choice is:
/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
Valid formats:
(123) 456-7890
(123)456-7890
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725
If you don't need to preserve any of the outputs you already successfully compiled
nmake /A
rebuilds all
Have a look at the following apache commons function:
org.apache.commons.io.FileUtils.readFileToByteArray(File)
All answers are great, and I encourage to use those methods with this one to improve build speed.
After release of android 2.2 on September 2016, Android released experimental build cache feature to speed up gradle
build performance, which is now official from Android Studio 2.3 Canary. (Official Release note)
It introduces a new build cache feature, which is enable by default, can speed up build times (including full builds, incremental builds, and instant run) by storing and reusing files/directories that were created in previous builds of the same or different Android project.
How to use:
Add following line in your gradle.properties
file
android.enableBuildCache = true
# Set to true or false to enable or disable the build cache. If this parameter is not set, the build cache is enable by default.
Clean the cache:
There is a new Gradle task called cleanBuildCache
for you to more easily clean the build cache. You can use it by typing the following in your terminal:
./gradlew cleanBuildCache
OR You can clean the cache for Android studio 2.2 by deleting all the files store at location
C:\Users\<username>\.android\build-cache
If you ever wondered how to do it using the new BDD style of Mockito:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
For something a little different, you could use JRuby and Mocha which are combined in JtestR to write tests for your Java code in expressive and succinct Ruby. There are some useful mocking examples with JtestR here. One advantage of this approach is that mocking concrete classes is very straightforward.
just .idea/
works fine for me
Apple recommends for stylistic purposes.If you write this code:
@property (nonatomic,assign) BOOL working;
Then you can not use [object isWorking].
It will show an error. But if you use below code means
@property (assign,getter=isWorking) BOOL working;
So you can use [object isWorking] .
React is not passing you the kind of events you might think. Rather, it is passing synthetic events.
In a brief test, event.keyCode == 0
is always true. What you want is event.charCode
if you use the number as your password, maybe you should try to change your password using string.
I can login using deltaqin:000000 on the website, but had this while running the program. then change the password to deltaiqn. and it works.
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
Accroding to Thinking in Java by Bruce Eckel, one use case for explicit System.gc() call is when you want to force finalization, i.e. the call to finalize method.
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
I've used the following with jQuery UI Dialog. (Maybe it works with other ajax callbacks?)
$('<div><img src="/i/loading.gif" id="loading" /></div>').load('/ajax.html').dialog({
height: 300,
width: 600,
title: 'Wait for it...'
});
The contains an animated loading gif until its content is replaced when the ajax call completes.
If you were using SQL 2012 or above you could use the CONCAT function:
SELECT CONCAT(field1, field2, field3) FROM table1
NULL fields won't break your concatenation.
@bummi - Thanks for the comment - edited my answer to correspond to it.
Personally I think Thread.Sleep
is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.
Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));
//Note Forms.Timer and Timer() have similar implementations.
public static void DelayAction(int millisecond, Action action)
{
var timer = new DispatcherTimer();
timer.Tick += delegate
{
action.Invoke();
timer.Stop();
};
timer.Interval = TimeSpan.FromMilliseconds(millisecond);
timer.Start();
}
Thats a linker problem.
Try to change Properties -> Linker -> System -> SubSystem (in Visual Studio).
from Windows (/SUBSYSTEM:WINDOWS) to Console (/SUBSYSTEM:CONSOLE)
Without answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The @WithMockUser
annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
String message = messageService.getMessage();
...
}
There is also the option to use @WithUserDetails
to emulate a UserDetails
returned from the UserDetailsService
, e.g.
@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
String message = messageService.getMessage();
...
}
More details can be found in the @WithMockUser and the @WithUserDetails chapters in the Spring Security reference docs (from which the above examples were copied)
Python Static methods can be created in two ways.
Using staticmethod()
class Arithmetic:
def add(x, y):
return x + y
# create add static method
Arithmetic.add = staticmethod(Arithmetic.add)
print('Result:', Arithmetic.add(15, 10))
Output:
Result: 25
Using @staticmethod
class Arithmetic:
# create add static method
@staticmethod
def add(x, y):
return x + y
print('Result:', Arithmetic.add(15, 10))
Output:
Result: 25
\i /path/to/yourfile.sql
It's simple. On the sender side, use Intent.putExtra
:
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
On the receiver side, use Intent.getIntExtra
:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Use this code:
public class LinkTest
{
public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.navigate().to("file:///C:/Users/vkiran/Desktop/xyz.html");
List<WebElement> alllinks =driver.findElements(By.xpath("//*[@id='sliding-navigation']//a"));
String a[]=new String[alllinks.size()];
for(int i=0;i<alllinks.size();i++)
{
a[i]=alllinks.get(i).getText();
if(a[i].startsWith("B"))
{
System.out.println("clicking on this link::"+driver.findElement(By.linkText(a[i])).getText());
driver.findElement(By.linkText(a[i])).click();
}
else
{
System.out.println("does not starts with B so not clicking");
}
}
}
}
np.count_nonzero(~np.isnan(data))
~
inverts the boolean matrix returned from np.isnan
.
np.count_nonzero
counts values that is not 0\false. .sum
should give the same result. But maybe more clearly to use count_nonzero
Testing speed:
In [23]: data = np.random.random((10000,10000))
In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan
In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop
In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop
In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop
data.size - np.count_nonzero(np.isnan(data))
seems to barely be the fastest here. other data might give different relative speed results.
To make each of the columns autosize you can set Width="Auto" on the GridViewColumn.
To right-align the text in the ID column you can create a cell template using a TextBlock and set the TextAlignment. Then set the ListViewItem.HorizontalContentAlignment (using a style with a setter on the ListViewItem) to make the cell template fill the entire GridViewCell.
Maybe there is a simpler solution, but this should work.
Note: the solution requires both HorizontalContentAlignment=Stretch in Window.Resources and TextAlignment=Right in the CellTemplate.
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</Window.Resources>
<Grid>
<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="40">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Id}" TextAlignment="Right" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
You can use Collections.list()
to convert an Enumeration
to a List
in one line:
List<T> list = Collections.list(enumeration);
There's no similar method to get a Set
, however you can still do it one line:
Set<T> set = new HashSet<T>(Collections.list(enumeration));
The above voted answers are dangerous for the health of your database. You can still make your database available just for reading and not for writing:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if false;
}
}
}
You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.
This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.
<Window.Resources>
<local:WidthConverter x:Key="widthConverter"/>
</Window.Resources>
<Grid>
<Grid>
<StackPanel VerticalAlignment="Center" Orientation="Vertical" >
<Viewbox Margin="100,0,100,0">
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
</Viewbox>
<TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
</StackPanel>
</Grid>
</Grid>
Converter
[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value*.7;
return width; // columnsCount;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
It seems like what you've done is imported the socket
module as import socket
. Therefore socket
is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
, as well as every other use of the socket
module, or change the import statement to from socket import socket
.
Or you've got an import socket
after your from socket import *
:
>>> from socket import *
>>> serv = socket(AF_INET,SOCK_STREAM)
>>> import socket
>>> serv = socket(AF_INET,SOCK_STREAM)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'module' object is not callable
To make POST request instead of GET request using urllib2
, you need to specify empty data, for example:
import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
You can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete.
The ==
operator checks to see if the two strings are exactly the same object.
The .equals()
method will check if the two strings have the same value.
Yes... by the time the regex compiler sees the pattern you've given it, it sees only a single backslash (since Java's lexer has turned the double backwhack into a single one). You need to replace "\\\\"
with "\\\\"
, believe it or not! Java really needs a good raw string syntax.
Remove the if
keyword. It should just be predicate ? true_result : false_result
.
Also ? :
is called ternary operator.
The ThreadPool.QueueUserWorkItem is pretty ideal for something simple. The only caveat is accessing a control from the other thread.
System.Threading.ThreadPool.QueueUserWorkItem(delegate {
DoSomethingThatDoesntInvolveAControl();
}, null);
Exact syntax will of course depend upon database, but something like:
SELECT * FROM my_table WHERE (filename, Dates) IN (SELECT filename, Max(Dates) FROM my_table GROUP BY filename)
This will give you results exactly what you are asking for and displaying above. Fiddle: http://www.sqlfiddle.com/#!2/3af8a/1/0
cd ..
will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername
. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications
would take you to Macintosh HD/Applications
UPDATE test
SET data = data::jsonb - 'a' || '{"a":5}'::jsonb
WHERE data->>'b' = '2'
This seems to be working on PostgreSQL 9.5
You can follow below steps to uninstall the app from the device via command prompt.
if it shows sucess your app is uninstalled successfully'
If you have some column in SELECT clause , how will it select it if there is several rows ? so yes , every column in SELECT clause should be in GROUP BY clause also , you can use aggregate functions in SELECT ...
you can have column in GROUP BY clause which is not in SELECT clause , but not otherwise
I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:
public static String getRelativePath(String fromPath, String toPath) {
// This weirdness is because a separator of '/' messes with String.split()
String regexCharacter = File.separator;
if (File.separatorChar == '\\') {
regexCharacter = "\\\\";
}
String[] fromSplit = fromPath.split(regexCharacter);
String[] toSplit = toPath.split(regexCharacter);
// Find the common path
int common = 0;
while (fromSplit[common].equals(toSplit[common])) {
common++;
}
StringBuffer result = new StringBuffer(".");
// Work your way up the FROM path to common ground
for (int i = common; i < fromSplit.length; i++) {
result.append(File.separatorChar).append("..");
}
// Work your way down the TO path
for (int i = common; i < toSplit.length; i++) {
result.append(File.separatorChar).append(toSplit[i]);
}
return result.toString();
}
Put the following code before int main()
:
using namespace std;
And you will be able to use cout
.
For example:
#include<iostream>
using namespace std;
int main(){
char t = 'f';
char *t1;
char **t2;
cout<<t;
return 0;
}
Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/
Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std;
at the top of your code. For detailed correct approach, please read the answers to this related SO question.
For remote registry you have to use .NET with powershell 2.0
$w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer1)
$keypath = 'SOFTWARE\Veritas\NetBackup\CurrentVersion'
$netbackup = $w32reg.OpenSubKey($keypath)
$NetbackupVersion1 = $netbackup.GetValue('PackageVersion')
I highly recommend the reading of a lecture in SciPy-lectures organization:
https://scipy-lectures.org/intro/language/reusing_code.html
It explains all the commented doubts.
But, new paths can be easily added and avoiding duplication with the following code:
import sys
new_path = 'insert here the new path'
if new_path not in sys.path:
sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script
Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.
If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.
The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.
So the ultimate difference is:
https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx
This link explains in detail how you can handle your problem and what you can do if you want to learn more. For simplicity purposes, what you want to do is
double whateverYouWantToChange = whateverYouWantToChange.ToString("F2");
if you want this for a currency, you can make it easier by typing "C2" instead of "F2"
There's a set_ticks()
function for axis objects.
Here's how I do it:
Code:
let fs = require('fs');
let path = require('path');
let myController = (req, res) => {
let filename = 'myFile.ext';
let absPath = path.join(__dirname, '/my_files/', filename);
let relPath = path.join('./my_files', filename); // path relative to server root
fs.writeFile(relPath, 'File content', (err) => {
if (err) {
console.log(err);
}
res.download(absPath, (err) => {
if (err) {
console.log(err);
}
fs.unlink(relPath, (err) => {
if (err) {
console.log(err);
}
console.log('FILE [' + filename + '] REMOVED!');
});
});
});
};
That would be the final solution. (inspired by @Hollan_Risley's post)
'use strict';
angular.module('app')
.config(function($provide) {
$provide.decorator('$state', function($delegate, $stateParams) {
$delegate.forceReload = function() {
return $delegate.go($delegate.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
};
return $delegate;
});
});
Now, whenever you need to reload, simply call:
$state.forceReload();
In PHP you can try this:
$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;
OR
$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -
$autoload['helper'] = array('url');
With Oracle SQL Developer 3.2.20.09, i managed to set the custom format for the type DATE this way :
In : Tools > Preferences > Database > NLS
Or : Outils > Préférences > Base de donées > NLS
YYYY-MM-DD HH24:MI:SS
Note that the following format does not worked for me :
DD-MON-RR HH24:MI:SS
As a result, it keeps the default format, without any error.
You can use diff
tool in linux to compare two files. You can use --changed-group-format and --unchanged-group-format options to filter required data.
Following three options can use to select the relevant group for each option:
'%<' get lines from FILE1
'%>' get lines from FILE2
'' (empty string) for removing lines from both files.
E.g: diff --changed-group-format="%<" --unchanged-group-format="" file1.txt file2.txt
[root@vmoracle11 tmp]# cat file1.txt
test one
test two
test three
test four
test eight
[root@vmoracle11 tmp]# cat file2.txt
test one
test three
test nine
[root@vmoracle11 tmp]# diff --changed-group-format='%<' --unchanged-group-format='' file1.txt file2.txt
test two
test four
test eight
This is more a comment to previous Thomas Mueller's post rather than an answer, but haven't got enough reputation for it. Another way of getting the connection if you are Spring JDBC Template is using the following:
jdbcTemplate.getDataSource().getConnection();
So on debug mode if you add to the "Expressions" view in Eclipse it will open the browser showing you the H2 Console:
org.h2.tools.Server.startWebServer(jdbcTemplate.getDataSource().getConnection());
New service updated to use the HttpClientModule and RxJS v5.5.x:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { catchError, tap } from 'rxjs/operators';
import { SomeClassOrInterface} from './interfaces';
import 'rxjs/add/observable/throw';
@Injectable()
export class MyService {
url = 'http://my_url';
constructor(private _http:HttpClient) {}
private handleError(operation: String) {
return (err: any) => {
let errMsg = `error in ${operation}() retrieving ${this.url}`;
console.log(`${errMsg}:`, err)
if(err instanceof HttpErrorResponse) {
// you could extract more info about the error if you want, e.g.:
console.log(`status: ${err.status}, ${err.statusText}`);
// errMsg = ...
}
return Observable.throw(errMsg);
}
}
// public API
public getData() : Observable<SomeClassOrInterface> {
// HttpClient.get() returns the body of the response as an untyped JSON object.
// We specify the type as SomeClassOrInterfaceto get a typed result.
return this._http.get<SomeClassOrInterface>(this.url)
.pipe(
tap(data => console.log('server data:', data)),
catchError(this.handleError('getData'))
);
}
Old service, which uses the deprecated HttpModule:
import {Injectable} from 'angular2/core';
import {Http, Response, Request} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
//import 'rxjs/Rx'; // use this line if you want to be lazy, otherwise:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do'; // debug
import 'rxjs/add/operator/catch';
@Injectable()
export class MyService {
constructor(private _http:Http) {}
private _serverError(err: any) {
console.log('sever error:', err); // debug
if(err instanceof Response) {
return Observable.throw(err.json().error || 'backend server error');
// if you're using lite-server, use the following line
// instead of the line above:
//return Observable.throw(err.text() || 'backend server error');
}
return Observable.throw(err || 'backend server error');
}
private _request = new Request({
method: "GET",
// change url to "./data/data.junk" to generate an error
url: "./data/data.json"
});
// public API
public getData() {
return this._http.request(this._request)
// modify file data.json to contain invalid JSON to have .json() raise an error
.map(res => res.json()) // could raise an error if invalid JSON
.do(data => console.log('server data:', data)) // debug
.catch(this._serverError);
}
}
I use .do()
(now .tap()
) for debugging.
When there is a server error, the body
of the Response
object I get from the server I'm using (lite-server) contains just text, hence the reason I use err.text()
above rather than err.json().error
. You may need to adjust that line for your server.
If res.json()
raises an error because it could not parse the JSON data, _serverError
will not get a Response
object, hence the reason for the instanceof
check.
In this plunker, change url
to ./data/data.junk
to generate an error.
Users of either service should have code that can handle the error:
@Component({
selector: 'my-app',
template: '<div>{{data}}</div>
<div>{{errorMsg}}</div>`
})
export class AppComponent {
errorMsg: string;
constructor(private _myService: MyService ) {}
ngOnInit() {
this._myService.getData()
.subscribe(
data => this.data = data,
err => this.errorMsg = <any>err
);
}
}
You don't need to go level up and use ..
since all buttons are on the same level:
//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']
Use std::greater
as the comparison function:
std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;
While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()
when it is deployed as JAR as I faced the same issue.
This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.
Below is the code snippet for the same -
ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
In visual studio, go to help | about and look at the version of Visual Studio that you're using to compile your app.
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
Change the window name in your two different calls:
function popitup(url,windowName) {
newwindow=window.open(url,windowName,'height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.
I do think mapping the Content-Type header in the request will also work. This will work even for cases when you upload a file with no extension. (when filename does not have an extension in the request)
Assume you are sending your data using HTTP POST:
POST /upload2 HTTP/1.1
Host: localhost:7098
Connection: keep-alive
Content-Length: 1047799
Accept: */*
Origin: http://localhost:63342
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
Content-Type: multipart/form-data; boundary=---- WebKitFormBoundaryPDULZN8DYK3VppPp
Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4
Request Payload
------WebKitFormBoundaryPDULZN8DYK3VppPp
Content-Disposition: form-data; name="image"; filename="blob"
Content-Type: image/png
------WebKitFormBoundaryPDULZN8DYK3VppPp--
Here name Content-Type header contains the mime type of the data. Mapping this mime type to an extension will get you the file extension :).
Restify BodyParser converts this header in to a property with name type
File {
domain:
Domain {
domain: null,
_events: { .... },
_eventsCount: 1,
_maxListeners: undefined,
members: [ ... ] },
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
size: 1047621,
path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
name: 'blob',
**type: 'image/png'**,
hash: null,
lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST),
_writeStream:
WriteStream {
... },
writable: true,
domain:
Domain {
...
},
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
pos: undefined,
bytesWritten: 1047621,
closed: true }
}
You can use this header and do the extension mapping (substring etc ...) manually, but there are also ready made libraries for this. Below two were the top results when i did a google search
and their usage is simple as well:
app.post('/upload2', function (req, res) {
console.log(mime.extension(req.files.image.type));
}
above snippet will print png to console.
Was looking for an Answer as well, but all I could find was outdated.
This Issue is solved since HTML5: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
<option value="Microsoft Edge">
</datalist>
If I had not found that, I would have gone with this approach:
http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html
PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn
which will show the process names (but must be run under an administrator account).
Having said that, I would expect the find "8080"
to find it...
Another thing to do is just visit http://localhost:8080
- on that port, chances are it's a web server of some description.
Simple solution for vertical align middle... for me it works like a charm
ul{display:table; text-align:center; margin:0 auto;}
li{display:inline-block; text-align:center;}
li.items_inside_li{display:inline-block; vertical-align:middle;}
I usually run this command when I have to copy my ssh-key
:
cat ~/.ssh/id_rsa.pub | pbcopy
ctrl+v
anywhere else.
use the val() function
What is Spring for? I will answer that question shortly, but first, let's take another look at the example by victor hugo. It's not a great example because it doesn't justify the need for a new framework.
public class BaseView {
protected UserLister userLister;
public BaseView() {
userLister = new UserListerDB(); // only line of code that needs changing
}
}
public class SomeView extends BaseView {
public SomeView() {
super();
}
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
Done! So now even if you have hundreds or thousands of views, you still just need to change the one line of code, as in the Spring XML approach. But changing a line of code still requires recompiling as opposed to editing XML you say? Well my fussy friend, use Ant and script away!
So what is Spring for? It's for:
Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12
SELECT name FROM sqlite_master where name = '<TABLE_NAME_HERE>'
If the table name does not exist then there would not be any records returned!
You can as well use
SELECT count(name) FROM sqlite_master where name = '<TABLE_NAME_HERE>'
if the count is 1, means table exists, otherwise, it would return 0
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
When changing icon size with
UIEdgeInsetsMake(top, left, bottom, right)
, keep in mind button dimensions and the ability of UIEdgeInsetsMake to work with negative values as if they are positive.
Example: Two buttons with height 100 and aspect 1:1.
left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(45, 0, 45, 0)
left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(60, 0, 60, 0)
Examples 1 and 3 are identical since ABS(100 - (40 + 40)) = ABS(100 - (60 + 60))
I changed color programmatically in this way :
var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);
as alertTitle, you can change other data by this way (next example is for titleDivider):
int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);
this is in C#, but in java it is the same.
From SQL Server 2012 and onwards I think this will do the trick:
SELECT DISTINCT
o.OrderNumber ,
FIRST_VALUE(li.Quantity) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Quantity ,
FIRST_VALUE(li.Description) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Description
FROM Orders AS o
INNER JOIN LineItems AS li ON o.OrderID = li.OrderID
If you change the ManagementObjectSearcher to the following:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%""");
So the "GetUSBDevices() looks like this"
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
Your results will be limited to USB devices (as opposed to all types on your system)
It takes keyword arguments for the variables:
url_for('add', variable=foo)
I had the same question and figured it out by using getBoundingClientRect().
This code is completely 'generic' and only has to be written once for it to work (you don't have to write it out for each element that you want to know is in the viewport).
This code only checks to see if it is vertically in the viewport, not horizontally. In this case, the variable (array) 'elements' holds all the elements that you are checking to be vertically in the viewport, so grab any elements you want anywhere and store them there.
The 'for loop', loops through each element and checks to see if it is vertically in the viewport. This code executes every time the user scrolls! If the getBoudingClientRect().top is less than 3/4 the viewport (the element is one quarter in the viewport), it registers as 'in the viewport'.
Since the code is generic, you will want to know 'which' element is in the viewport. To find that out, you can determine it by custom attribute, node name, id, class name, and more.
Here is my code (tell me if it doesn't work; it has been tested in Internet Explorer 11, Firefox 40.0.3, Chrome Version 45.0.2454.85 m, Opera 31.0.1889.174, and Edge with Windows 10, [not Safari yet])...
// Scrolling handlers...
window.onscroll = function(){
var elements = document.getElementById('whatever').getElementsByClassName('whatever');
for(var i = 0; i != elements.length; i++)
{
if(elements[i].getBoundingClientRect().top <= window.innerHeight*0.75 &&
elements[i].getBoundingClientRect().top > 0)
{
console.log(elements[i].nodeName + ' ' +
elements[i].className + ' ' +
elements[i].id +
' is in the viewport; proceed with whatever code you want to do here.');
}
};
@Nullable
and @NotNull
do nothing on their own. They are supposed to act as Documentation tools.
The @Nullable
Annotation reminds you about the necessity to introduce an NPE check when:
The @NotNull
Annotation is, actually, an explicit contract declaring the following:
For example, instead of writing:
/**
* @param aX should not be null
*/
public void setX(final Object aX ) {
// some code
}
You can use:
public void setX(@NotNull final Object aX ) {
// some code
}
Additionally, @NotNull
is often checked by ConstraintValidators (eg. in spring and hibernate).
The @NotNull
annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator
type reference.
For more info see:
That works better with this :
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
Your code has nothing to do with the service installation, it is not the problem.
In order to test the service, you must install it as indicated.
For more information about installing your service : Installing and Uninstalling Services
.ico
, or is it just named ".ico"?The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.
If you must have it in a subdirectory, use:
<link rel="shortcut icon" href="/img/favicon.ico" />
Note the /
before img
to ensure it is anchored to the root folder.
Use WSDL.EXE utility to generate a Web Service proxy from WSDL.
You'll get a long C# source file that contains a class that looks like this:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
...
}
In your client-side, Web-service-consuming code:
ElementFormDefault has nothing to do with namespace of the types in the schema, it's about the namespaces of the elements in XML documents which comply with the schema.
Here's the relevent section of the spec:
Element Declaration Schema Component Property {target namespace} Representation If form is present and its ·actual value· is qualified, or if form is absent and the ·actual value· of elementFormDefault on the <schema> ancestor is qualified, then the ·actual value· of the targetNamespace [attribute] of the parent <schema> element information item, or ·absent· if there is none, otherwise ·absent·.
What that means is that the targetNamespace you've declared at the top of the schema only applies to elements in the schema compliant XML document if either elementFormDefault is "qualified" or the element is declared explicitly in the schema as having form="qualified".
For example: If elementFormDefault is unqualified -
<element name="name" type="string" form="qualified"></element>
<element name="page" type="target:TypePage"></element>
will expect "name" elements to be in the targetNamespace and "page" elements to be in the null namespace.
To save you having to put form="qualified" on every element declaration, stating elementFormDefault="qualified" means that the targetNamespace applies to each element unless overridden by putting form="unqualified" on the element declaration.
That's a bad practice to use the ==
equality operator instead of ===
.
undefined === undefined // true
null == undefined // true
null === undefined // false
The object.x === undefined
should return true
if x
is unknown property.
In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:
If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.
In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like
value = myObject[name]; if (value == null) { alert(name + ' not found.'); }
It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:
value = myObject[name]; if (value === undefined) { alert(name + ' not found.'); }
Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:
fun1("who is who", 3, "jack")
What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".
Instead of manipulating the CMAKE_CXX_FLAGS
strings directly (which could be done more nicely using string(APPEND CMAKE_CXX_FLAGS_DEBUG " -g3")
btw), you can use add_compiler_options
:
add_compile_options(
"-Wall" "-Wpedantic" "-Wextra" "-fexceptions"
"$<$<CONFIG:DEBUG>:-O0;-g3;-ggdb>"
)
This would add the specified warnings to all build types, but only the given debugging flags to the DEBUG
build. Note that compile options are stored as a CMake list, which is just a string separating its elements by semicolons ;
.
A more generic solution without function overloading than my previous one:
template<typename T>
std::string TypeOf(T){
std::string Type="unknown";
if(std::is_same<T,int>::value) Type="int";
if(std::is_same<T,std::string>::value) Type="String";
if(std::is_same<T,MyClass>::value) Type="MyClass";
return Type;}
Here MyClass is user defined class. More conditions can be added here as well.
Example:
#include <iostream>
class MyClass{};
template<typename T>
std::string TypeOf(T){
std::string Type="unknown";
if(std::is_same<T,int>::value) Type="int";
if(std::is_same<T,std::string>::value) Type="String";
if(std::is_same<T,MyClass>::value) Type="MyClass";
return Type;}
int main(){;
int a=0;
std::string s="";
MyClass my;
std::cout<<TypeOf(a)<<std::endl;
std::cout<<TypeOf(s)<<std::endl;
std::cout<<TypeOf(my)<<std::endl;
return 0;}
Output:
int
String
MyClass
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
I had this issue running within a corporate network. I added a DNS entry for google DNS at 8.8.8.8, then my own corporate DNS server below this. Worked great after that.
Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017
-- Creating a table using NEWID for uniqueidentifier data type.
CREATE TABLE cust
(
CustomerID uniqueidentifier NOT NULL
DEFAULT newid(),
Company varchar(30) NOT NULL,
ContactName varchar(60) NOT NULL,
Address varchar(30) NOT NULL,
City varchar(30) NOT NULL,
StateProvince varchar(10) NULL,
PostalCode varchar(10) NOT NULL,
CountryRegion varchar(20) NOT NULL,
Telephone varchar(15) NOT NULL,
Fax varchar(15) NULL
);
GO
-- Inserting 5 rows into cust table.
INSERT cust
(CustomerID, Company, ContactName, Address, City, StateProvince,
PostalCode, CountryRegion, Telephone, Fax)
VALUES
(NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,
'90110', 'Finland', '981-443655', '981-443655')
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',
'08737-363', 'Brasil', '(14) 555-8122', '')
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,
'1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,
'8010', 'Austria', '7675-3425', '7675-3426')
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,
'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');
GO
Here's another solution, using the ast
module:
python -c "import ast; ast.parse(open('programfile').read())"
To do it cleanly from within a Python script:
import ast, traceback
filename = 'programfile'
with open(filename) as f:
source = f.read()
valid = True
try:
ast.parse(source)
except SyntaxError:
valid = False
traceback.print_exc() # Remove to silence any errros
print(valid)
Set the width of post-content and post-thumb so that you get a two-column layout.
Here is an alternative solution:
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__dict__ = self
a = AttrDict()
a.a = 1
a.b = 2
You seem to be using the combined log format.
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined
"-"
otherwise.The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.
This can happen due to your choice of the signature version. On some phones, installation errors occur if the signature version was selected as V2. So if that happens, try selecting V1, it will surely work.
After searching for a day, I think this is the easiest solution:
imageView.getLayoutParams().width = 250;
imageView.getLayoutParams().height = 250;
imageView.setAdjustViewBounds(true);
There's no easy solution. Each way has their pros and cons . But the canonical way is using the first option: multipart/form-data
. As W3 recommendation guide says
The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
We aren't sending forms,really, but the implicit principle still applies. Using base64 as a binary representation, is incorrect because you're using the incorrect tool for accomplish your goal, in other hand, the second option forces your API clients to do more job in order to consume your API service. You should do the hard work in the server side in order to supply an easy-to-consume API. The first option is not easy to debug, but when you do it, it probably never changes.
Using multipart/form-data
you're sticked with the REST/http philosophy. You can view an answer to similar question here.
Another option if mixing the alternatives, you can use multipart/form-data but instead of send every value separate, you can send a value named payload with the json payload inside it. (I tried this approach using ASP.NET WebAPI 2 and works fine).
In order to deal with the IllegalMonitorStateException, you must verify that all invocations of the wait, notify and notifyAll methods are taking place only when the calling thread owns the appropriate monitor. The most simple solution is to enclose these calls inside synchronized blocks. The synchronization object that shall be invoked in the synchronized statement is the one whose monitor must be acquired.
Here is the simple example for to understand the concept of monitor
public class SimpleMonitorState {
public static void main(String args[]) throws InterruptedException {
SimpleMonitorState t = new SimpleMonitorState();
SimpleRunnable m = new SimpleRunnable(t);
Thread t1 = new Thread(m);
t1.start();
t.call();
}
public void call() throws InterruptedException {
synchronized (this) {
wait();
System.out.println("Single by Threads ");
}
}
}
class SimpleRunnable implements Runnable {
SimpleMonitorState t;
SimpleRunnable(SimpleMonitorState t) {
this.t = t;
}
@Override
public void run() {
try {
// Sleep
Thread.sleep(10000);
synchronized (this.t) {
this.t.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Also, you can see the build dependencies in the file setup.cfg
To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017
and may leave the author guessing (which I am a victim of myself).
Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:
"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"
So, not supported are:
\A
, alternatively use the ^
caret to match postion before 1st char in string\Z
, alternatively use the $
dollar sign to match postion after last char in string(?<=a)b
(whilst postive LookAhead is supported)(?<!a)b
(whilst negative LookAhead is supported)\{uFFFF}
/i
(case sensitivity) or /g
(global) etc. Set these through the RegExp
object properties > RegExp.Global = True
and RegExp.IgnoreCase = True
if available.'
comments in script I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind
but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.
P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.
Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.
I got it
Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"
Basically, I need to set the cell format, instead of setting the date.
If ever you need to do the same thing with mongoid:
Model.all.rename(:old_field, :new_field)
UPDATE
There is change in the syntax in monogoid 4.0.0
:
Model.all.rename(old_field: :new_field)
Union
will remove duplicates. Union All
does not.
There is no difference between the %i
and %d
format specifiers for printf
. We can see this by going to the draft C99 standard section 7.19.6.1
The fprintf function which also covers printf
with respect to format specifiers and it says in paragraph 8:
The conversion specifiers and their meanings are:
and includes the following bullet:
d,i The int argument is converted to signed decimal in the style [-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.
On the other hand for scanf
there is a difference, %d
assume base 10 while %i
auto detects the base. We can see this by going to section 7.19.6.2
The fscanf function which covers scanf
with respect to format specifier, in paragraph 12 it says:
The conversion specifiers and their meanings are:
and includes the following:
d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer. i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:
.style1[disabled] { ... }
Worked ok on IE8.
For MacOS users:
Just do this and easily it will solve your problem:
brew install cocoapods
It's not strictly speaking a comment, but...
It was the mid-1990s and I was working on a big migration: small software vendor, big client, lots of pressure. We had a lot of shifting-goalpost stuff; the project was very hard to control. I was the key developer, but new to the system, and the other developer was the vendor's owner/founder.
After a few months of not quite making deadlines and not quite satisfying the client, the owner/founder brought on another developer, who was working remotely. (I'm gonna go out on a limb and say the new developer had lesser skills and experience than me.)
Well, the new guy made some changes in code that I'd already worked on, and then a month or two later I was back in the same area of the code, and there were variables I hadn't seen before. With names like StupidMark
.
Dude, that's just not right. I mean, there's teamwork considerations, but also: in this environment, variable names can show up in runtime error messages. I'm just saying.
In my opinion at the time, the new guy's code wasn't getting us much closer to a deliverable product anyway, which made the insult sting a little more.
You can append to a csv by opening the file in append mode:
with open('my_csv.csv', 'a') as f:
df.to_csv(f, header=False)
If this was your csv, foo.csv
:
,A,B,C
0,1,2,3
1,4,5,6
If you read that and then append, for example, df + 6
:
In [1]: df = pd.read_csv('foo.csv', index_col=0)
In [2]: df
Out[2]:
A B C
0 1 2 3
1 4 5 6
In [3]: df + 6
Out[3]:
A B C
0 7 8 9
1 10 11 12
In [4]: with open('foo.csv', 'a') as f:
(df + 6).to_csv(f, header=False)
foo.csv
becomes:
,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12
The WPF DataGrid
has an IsReadOnly
property that you can set to True
to ensure that users cannot edit your DataGrid
's cells.
You can also set this value for individual columns in your DataGrid
as needed.
I assume that you are looking for intuitive definitions, since the technical definitions require quite some time to understand. First of all, let's remember a preliminary needed concept to understand those definitions.
Now, let us define those complexity classes.
P is a complexity class that represents the set of all decision problems that can be solved in polynomial time.
That is, given an instance of the problem, the answer yes or no can be decided in polynomial time.
Example
Given a connected graph G
, can its vertices be coloured using two colours so that no edge is monochromatic?
Algorithm: start with an arbitrary vertex, color it red and all of its neighbours blue and continue. Stop when you run out of vertices or you are forced to make an edge have both of its endpoints be the same color.
NP is a complexity class that represents the set of all decision problems for which the instances where the answer is "yes" have proofs that can be verified in polynomial time.
This means that if someone gives us an instance of the problem and a certificate (sometimes called a witness) to the answer being yes, we can check that it is correct in polynomial time.
Example
Integer factorisation is in NP. This is the problem that given integers n
and m
, is there an integer f
with 1 < f < m
, such that f
divides n
(f
is a small factor of n
)?
This is a decision problem because the answers are yes or no. If someone hands us an instance of the problem (so they hand us integers n
and m
) and an integer f
with 1 < f < m
, and claim that f
is a factor of n
(the certificate), we can check the answer in polynomial time by performing the division n / f
.
NP-Complete is a complexity class which represents the set of all problems X
in NP for which it is possible to reduce any other NP problem Y
to X
in polynomial time.
Intuitively this means that we can solve Y
quickly if we know how to solve X
quickly. Precisely, Y
is reducible to X
, if there is a polynomial time algorithm f
to transform instances y
of Y
to instances x = f(y)
of X
in polynomial time, with the property that the answer to y
is yes, if and only if the answer to f(y)
is yes.
Example
3-SAT
. This is the problem wherein we are given a conjunction (ANDs) of 3-clause disjunctions (ORs), statements of the form
(x_v11 OR x_v21 OR x_v31) AND
(x_v12 OR x_v22 OR x_v32) AND
... AND
(x_v1n OR x_v2n OR x_v3n)
where each x_vij
is a boolean variable or the negation of a variable from a finite predefined list (x_1, x_2, ... x_n)
.
It can be shown that every NP problem can be reduced to 3-SAT. The proof of this is technical and requires use of the technical definition of NP (based on non-deterministic Turing machines). This is known as Cook's theorem.
What makes NP-complete problems important is that if a deterministic polynomial time algorithm can be found to solve one of them, every NP problem is solvable in polynomial time (one problem to rule them all).
Intuitively, these are the problems that are at least as hard as the NP-complete problems. Note that NP-hard problems do not have to be in NP, and they do not have to be decision problems.
The precise definition here is that a problem X
is NP-hard, if there is an NP-complete problem Y
, such that Y
is reducible to X
in polynomial time.
But since any NP-complete problem can be reduced to any other NP-complete problem in polynomial time, all NP-complete problems can be reduced to any NP-hard problem in polynomial time. Then, if there is a solution to one NP-hard problem in polynomial time, there is a solution to all NP problems in polynomial time.
Example
The halting problem is an NP-hard problem. This is the problem that given a program P
and input I
, will it halt? This is a decision problem but it is not in NP. It is clear that any NP-complete problem can be reduced to this one. As another example, any NP-complete problem is NP-hard.
My favorite NP-complete problem is the Minesweeper problem.
This one is the most famous problem in computer science, and one of the most important outstanding questions in the mathematical sciences. In fact, the Clay Institute is offering one million dollars for a solution to the problem (Stephen Cook's writeup on the Clay website is quite good).
It's clear that P is a subset of NP. The open question is whether or not NP problems have deterministic polynomial time solutions. It is largely believed that they do not. Here is an outstanding recent article on the latest (and the importance) of the P = NP problem: The Status of the P versus NP problem.
The best book on the subject is Computers and Intractability by Garey and Johnson.
The fastest way if your keys are in an SSH agent:
$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin
Each key in the agent will be printed as:
4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)
Include a few #ifndef name #define name #endif preprocessor that should solve your problem. The issue is it going from the header to the function then back to the header so it is redefining the class with all the preprocessor(#include) multiple times.
I do it this way:
The html:
<head>
<style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>
The xCss.php:
<? // place here your vars
$fntBtn = 'bold 14px Arial'
$colBorder = '#556677' ;
$colBG0 = '#dddddd' ;
$colBG1 = '#44dddd' ;
$colBtn = '#aadddd' ;
// here goes your css after the php-close tag:
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; }
>>> map(myList.__getitem__, (2,2,1,3))
('baz', 'baz', 'bar', 'quux')
You can also create your own List
class which supports tuples as arguments to __getitem__
if you want to be able to do myList[(2,2,1,3)]
.
So what will happen if two threads attack a volatile primitive variable at same time?
Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.
Does this mean that whosoever takes lock on it, that will be setting its value first.
There is no lock. That is what synchronized
is for.
And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
Yes,
What is the difference between Atomic and volatile keyword?
AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.
AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.
int i = myObject.myField.CastTo<int>();
I have a function next()
which will maybe inspire you.
function queue(target) {
var array = Array.prototype;
var queueing = [];
target.queue = queue;
target.queued = queued;
return target;
function queued(action) {
return function () {
var self = this;
var args = arguments;
queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}
function queue(action) {
if (!action) {
return;
}
queueing.push(action);
if (queueing.length === 1) {
next();
}
}
function next() {
queueing[0](function (err) {
if (err) {
throw err;
}
queueing = queueing.slice(1);
if (queueing.length) {
next();
}
});
}
}
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
This question seems to be answered, however for completeness, I would add another approach.
You can use a unique ID number generator which is based on Twitter's Snowflake id generator. C# implementation can be found here.
var id64Generator = new Id64Generator();
// ...
public string generateID(string sourceUrl)
{
return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}
Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.
// node 0
var id64Generator = new Id64Generator(0);
// node 1
var id64Generator = new Id64Generator(1);
// ... node 10
var id64Generator = new Id64Generator(10);
I ran into this problem today and this was the trick I did, which worked for me:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAOMANAGER");
EntityManagerem = emf.createEntityManager();
org.hibernate.Session session = ((EntityManagerImpl) em).getSession();
java.sql.Connection connectionObj = session.connection();
Though not the best way but does the job.
#include <stdio.h>
//fonts color
#define FBLACK "\033[30;"
#define FRED "\033[31;"
#define FGREEN "\033[32;"
#define FYELLOW "\033[33;"
#define FBLUE "\033[34;"
#define FPURPLE "\033[35;"
#define D_FGREEN "\033[6;"
#define FWHITE "\033[7;"
#define FCYAN "\x1b[36m"
//background color
#define BBLACK "40m"
#define BRED "41m"
#define BGREEN "42m"
#define BYELLOW "43m"
#define BBLUE "44m"
#define BPURPLE "45m"
#define D_BGREEN "46m"
#define BWHITE "47m"
//end color
#define NONE "\033[0m"
int main(int argc, char *argv[])
{
printf(D_FGREEN BBLUE"Change color!\n"NONE);
return 0;
}
Remember that a single =
is always an assignment in C or C++.
Your test should be if ( match == 0 && k == M )
you made a typo on the k == M
test.
If you really mean k=M
(i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0)
but most coding rules advise not writing that.
BTW, your mistake suggests to ask for all warnings (e.g. -Wall
option to g++
), and to upgrade to recent compilers. The next GCC 4.8 will give you:
% g++-trunk -Wall -c ederman.cc
ederman.cc: In function ‘void foo()’:
ederman.cc:9:30: error: lvalue required as left operand of assignment
if ( match == 0 && k = M )
^
and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable
So use recent versions of free compilers and enable all the warnings when using them.
cakephp version >= 3.6
echo $this->Form->control('field_name', ['type' => 'select', 'options' => $departments, 'default' => 'your value']);
SELECT *
FROM tbl
WHERE myDate BETWEEN #date one# AND #date two#;
You have to explicitly define the constructor in B and explicitly call the constructor for the parent.
B(int x) : A(x) { }
or
B() : A(5) { }
Position the div
relatively, and position the ribbon absolutely inside it. Something like:
#content {
position:relative;
}
.ribbon {
position:absolute;
top:0;
right:0;
}
$(":button").click(function () {
$("#anchor_google")[0].click();
});
Your database may be corrupt. Try to check if mysql.user exists:
use mysql;
select * from user;
If these are missing you can try recreating the tables by using
mysql_install_db
or you may have to clean (completely remove it) and reinstall MySQL.
I see two problems:
The pointer answer
is a null
pointer and you are trying to dereference it in scanf
, this leads to undefined behavior.
You don't need a char
pointer here. You can just use a char
variable as:
char answer;
scanf(" %c",&answer);
Next to see if the read character is 'y'
or 'Y'
you should do:
if( answer == 'y' || answer == 'Y') {
// user entered y or Y.
}
If you really need to use a char pointer you can do something like:
char var;
char *answer = &var; // make answer point to char variable var.
scanf (" %c", answer);
if( *answer == 'y' || *answer == 'Y') {
In your example you are comparing the string objects, not their content.
Your comparison should be :
if (s.equals("/quit"))
Or if s
string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))
This is due to MultiDex.
Steps to solve:
In gradle->dependencies->(compile'com.android.support:multidex:1.0.1') Add this in dependencies
In your project application class extends MultiDexApplication like this (public class MyApplication extends MultiDexApplication)
Run and check
For me the issue was with the space in volume mapping that was not escaped. The jenkins job which was running the docker run command had a space in it and as a result docker engine was not able to understand the docker run command.
Get key values from list of dictionaries in python?
Ex:
data =
[{'obj1':[{'cpu_percentage':'15%','ram':3,'memory_percentage':'66%'}]},
{'obj2': [{'cpu_percentage':'0','ram':4,'memory_percentage':'35%'}]}]
for d in data:
for key,value in d.items():
z ={key: {'cpu_percentage': d['cpu_percentage'],'memory_percentage': d['memory_percentage']} for d in value}
print(z)
Output:
{'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
{'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}
Add grid with defined height and width for columns and rows. Then add ScrollViewer
and inside it add the dataGrid.
Try using
docker exec -it <container-name> /bin/bash
There might be possibility that bash is not implemented. for that you can use
docker exec -it <container-name> sh
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.
JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
add(mycombo); //Adds it to the jframe.
mycombo.addItem("Hello Nepal"); //Adds data to the JComboBox.
String s=String.valueOf(mycombo.getSelectedItem()); //Assigns "Hello Nepal" to s.
System.out.println(s); //Prints "Hello Nepal".
I agree that this var formattedString = string.replace(/'/g, "\\'");
works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \
and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \
was the work around.
Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager.
If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start. In some cases above state can stop though TCP connection to port 1433 is assigned.
Why not use a regex for this?
a = a.replaceAll("\\s","");
In the context of a regex, \s
will remove anything that is a space character (including space, tab characters etc). You need to escape the backslash in Java so the regex turns into \\s
. Also, since Strings are immutable it is important that you assign the return value of the regex to a
.
Using a single sed
echo "/var/cpanel/users/joebloggs:DNS9=domain.com" | sed 's/.*\/\(.*\):.*/\1/'
You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.
Another, simpler approach (to an old question)..
would be to place elements as siblings and use:
Adjacent Sibling Selector (+
)
or
General Sibling Selector (~
)
<div id="parent">
<!-- control should come before the target... think "cascading" ! -->
<button id="control">Hover Me!</button>
<div id="target">I'm hovered too!</div>
</div>
#parent {
position: relative;
height: 100px;
}
/* Move button control to bottom. */
#control {
position: absolute;
bottom: 0;
}
#control:hover ~ #target {
background: red;
}
Click on the New file menu, and chose file select language Objective. At that time it automatically generates a "Objective-C Bridging Header" file that is used to define some class name.
"Objective-C Bridging Header" under "Swift Compiler - Code Generation".
It is not possible to assign values to an array all at once after initialization. The best alternative would be to use a loop.
for(i=0;i<N;i++)
{
array[i] = i;
}
You can hard code and assign values like --array[0] = 1
and so on.
Memcpy can also be used if you have the data stored in an array already.
Issue is gem dependency so before installing pg make sure you have installed "libpq-dev"
Ubuntu systems:
sudo apt-get install libpq-dev
RHEL systems:
yum install postgresql-devel
Mac:
brew install postgresql
Add http:// in front of url
Incorrect
<a href="www.example.com">www.example.com</span></p>
Correct
<a href="http://www.example.com">www.example.com</span></p>
Properties in your object are value types and you can use the shallow copy in such situation like that:
obj myobj2 = (obj)myobj.MemberwiseClone();
But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization
and Deserialization
techniques with the help of BinaryFormatter
class:
public static T DeepCopy<T>(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Clone);
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
The purpose of setting StreamingContext
:
We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable
interface or using built-in attributes like OnDeserialized
, OnDeserializing
, OnSerializing
, OnSerialized
. In all cases StreamingContext
will be passed as an argument to the methods(and to the special constructor in case of ISerializable
interface). With setting ContextState
to Clone
, we are just giving hint to that method about the purpose of the serialization.
Additional Info: (you can also read this article from MSDN)
Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.
Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.
Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html
It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.
Best way is use DateTime object to convert your date.
$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');
Note: It will support for PHP 5 >= 5.3.0 only.
Using the following imports:
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';
Try this:
let fakeResponse = [1,2,3];
let delayedObservable = Observable.of(fakeResponse).delay(5000);
delayedObservable.subscribe(data => console.log(data));
UPDATE: RXJS 6
The above solution doesn't really work anymore in newer versions of RXJS (and of angular for example).
So the scenario is that I have an array of items to check with an API with. The API only accepts a single item, and I do not want to kill the API by sending all requests at once. So I need a timed release of items on the Observable stream with a small delay in between.
Use the following imports:
import { from, of } from 'rxjs';
import { delay } from 'rxjs/internal/operators';
import { concatMap } from 'rxjs/internal/operators';
Then use the following code:
const myArray = [1,2,3,4];
from(myArray).pipe(
concatMap( item => of(item).pipe ( delay( 1000 ) ))
).subscribe ( timedItem => {
console.log(timedItem)
});
It basically creates a new 'delayed' Observable for every item in your array. There are probably many other ways of doing it, but this worked fine for me, and complies with the 'new' RXJS format.
You can also set attribute:
elem.setAttribute("onclick","alert('blah');");
You can do something like this:
String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null) {
// Store the content into an array
Scanner s = new Scanner(strLine);
while(s.hasNext()) {
if (wordList.length == wordCount) {
// expand list
wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
}
wordList[wordCount] = s.next();
wordCount++;
}
}
Using java.util.Arrays.copyOf(String[])
is basically doing the same thing as:
if (wordList.length == wordCount) {
String[] temp = new String[wordList.length + arrayGrowth];
System.arraycopy(wordList, 0, temp, 0, wordList.length);
wordList = temp;
}
except it is one line of code instead of three. :)
Consider two ways of doing the same thing:
PreparedStatement stmt = conn.createStatement("INSERT INTO students VALUES('" + user + "')");
stmt.execute();
Or
PreparedStatement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)");
stmt.setString(1, user);
stmt.execute();
If "user" came from user input and the user input was
Robert'); DROP TABLE students; --
Then in the first instance, you'd be hosed. In the second, you'd be safe and Little Bobby Tables would be registered for your school.
You can handle click on list view item like this:
<ListView.ItemTemplate>
<DataTemplate>
<Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Button.Template>
<ControlTemplate>
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
...
If you want more compact code, I suggest using Apache Commons DbUtils. In this case:
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
str_replace
with arrays just performs all the replacements sequentially. Use strtr
instead to do them all at once:
$new_message = strtr($message, 'lmnopq...', 'abcdef...');
That is a pretty standard use case for apply()
:
R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
start end newcol
1 1 2 1.5
2 3 6 4.5
3 5 7 6.0
4 7 9 8.0
R>
You can also use plyr
if you prefer but here is no real need to go beyond functions from base R.
chmod +x gradlew
Just run the above comment. that's all enjoy your coding...
I was having this issue as well, and I found an easy way to resolve it.
Get the index of unassigned shards
$ curl -XGET http://172.16.4.140:9200/_cat/shards
Install curator Tools, and use it to delete index
$ curator --host 172.16.4.140 delete indices --older-than 1 \
--timestring '%Y.%m.%d' --time-unit days --prefix logstash
NOTE: In my case, the index is logstash of the day 2016-04-21
I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.
The trick is to use --trustedhost
to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.
So in a nutshell, you should do:
pip install python-certifi-win32 -trustedhost pypi.org
and after that you should be good to go
It seems you want to save your class instances across sessions, and using pickle
is a decent way to do this. However, there's a package called klepto
that abstracts the saving of objects to a dictionary interface, so you can choose to pickle objects and save them to a file (as shown below), or pickle the objects and save them to a database, or instead of use pickle use json, or many other options. The nice thing about klepto
is that by abstracting to a common interface, it makes it easy so you don't have to remember the low-level details of how to save via pickling to a file, or otherwise.
Note that It works for dynamically added class attributes, which pickle cannot do...
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> class Fruits: pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>>
>>> db['banana'] = banana
>>> db.dump()
>>>
Then we restart…
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> db.load()
>>>
>>> db['banana'].color
'yellow'
>>>
Klepto
works on python2 and python3.
Get the code here: https://github.com/uqfoundation
I have used the same instructions Stefan
used, taken from Tortoise website.
But it's important to click COMMIT right after. I was getting crazy until I realized that.
If you need to make an older revision your head revision do the following:
Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.
Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.
Right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.
Make a commit.
Personally I prefer this clean implementation:
watch: {
myVariable: {
handler(newVal, oldVal){ // here having access to the new and old value
// do stuff
},
deep: true,
immediate: true // Also very important the immediate in case you need it, the callback will be called immediately after the start of the observation
}
}
I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.
I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.
Could it be a mistake in my implementation that looks like this (PHP - server side):
$data = array();
$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);
$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);
$jsonString = "[" . implode(", ", $data) . "]";
The final step is that I store the JSON encoded string into an JS variable:
<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>
If I use "" instead of '' it still throws an error.
SOLUTION:
The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:
json_encode($tmp, JSON_HEX_APOS);
Is there another way of tackle this issue? Is my code wrong or poorly written?
Thanks
Here is one of my mistakes that produced this exception: I had a try
block without any except
or finally
blocks. This will not work:
try:
lets_do_something_beneficial()
To fix this, add an except
or finally
block:
try:
lets_do_something_beneficial()
finally:
lets_go_to_sleep()
The documentation for required()
states:
To force a user to select an option from a select box, provide an empty options like
<option value="">Choose...</option>
By having value="none"
in your <option>
tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:
If you can't change the value
attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.
The really quick and dirty way is to point to a local file:
<dependency>
<groupId>sampleGroupId</groupId>
<artifactId>sampleArtifactId</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C:\DEV\myfunnylib\yourJar.jar</systemPath>
</dependency>
However this will only live on your machine (obviously), for sharing it usually makes sense to use a proper m2 archive (nexus/artifactory) or if you do not have any of these or don't want to set one up a local maven structured archive and configure a "repository" in your pom:
local:
<repositories>
<repository>
<id>my-local-repo</id>
<url>file://C:/DEV//mymvnrepo</url>
</repository>
</repositories>
remote:
<repositories>
<repository>
<id>my-remote-repo</id>
<url>http://192.168.0.1/whatever/mavenserver/youwant/repo</url>
</repository>
</repositories>
I use this regular expression to filter out bad characters in a filename.
Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")
That should be all the characters allowed for filenames.
You could use a Set. It is a collection which doesn't accept duplicates.
You'd need to remove the blank table cell element entirely, and change the colspan attribute on another cell in the row to encompass the released space, e.g.:
refToCellToRemove.remove();
refTocellToExpand.colspan = 4;
Note that setting it via setAttribute (which would otherwise be correct) will not work properly on IE.
Beware: IE does some very strange table layout things when you muck about with colspans dynamically. If you can avoid it, I would.
I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.
The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument
This works for me on toggling enable and disable datepicker of JQuery:
if (condition) {
$('#ElementID').datepicker(); //Enable datepicker
} else {
//Disable datepicker without the ability to enter any character on text input
$('#ElementID').datepicker('destroy');
$('#ElementID').attr('readonly', true); }
I don't know why but when I use enable/disable in datepicker options, it doesn't behave the way it should be. It only works after you enable and disable it, but once you disable it, it doesn't enable again after, so the code above works perfectly fine for me:
if (condition) {
$('#ElementID').datepicker('enable'); //Enable datepicker
} else {
//Disable datepicker but I cannot enable it again once it goes through this condition
$('#ElementID').datepicker('disable'); }
Say:
sed "s|\$ROOT|${HOME}|" abc.sh
Note:
/
since the replacement contains /
$
in the pattern since you don't want to expand it.EDIT: In order to replace all occurrences of $ROOT
, say
sed "s|\$ROOT|${HOME}|g" abc.sh
Use the Application.DispatcherUnhandledException Event
. See this question for a summary (see Drew Noakes' answer).
Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.
Here's a version of @Julian Mosquera's code that also supports a "fallback" field to use in case the primary field happens to be null or undefined:
yourApp.filter('orderObjectBy', function() {
return function(items, field, fallback, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
var af = a[field];
if(af === undefined || af === null) { af = a[fallback]; }
var bf = b[field];
if(bf === undefined || bf === null) { bf = b[fallback]; }
return (af > bf ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
sed '/^cdef$/r'<(
echo "line1"
echo "line2"
echo "line3"
echo "line4"
) -i -- input.txt
Thank you Joel for giving me a clue on how to resolve this problem.
I have simplified the code(without need for a GestureDetector) to achieve the same effect:
public class VerticalScrollView extends ScrollView {
private float xDistance, yDistance, lastX, lastY;
public VerticalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
xDistance = yDistance = 0f;
lastX = ev.getX();
lastY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
final float curX = ev.getX();
final float curY = ev.getY();
xDistance += Math.abs(curX - lastX);
yDistance += Math.abs(curY - lastY);
lastX = curX;
lastY = curY;
if(xDistance > yDistance)
return false;
}
return super.onInterceptTouchEvent(ev);
}
}
I have a ~/bin/code
shell script that matches the command @BengaminPasero wrote.
#!/bin/bash
VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $*
I prefix ~/bin:
to my $PATH
which allows me to add a bunch of one off scripts without polluting my ~/.bash_profile
script.
@Temporal
is a JPA annotation which can be used to store in the database table on of the following column items:
java.sql.Date
)java.sql.Time
)java.sql.Timestamp
)Generally when we declare a Date
field in the class and try to store it.
It will store as TIMESTAMP in the database.
@Temporal
private Date joinedDate;
Above code will store value looks like 08-07-17 04:33:35.870000000 PM
If we want to store only the DATE in the database,
We can use/define TemporalType
.
@Temporal(TemporalType.DATE)
private Date joinedDate;
This time, it would store 08-07-17 in database
There are some other attributes as well as @Temporal
which can be used based on the requirement.
In my case I got this error because of a line
<script src="#"></script>
Chrome tried to interpret the current HTML file then as javascript.
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...