File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.
You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo rm -rf /var/lib/mysql
I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!
this works for me
template.html
$.ajax({
url: "{% url 'XXXXXX' %}",
type: 'POST',
data: {modifica: jsonText, "csrfmiddlewaretoken" : "{{csrf_token}}"},
traditional: true,
dataType: 'html',
success: function(result){
window.location.href = "{% url 'XXX' %}";
}
});
view.py
def aggiornaAttivitaAssegnate(request):
if request.is_ajax():
richiesta = json.loads(request.POST.get('modifica'))
Just implement an Interface given by PHP JsonSerializable.
As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things
Propagate the InterruptedException
- Declare your method to throw the checked InterruptedException
so that your caller has to deal with it.
Restore the Interrupt - Sometimes you cannot throw InterruptedException
. In these cases you should catch the InterruptedException
and restore the interrupt status by calling the interrupt()
method on the currentThread
so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log()
or sendMetric()
may be such method, or boolean tryTransferMoney()
, but not void transferMoney()
. See here for more details.
Uninterruptibles
. Uninterruptibles
take over the boilerplate code like in the Noncancelable Task example in JCIP § 7.1.3.The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /lin/Campaignn.jsp.
As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.
Using background-size cover worked for me.
#footer {
background-color: #eee;
background-image: url(images/bodybgbottomleft.png);
background-repeat: no-repeat;
background-size: cover;
clear: both;
width: 100%;
margin: 0;
padding: 30px 0 0;
}
Obviously be aware of support issues, check Can I Use: http://caniuse.com/#search=background-size
use List<T>
. Internally it uses arrays and arrays do use contiguous memory.
I'm a little late to the party but I'll give my two cents. I just resolved this issue after spending longer than I'd like on it. The above solutions didn't work for me and here's why:
there was a network issue when maven was downloading the required repositories so I actually didn't have the right jars. adding a -U to a maven clean install went and got them for me. So if the above solutions aren't working try this:
Hope it works for you.
I just found the "-fae" parameter, which causes Maven to run all tests and not stop on failure.
In my case I had to compare two Integer
s for equality where both of them could be null
. Searched similar topic, didn't found anything elegant for this. Came up with a simple utility functions.
public static boolean integersEqual(Integer i1, Integer i2) {
if (i1 == null && i2 == null) {
return true;
}
if (i1 == null && i2 != null) {
return false;
}
if (i1 != null && i2 == null) {
return false;
}
return i1.intValue() == i2.intValue();
}
//considering null is less than not-null
public static int integersCompare(Integer i1, Integer i2) {
if (i1 == null && i2 == null) {
return 0;
}
if (i1 == null && i2 != null) {
return -1;
}
return i1.compareTo(i2);
}
Change this line:
The 2 should be 0. Every count starts at 0.
//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong
//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
According to the latest angular 2 documentation you can animate "Entering and Leaving" elements (like in angular 1).
Example of simple fade animation:
In relevant @Component add:
animations: [
trigger('fadeInOut', [
transition(':enter', [ // :enter is alias to 'void => *'
style({opacity:0}),
animate(500, style({opacity:1}))
]),
transition(':leave', [ // :leave is alias to '* => void'
animate(500, style({opacity:0}))
])
])
]
Do not forget to add imports
import {style, state, animate, transition, trigger} from '@angular/animations';
The relevant component's html's element should look like:
<div *ngIf="toggle" [@fadeInOut]>element</div>
I built example of slide and fade animation here.
Explanation on 'void' and '*':
void
is the state when ngIf
is set to false (it applies when the
element is not attached to a view).*
- There can be many animation states (read more in docs). The *
state takes precedence over all of them as a "wildcard" (in my example this is the state when ngIf
is set to true
).Notice (taken from angular docs):
Extra declare inside the app module,
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
Angular animations are built on top of the standard Web Animations API and run natively on browsers that support it. For other browsers, a polyfill is required. Grab web-animations.min.js from GitHub and add it to your page.
There's an alternative to the StopIteration
by using next(iterator, default_value)
.
For exapmle:
>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None
So you can detect for None
or other pre-specified value for end of the iterator if you don't want the exception way.
Bash also supports a +=
operator as shown in this code:
A="X Y"
A+=" Z"
echo "$A"
output
X Y Z
One object may contain another as a part of its attribute.
So containment need not be physical. e.g., computer system has a warranty.
We are using MongoDB in production in our mobile backend service namely Netmera. We are using it to store all user and content data.
If you want to set $_POST['text'] to another value, why not use:
$_POST['text'] = $var;
on next.php?
Here's my general-purpose function for this. It returns a list of file paths rather than filenames since I found that to be more useful. It has a few optional arguments that make it versatile. For instance, I often use it with arguments like pattern='*.txt'
or subfolders=True
.
import os
import fnmatch
def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
"""Return a list of the file paths matching the pattern in the specified
folder, optionally including files inside subfolders.
"""
match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
return [os.path.join(root, f)
for root, dirnames, filenames in walked
for f in filenames if match(f, pattern)]
Open your workspace\.metadata\.log
file. That will tell you usually what is going wrong.
To complete @cpu-100 answer,
in case you don't want to enable/use web interface, you can create a new credentials using command line like below and use it in your code to connect to RabbitMQ.
$ rabbitmqctl add_user YOUR_USERNAME YOUR_PASSWORD
$ rabbitmqctl set_user_tags YOUR_USERNAME administrator
$ rabbitmqctl set_permissions -p / YOUR_USERNAME ".*" ".*" ".*"
function isEqual(a) {
if (arrayData.length > 0) {
for (var i in arrayData) {
if (JSON.stringify(arrayData[i]) === JSON.stringify(a)) {
alert("Ya existe un registro con esta informacion");
return false;
}
}
}
}
Field.CurrentPage only works for Filter fields (also called page fields).
If you want to filter a row/column field, you have to cycle through the individual items, like so:
Sub FilterPivotField(Field As PivotField, Value)
Application.ScreenUpdating = False
With Field
If .Orientation = xlPageField Then
.CurrentPage = Value
ElseIf .Orientation = xlRowField Or .Orientation = xlColumnField Then
Dim i As Long
On Error Resume Next ' Needed to avoid getting errors when manipulating PivotItems that were deleted from the data source.
' Set first item to Visible to avoid getting no visible items while working
.PivotItems(1).Visible = True
For i = 2 To Field.PivotItems.Count
If .PivotItems(i).Name = Value Then _
.PivotItems(i).Visible = True Else _
.PivotItems(i).Visible = False
Next i
If .PivotItems(1).Name = Value Then _
.PivotItems(1).Visible = True Else _
.PivotItems(1).Visible = False
End If
End With
Application.ScreenUpdating = True
End Sub
Then, you would just call:
FilterPivotField ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode"), "K123223"
Naturally, this gets slower the more there are individual different items in the field. You can also use SourceName instead of Name if that suits your needs better.
I prefer the next hint:
having the matrix named matrix_a
and use column_number
, for example:
import numpy as np
matrix_a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
column_number=2
# you can get the row from transposed matrix - it will be a column:
col=matrix_a.transpose()[column_number]
If you are building a python package distribution in a .gitlab-ci.yml file in for GitLab CI that uses a gitlab runner deployed in an AWS EC2 machine
- apk add --update alpine-sdk && \
- apk add libffi-dev openssl-dev && \
- apk --no-cache --update add build-base
Using the Drag and Drop method
cmd
to pull up the windows bar operation.Open File Location
.Copy to Desktop
while dragging and before dropping, then push down and hold the Control key until you see the message. There's a proposed feature which you could use for arbitrarily shaped drop shadows. You could see it here, courtesy of Lea Verou:
http://www.netmagazine.com/features/hot-web-standards-css-blending-modes-and-filters-shadow-dom
Browser support is minimal, though.
The best approach is using a lambda within "array_walk" native function to make the required changes:
array_walk($data, function (&$value, $key) {
if($key == 'transaction_date'){
$value = date('d/m/Y', $value);
}
});
The value is updated in the array as it's passed with as a reference "&".
If anyone else ends up breaking their proxy config settings go to your .npmrc, to type in the settings. This file is located at your node root folder level.
Here's whats my corrected file looks like:
#proxy = http://proxy.company.com:8080
https-proxy = https://proxy.company.com:8080
registry = http://registry.npmjs.org/
You can achieve the same using
<select [ngModel]="object">
<option *ngFor="let object of objects;let i= index;" [value]="object.value" selected="i==0">{{object.name}}</option>
</select>
Another alternative is to use a lambda:
ent.bind("<Return>", (lambda event: name_of_function()))
Full code:
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title="Reply", message = "Hello %s!" % name)
top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
As you can see, creating a lambda function with an unused variable "event" solves the problem.
Most of the answers here are more or less related to application programming. Here is an example from embedded systems programming. For example below is an excerpt from the reference manual of NXP's Kinetis KL13 series microcontroller, this code snippet is used to run bootloader, which resides in ROM, from firmware:
" To get the address of the entry point, the user application reads the word containing the pointer to the bootloader API tree at offset 0x1C of the bootloader's vector table. The vector table is placed at the base of the bootloader's address range, which for the ROM is 0x1C00_0000. Thus, the API tree pointer is at address 0x1C00_001C.
The bootloader API tree is a structure that contains pointers to other structures, which have the function and data addresses for the bootloader. The bootloader entry point is always the first word of the API tree. "
uint32_t runBootloaderAddress;
void (*runBootloader)(void * arg);
// Read the function address from the ROM API tree.
runBootloaderAddress = **(uint32_t **)(0x1c00001c);
runBootloader = (void (*)(void * arg))runBootloaderAddress;
// Start the bootloader.
runBootloader(NULL);
Try with setPreferredSize
instead of setSize
.
UPDATE: GridLayout
take up all space in its container, and BoxLayout
seams to take up all the width in its container, so I added some glue-panels that are invisible and just take up space when the user stretches the window. I have just done this horizontally, and not vertically, but you could implement that in the same way if you want it.
Since GridLayout
make all cells in the same size, it doesn't matter if they have a specified size. You have to specify a size for its container instead, as I have done.
import javax.swing.*;
import java.awt.*;
public class PanelModel {
public static void main(String[] args) {
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel(new GridLayout(4, 4));
firstPanel.setPreferredSize(new Dimension(4*100, 4*100));
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
firstPanel.add(new JButton());
}
}
JPanel firstGluePanel = new JPanel(new BorderLayout());
firstGluePanel.add(firstPanel, BorderLayout.WEST);
firstGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
firstGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);
JPanel secondPanel = new JPanel(new GridLayout(13, 5));
secondPanel.setPreferredSize(new Dimension(5*40, 13*40));
for (int i=1; i<=5; i++) {
for (int j=1; j<=13; j++) {
secondPanel.add(new JButton());
}
}
JPanel secondGluePanel = new JPanel(new BorderLayout());
secondGluePanel.add(secondPanel, BorderLayout.WEST);
secondGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
secondGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);
mainPanel.add(firstGluePanel);
mainPanel.add(secondGluePanel);
frame.getContentPane().add(mainPanel);
//frame.setSize(400,600);
frame.pack();
frame.setVisible(true);
}
}
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
?>
Try this example and see if it fits your needs, there are three main aspects to it.
Line.Stretch is set to fill.
For horizontal lines the VerticalAlignment of the line is set Bottom, and for VerticalLines the HorizontalAlignment is set to Right.
We then need to tell the line how many rows or columns to span, this is done by binding to either RowDefinitions or ColumnDefintions count property.
<Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">
<Setter Property="X2" Value="1" />
<Setter Property="VerticalAlignment" Value="Bottom" />
<Setter Property="Grid.ColumnSpan"
Value="{Binding
Path=ColumnDefinitions.Count,
RelativeSource={RelativeSource AncestorType=Grid}}"/>
</Style>
<Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">
<Setter Property="Y2" Value="1" />
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="Grid.RowSpan"
Value="{Binding
Path=RowDefinitions.Count,
RelativeSource={RelativeSource AncestorType=Grid}}"/>
</Style>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Line Grid.Column="0" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Column="1" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Column="2" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Column="3" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Row="0" Style="{StaticResource horizontalLineStyle}"/>
<Line Grid.Row="1" Style="{StaticResource horizontalLineStyle}"/>
<Line Grid.Row="2" Style="{StaticResource horizontalLineStyle}"/>
<Line Grid.Row="3" Style="{StaticResource horizontalLineStyle}"/>
When you try to set text in Edittext
or textview
you
should pass only String format.
dateTime.setText(app.getTotalDl());
to
dateTime.setText(String.valueOf(app.getTotalDl()));
Simply do this:
IF EXISTS (SELECT * FROM tablename)
BEGIN
DELETE from tablename
DBCC checkident ('tablename', reseed, 0)
END
You can use the standard MaterialCard
included in the official Material Components library.
Use in your layout:
<com.google.android.material.card.MaterialCardView
style="@style/MyCardView"
...>
In your style use the shapeAppearanceOverlay
attribute to customize the shape (the default corner radius is 4dp
)
<style name="MyCardView" parent="@style/Widget.MaterialComponents.CardView">
<item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MaterialCardView.Cut</item>
</style>
<style name="ShapeAppearanceOverlay.MaterialCardView.Cut" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSizeTopRight">8dp</item>
<item name="cornerSizeTopLeft">8dp</item>
<item name="cornerSizeBottomRight">0dp</item>
<item name="cornerSizeBottomLeft">0dp</item>
</style>
You can also use:
<com.google.android.material.card.MaterialCardView
app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MaterialCardView.Cut"
...>
It is the result:
There are several ways to do it:
n = L[0][0]
m = len(A)
found = False
for i in range(m):
if found:
break
for j in range(m):
if L[i][j] != n:
found = True
break
Pros: easy to understand Cons: additional conditional statement for every loop
n = L[0][0]
m = len(A)
try:
for x in range(3):
for z in range(3):
if L[i][j] != n:
raise StopIteration
except StopIteration:
pass
Pros: very straightforward Cons: you use Exception outside of their semantic
def is_different_value(l, elem, size):
for x in range(size):
for z in range(size):
if l[i][j] != elem:
return True
return False
if is_different_value(L, L[0][0], len(A)):
print "Doh"
pros: much cleaner and still efficient cons: yet feels like C
def is_different_value(iterable):
first = iterable[0][0]
for l in iterable:
for elem in l:
if elem != first:
return True
return False
if is_different_value(L):
print "Doh"
pros: still clean and efficient cons: you reinvdent the wheel
any()
:def is_different_value(iterable):
first = iterable[0][0]
return any(any((cell != first for cell in col)) for elem in iterable)):
if is_different_value(L):
print "Doh"
pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you
In case you just want to know if you scroll up or down using a pointer device (mouse or track pad) you can use the deltaY property of the wheel
event.
$('.container').on('wheel', function(event) {_x000D_
if (event.originalEvent.deltaY > 0) {_x000D_
$('.result').append('Scrolled down!<br>');_x000D_
} else {_x000D_
$('.result').append('Scrolled up!<br>');_x000D_
}_x000D_
});
_x000D_
.container {_x000D_
height: 200px;_x000D_
width: 400px;_x000D_
margin: 20px;_x000D_
border: 1px solid black;_x000D_
overflow-y: auto;_x000D_
}_x000D_
.content {_x000D_
height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="content">_x000D_
Scroll me!_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="result">_x000D_
<p>Action:</p>_x000D_
</div>
_x000D_
An elegant method would be to use the ~=
compatible release operator according to PEP 440. In your case this would amount to:
package~=0.5.0
As an example, if the following versions exist, it would choose 0.5.9
:
0.5.0
0.5.9
0.6.0
For clarification, each pair is equivalent:
~= 0.5.0
>= 0.5.0, == 0.5.*
~= 0.5
>= 0.5, == 0.*
In addition to what is said above, you should be very aware that nolock actually imposes the risk of you not getting rows that has been committed before your select.
Take offline takes a while and sometimes I experience some problems with that..
Most solid way in my opinion:
Detach Right click DB -> Tasks -> Detach... check "Drop Connections" Ok
Reattach Right click Databases -> Attach.. Add... -> select your database, and change the Attach As column to your desired database name. Ok
global $post;
echo $post->ID;
I suppose you're probably using the Decimal()
objects from the decimal
module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)
If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:
Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?
A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
...
Inexact: None
The next question reads
Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?
If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimal
s with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with str
will work fine:
str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'
I take the below approach to remove the item in slice. This helps in readability for others. And also immutable.
func remove(items []string, item string) []string {
newitems := []string{}
for _, i := range items {
if i != item {
newitems = append(newitems, i)
}
}
return newitems
}
Update 2: My solution is based on disabling the browser's native scrolling altogether (when cursor is inside the DIV) and then manually scrolling the DIV with JavaScript (by setting its .scrollTop
property). An alternative and IMO better approach would be to only selectively disable the browser's scrolling in order to prevent the page scroll, but not the DIV scroll. Check out Rudie's answer below which demonstrates this solution.
Here you go:
$( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
var e0 = e.originalEvent,
delta = e0.wheelDelta || -e0.detail;
this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
e.preventDefault();
});
Live demo: https://jsbin.com/howojuq/edit?js,output
So you manually set the scroll position and then just prevent the default behavior (which would be to scroll the DIV or whole web-page).
Update 1: As Chris noted in the comments below, in newer versions of jQuery, the delta information is nested within the .originalEvent
object, i.e. jQuery does not expose it in its custom Event object anymore and we have to retrieve it from the native Event object instead.
Use padding to fake it since vertical-align doesn't work on text inputs.
CSS
.date-input {
width: 145px;
padding-top: 80px;
}?
you can use Word Mover's Distance algorithm. here is an easy description about WMD.
#load word2vec model, here GoogleNews is used
model = gensim.models.KeyedVectors.load_word2vec_format('../GoogleNews-vectors-negative300.bin', binary=True)
#two sample sentences
s1 = 'the first sentence'
s2 = 'the second text'
#calculate distance between two sentences using WMD algorithm
distance = model.wmdistance(s1, s2)
print ('distance = %.3f' % distance)
P.s.: if you face an error about import pyemd library, you can install it using following command:
pip install pyemd
What is the purpose of a module system?
It accomplishes the following things:
Having modules makes it easier to find certain parts of code which makes our code more maintainable.
How does it work?
NodejS
uses the CommomJS module system which works in the following manner:
module.export
syntaxrequire('file')
syntaxtest1.js
const test2 = require('./test2'); // returns the module.exports object of a file
test2.Func1(); // logs func1
test2.Func2(); // logs func2
test2.js
module.exports.Func1 = () => {console.log('func1')};
exports.Func2 = () => {console.log('func2')};
require()
is called on the same module the is pulled from the cache.require()
right away.We have some generic playbooks that are usable by a large number of teams. We also have environment specific inventory files, that contain multiple group declarations.
To force someone calling a playbook to specify a group to run against, we seed a dummy entry at the top of the playbook:
[ansible-dummy-group]
dummy-server
We then include the following check as a first step in the shared playbook:
- hosts: all
gather_facts: False
run_once: true
tasks:
- fail:
msg: "Please specify a group to run this playbook against"
when: '"dummy-server" in ansible_play_batch'
If the dummy-server shows up in the list of hosts this playbook is scheduled to run against (ansible_play_batch), then the caller didn't specify a group and the playbook execution will fail.
I think the simplest way to use the newest version of Node.js is to get the newest Node.js pkg file in the website https://nodejs.org/en/download/current/ if you want to use different version of Node.js you can use nvm or n to manage it.
This issue is probably because of the earlier versions of Java installed in your System. First check your Environment Variables Carefully and remove all the Environment Variables related to the previous versions of JAVA and replace those paths to
C:\Program Files\Java\<your new jdk version>\bin
I have figured out that I can convert the keyCode of the event to a character by using the following function:
var char = String.fromCharCode(v_code);
From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).
Thanks for all your help guys.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<h4 align="center">
<a href="Demo2.html">Center</a>
</h4>
</body>
</html>
In my opinion, it's a way to implement currying in python.
from functools import partial
def add(a,b):
return a + b
def add2number(x,y,z):
return x + y + z
if __name__ == "__main__":
add2 = partial(add,2)
print("result of add2 ",add2(1))
add3 = partial(partial(add2number,1),2)
print("result of add3",add3(1))
The result is 3 and 4.
Is the file being blocked? I had the same issue and was able to resolve it by right clicking the .PS1 file, Properties and choosing Unblock.
document.getElementById('tries').scrollIntoView()
works. This works better than window.location.hash
when you have fixed positioning.
Using .net
[int]$b = $null #used after as refence
$b
0
[int32]::TryParse($a , [ref]$b ) # test if is possible to cast and put parsed value in reference variable
True
$b
10
$b.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
note this (powershell coercing feature)
$a = "10"
$a + 1 #second value is evaluated as [string]
101
11 + $a # second value is evaluated as [int]
21
import java.io.IOException;
import java.lang.ProcessBuilder;
public class handlingexe {
public static void main(String[] args) throws IOException {
ProcessBuilder p = new ProcessBuilder();
System.out.println("Started EXE");
p.command("C:\\Users\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
p.start();
System.out.println("Started EXE");
}
}
I think if you logout of the previous project in git bash and then try to add those files to the new project. It will work fine
can't you just subset the columns in either df first?
[i for i in df.columns if i not in df2.columns]
dfNew = merge(df **[i for i in df.columns if i not in df2.columns]**, df2, left_index=True, right_index=True, how='outer')
you can set Focus
to a specific Cell
by setting Selected
property to true
dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;
to avoid Multiple Selection just set
dataGridView1.MultiSelect = false;
jQuery:
$('#foo').click(function() { alert('foo'); });
Or if you don't want it to follow the link href:
$('#foo').click(function() { alert('foo'); return false; });
Okay, here are the explanations.
e.keyCode - used to get the number that represents the key on the keyboard
e.charCode - a number that represents the unicode character of the key on keyboard
e.which - (jQuery specific) is a property introduced in jQuery (DO Not use in plain javascript)
Below is the code snippet to get the keyCode and charCode
<script>
// get key code
function getKey(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
alert(keyCode);
}
// get char code
function getChar(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
var typedChar = String.fromCharCode(keyCode);
alert(typedChar);
}
</script>
Live example of Getting keyCode and charCode in JavaScript.
Swift 3.0
With Swift 3, the name of NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Swift 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
var requestedURL = "https://accounts.google.com/o/oauth2/token?code=" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "&grant_type=authorization_code";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(requestedURL);
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.Method = "POST";
//Set content length to 0
authRequest.ContentLength = 0;
WebResponse authResponseTwitter = authRequest.GetResponse();
The ContentLength
property contains the value to send as the Content-length
HTTP header with the request.
Any value other than -1 in the ContentLength
property indicates that the request uploads data and that only methods that upload data are allowed to be set in the Method property.
After the ContentLength
property is set to a value, that number of bytes must be written to the request stream that is returned by calling the GetRequestStream
method or both the BeginGetRequestStream
and the EndGetRequestStream
methods.
for more details click here
You can solve it very easily, just wrap that iframe in wrapper, and track clicks on it.
Like this:
<div id="iframe_id_wrapper">
<iframe id="iframe_id" src="http://something.com"></iframe>
</div>
And disable pointer events on iframe itself.
#iframe_id { pointer-events: none; }
After this changes your code will work like expected.
$('#iframe_id_wrapper').click(function() {
//run function that records clicks
});
For those finding this question in dotnet core. I found a solution here
Code:
private void OpenUrl(string url)
{
try
{
Process.Start(url);
}
catch
{
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
For your second example, where you have to initialize a new List<T>
, one idea is to create an anonymous list, and then clear it.
var list = new[] { o, o1 }.ToList();
list.Clear();
//and you can keep adding.
while (....)
{
....
list.Add(new { Id = x, Name = y });
....
}
Or as an extension method, should be easier:
public static List<T> GetEmptyListOfThisType<T>(this T item)
{
return new List<T>();
}
//so you can call:
var list = new { Id = 0, Name = "" }.GetEmptyListOfThisType();
Or probably even shorter,
var list = new int[0].Select(x => new { Id = 0, Name = "" }).Tolist();
Without any further information, which Database etc the best we can do is something like
Sql Server
SELECT TOP 1 * FROM Table ORDER BY ID DESC
MySql
SELECT * FROM Table ORDER BY ID DESC LIMIT 1
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
You will find these methods in it:
getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()
Use a mix of these to achieve your result.
One issue with Bryan Rieger's useful answer is that on high-density displays, Apple devices report screen.width in dips, while Android devices report it in physical pixels. (See http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html .) I suggest using if (window.matchMedia('(max-device-width: 960px)').matches) {}
on browsers supporting matchMedia.
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
Use php -v //PHP 8.0.1
Check the latest version of simple xml here
https://pkgs.org/download/php-simplexml
sudo apt-get install php8.0-xml
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
The greater sign ( > ) selector in CSS means that the selector on the right is a direct descendant / child of whatever is on the left.
An example:
article > p { }
Means only style a paragraph that comes after an article.
Here is yet another approach, which was more convenient in my case (I just wanted to drop root privileges and do the rest of my script from restricted user): you can make the script restart itself from correct user. Let's suppose it is run as root initially. Then it will look like this:
#!/bin/bash
if [ $UID -eq 0 ]; then
user=$1
dir=$2
shift 2 # if you need some other parameters
cd "$dir"
exec su "$user" "$0" -- "$@"
# nothing will be executed beyond that line,
# because exec replaces running process with the new one
fi
echo "This will be run from user $UID"
...
Here is a JavaScript library which you can use for finding diff between two JavaScript objects:
Github URL: https://github.com/cosmicanant/recursive-diff
Npmjs url: https://www.npmjs.com/package/recursive-diff
You can use recursive-diff library in browser as well as Node.js. For browser, do the following:
<script type="text" src="https://unpkg.com/recursive-diff@latest/dist/recursive-diff.min.js"/>
<script type="text/javascript">
const ob1 = {a:1, b: [2,3]};
const ob2 = {a:2, b: [3,3,1]};
const delta = recursiveDiff.getDiff(ob1,ob2);
/* console.log(delta) will dump following data
[
{path: ['a'], op: 'update', val: 2}
{path: ['b', '0'], op: 'update',val: 3},
{path: ['b',2], op: 'add', val: 1 },
]
*/
const ob3 = recursiveDiff.applyDiff(ob1, delta); //expect ob3 is deep equal to ob2
</script>
Whereas in node.js you can require 'recursive-diff' module and use it like below:
const diff = require('recursive-diff');
const ob1 = {a: 1}, ob2: {b:2};
const diff = diff.getDiff(ob1, ob2);
For a completely stateless utility class in Java, I suggest the class be declared public
and final
, and have a private constructor to prevent instantiation. The final
keyword prevents sub-classing and can improve efficiency at runtime.
The class should contain all static
methods and should not be declared abstract
(as that would imply the class is not concrete and has to be implemented in some way).
The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).
The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).
Methods in the class should have appropriate names.
Methods only used by the class itself should be private.
The class should not have any non-final/non-static class fields.
The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).
Example:
public final class ExampleUtilities {
// Example Utility method
public static int foo(int i, int j) {
int val;
//Do stuff
return val;
}
// Example Utility method overloaded
public static float foo(float i, float j) {
float val;
//Do stuff
return val;
}
// Example Utility method calling private method
public static long bar(int p) {
return hid(p) * hid(p);
}
// Example private method
private static long hid(int i) {
return i * 2 + 1;
}
}
Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.
Somewhere around r59 this gets easier (rotate around x):
bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
obj.position.applyEuler(euler);
}
I think df['word'].value_counts()
should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count
should be much slower than max
. Both take some time to avoid missing values. (Compare with size
.)
In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.
One explanation might be floating point rounding issues. For example, if you could call
range(0, 0.4, 0.1)
you might expect an output of
[0, 0.1, 0.2, 0.3]
but you in fact get something like
[0, 0.1, 0.2000000001, 0.3000000001]
due to rounding issues. And since range is often used to generate indices of some sort, it's integers only.
Still, if you want a range generator for floats, you can just roll your own.
def xfrange(start, stop, step):
i = 0
while start + i * step < stop:
yield start + i * step
i += 1
I guess you are asking why is 1388516401 equal to 2014-01-01...?
There is an historical reason for that. There is a 32-bit integer variable, called time_t
, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t
will be equal to 1388516401.
This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t
will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D
grep was born to extract things:
grep -Po 'name="\K[^"]*'
test with your data:
kent$ echo '<parameter name="PortMappingEnabled" access="readWrite" type="xsd:boolean"></parameter>
<parameter name="PortMappingLeaseDuration" access="readWrite" activeNotify="canDeny" type="xsd:unsignedInt"></parameter>
<parameter name="RemoteHost" access="readWrite"></parameter>
<parameter name="ExternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="ExternalPortEndRange" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="InternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="PortMappingProtocol" access="readWrite"></parameter>
<parameter name="InternalClient" access="readWrite"></parameter>
<parameter name="PortMappingDescription" access="readWrite"></parameter>
'|grep -Po 'name="\K[^"]*'
PortMappingEnabled
PortMappingLeaseDuration
RemoteHost
ExternalPort
ExternalPortEndRange
InternalPort
PortMappingProtocol
InternalClient
PortMappingDescription
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
mvn -Dschemaname=public liquibase:update
If you're using SQL Server express, change
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/
If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.
TypeScript
function hideThumbnail():boolean{
if (/* Your criteria here */)
return true;
}
CSS:
.request-card-hidden {
display: none;
}
HTML:
<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>
A tad bit late, but I think the OP was looking for something like:
curl -K myfile.txt --trace-asci output.txt
Transparency is a property outside the color itself, also known as alpha
component. You can't code it as RGB.
If you want a transparent background, you can do this:
background: transparent;
Additionally, I don't know if it might be helpful or not but, you could set the opacity
property:
.half{
opacity: 0.5;
filter: alpha(opacity=50);
}
You need both in order to get it working in IE and all other decent browsers.
create table test (a int, b int , c int, d int);
alter table test drop column b, d;
Be aware that DROP COLUMN does not physically remove the data, and for fixed length types (int, numeric, float, datetime, uniqueidentifier etc) the space is consumed even for records added after the columns were dropped. To get rid of the wasted space do ALTER TABLE ... REBUILD
.
String str = "1,2,3,4,5,6,7,8,9,0";
String items[] = str.split(",");
int ent[] = new int[items.length];
for(i=0;i<items.length;i++){
try{
ent[i] = Integer.parseInt(items[i]);
System.out.println("#"+i+": "+ent[i]);//Para probar
}catch(NumberFormatException e){
//Error
}
}
I have just found this pretty solution:
import sys; sys.path.insert(0, '..') # add parent folder path where lib folder is
import lib.store_load # store_load is a file on my library folder
You just want some functions of that file
from lib.store_load import your_function_name
If python version >= 3.3 you do not need init.py file in the folder
This is now possible in modern browsers using localeCompare. By passing the numeric: true
option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'
. Tested in Chrome, Firefox, and IE11.
Here's an example. It returns 1
, meaning 10 goes after 2:
'10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})
For performance when sorting large numbers of strings, the article says:
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});_x000D_
var myArray = ['1_Document', '11_Document', '2_Document'];_x000D_
console.log(myArray.sort(collator.compare));
_x000D_
For many people working with node.js, a major benefit of bower is for managing dependencies that are not javascript at all. If they are working with languages that compile to javascript, npm can be used to manage some of their dependencies. however, not all their dependencies are going to be node.js modules. Some of those that compile to javascript may have weird source language specific mangling that makes passing them around compiled to javascript an inelegant option when users are expecting source code.
Not everything in an npm package needs to be user-facing javascript, but for npm library packages, at least some of it should be.
Database files cannot be reduced in size. While "repairing" database, it is only possible for mongo server to delete some of its files. If large amount of data has been deleted, mongo server will "release" (delete), during repair, some of its existing files.
If your HP-UX installation has Tcl installed, you might find it's date arithmetic very readable (unfortunately the Tcl shell does not have a nice "-e" option like perl):
dt=$(echo 'puts [clock format [clock scan yesterday] -format "%a %d/%m/%Y"]' | tclsh)
echo "yesterday was $dt"
This will handle all the daylight savings bother.
On POSIX platforms, you can use getcwd().
On Windows, you may use _getcwd(), as use of getcwd() has been deprecated.
For standard libraries, if Boost were standard enough for you, I would have suggested Boost::filesystem, but they seem to have removed path normalization from the proposal. You may have to wait until TR2 becomes readily available for a fully standard solution.
Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.
Assuming your file is named myclone.csv
and contains
workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0
this code should give you an idea or two:
>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
... column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
... for h, v in zip(headers, row):
... column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>
To get your numeric values into floats, add this
converters = [str.strip] + [float] * (len(headers) - 1)
up front, and do this
for h, v, conv in zip(headers, row, converters):
column[h].append(conv(v))
for each row instead of the similar two lines above.
While working on my internship project I found a website for this https://thezipcodes.com/ Create a free account and get the API key from account Section.
https://thezipcodes.com/api/v1/search?zipCode={zipCode}&countryCode={2digitCountryCode}&apiKey={apiKey}
I found majority of data here.
I Used Java 8 generics to get what is the object instance at runtime rather than having to use switch case
public <T> void print(T data) {
System.out.println(data.getClass().getName()+" => The data is " + data);
}
pass any type of data and the method will print the type of data you passed while calling it. eg
String str = "Hello World";
int number = 10;
double decimal = 10.0;
float f = 10F;
long l = 10L;
List list = new ArrayList();
print(str);
print(number);
print(decimal);
print(f);
print(l);
print(list);
Following is the output
java.lang.String => The data is Hello World
java.lang.Integer => The data is 10
java.lang.Double => The data is 10.0
java.lang.Float => The data is 10.0
java.lang.Long => The data is 10
java.util.ArrayList => The data is []
In your config.ini
file of eclipse eclipse\configuration\config.ini
check this three things:
osgi.framework=file\:plugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
osgi.bundles=reference\:file\:org.eclipse.equinox.simpleconfigurator_1.0.0.v20080604.jar@1\:start
org.eclipse.equinox.simpleconfigurator.configUrl=file\:org.eclipse.equinox.simpleconfigurator\\bundles.info
And check whether these jars are in place or not, the jar files depend upon your version of eclipse .
You are able to cut all odd/even columns by using seq:
This would print all odd columns
echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)
To print all even columns you could use
echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)
By changing the second number of seq you can specify which columns to be printed.
If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like
echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)
This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.
Use sortedWith
to sort a list with Comparator
.
You can then construct a comparator using several ways:
@Mahmoud Ali Kaseem
I have just changed some CSS to make it look different and added focus();
https://jsfiddle.net/xn9eogmx/81/
$('#clear').click(function() {_x000D_
$('#input-outer input').val('');_x000D_
$('#input-outer input').focus();_x000D_
});
_x000D_
body {_x000D_
font-family: "Arial";_x000D_
font-size: 14px;_x000D_
}_x000D_
#input-outer {_x000D_
height: 2em;_x000D_
width: 15em;_x000D_
border: 1px #777 solid;_x000D_
position: relative;_x000D_
padding: 0px;_x000D_
border-radius: 4px;_x000D_
}_x000D_
#input-outer input {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
border: 0px;_x000D_
outline: none;_x000D_
margin: 0 0 0 0px;_x000D_
color: #666;_x000D_
box-sizing: border-box;_x000D_
padding: 5px;_x000D_
padding-right: 35px;_x000D_
border-radius: 4px;_x000D_
}_x000D_
#clear {_x000D_
position: absolute;_x000D_
float: right;_x000D_
height: 2em;_x000D_
width: 2em;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
background: #aaa;_x000D_
color: white;_x000D_
text-align: center;_x000D_
cursor: pointer;_x000D_
border-radius: 0px 4px 4px 0px;_x000D_
}_x000D_
#clear:after {_x000D_
content: "\274c";_x000D_
position: absolute;_x000D_
top: 4px;_x000D_
right: 7px;_x000D_
}_x000D_
#clear:hover,_x000D_
#clear:focus {_x000D_
background: #888;_x000D_
}_x000D_
#clear:active {_x000D_
background: #666;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
<input type="text">_x000D_
<div id="clear"></div>_x000D_
</div>
_x000D_
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
The HTML parser simply doesn't interpret the inlined javascript like this.
You may do this :
<td><input type="checkbox" id="repriseCheckBox" name="repriseCheckBox"/></td>
<script>document.getElementById("repriseCheckBox").disabled=checkStat == 1 ? true : false;</script>
Do I really have to first convert it into an array of arrays of key-value pairs?
No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:
function* entries(obj) {
for (let key in obj)
yield [key, obj[key]];
}
const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
I create a simple function with typescript
const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);
function setDiffTimeString(diffDuration: moment.Duration) {
const str = [];
diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
console.log(str.join(', '));
}
// output: 1 day(s), 23 hour(s), 29 minute(s)
for generate javascript https://www.typescriptlang.org/play/index.html
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
To read the user input and store it in a variable, for later use, you can use SQL*Plus command ACCEPT
.
Accept <your variable> <variable type if needed [number|char|date]> prompt 'message'
example
accept x number prompt 'Please enter something: '
And then you can use the x
variable in a PL/SQL block as follows:
declare
a number;
begin
a := &x;
end;
/
Working with a string example:
accept x char prompt 'Please enter something: '
declare
a varchar2(10);
begin
a := '&x'; -- for a substitution variable of char data type
end; -- to be treated as a character string it needs
/ -- to be enclosed with single quotation marks
If you need to remove just trailing whitespace, you could use str.rstrip()
, which should be slightly more efficient than str.strip()
:
>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']
By this you can get any index in *ngFor
loop in ANGULAR ...
<ul>
<li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
<div *ngIf="first">
// write your code...
</div>
<div *ngIf="last">
// write your code...
</div>
</li>
</ul>
We can use these alias in *ngFor
index
: number
: let i = index
to get all index of object.first
: boolean
: let first = first
to get first index of object.last
: boolean
: let last = last
to get last index of object.odd
: boolean
: let odd = odd
to get odd index of object.even
: boolean
: let even = even
to get even index of object.You can declare local variables in MySQL triggers, with the DECLARE
syntax.
Here's an example:
DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
i SERIAL PRIMARY KEY
);
DELIMITER //
DROP TRIGGER IF EXISTS bar //
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = NEW.i;
SET @a = x; -- set user variable outside trigger
END//
DELIMITER ;
SET @a = 0;
SELECT @a; -- returns 0
INSERT INTO foo () VALUES ();
SELECT @a; -- returns 1, the value it got during the trigger
When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row
".
You can use LIMIT
or MAX()
to make sure that the local variable is set to a single value.
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = (SELECT age FROM users WHERE name = 'Bill');
-- ERROR 1242 if more than one row with 'Bill'
END//
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
-- OK even when more than one row with 'Bill'
END//
You could try:
#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/
for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
cd "$f"
<your job here>
done
or similar...
Explanation:
find . -maxdepth 1 -mindepth 1 -type d
:
Only find directories with a maximum recursive depth of 1 (only the subdirectories of $1) and minimum depth of 1 (excludes current folder .
)
I was looking at the same statistics problems. The approach you are thinking it is good and it will work. (Answer to the sorting has been given)
But in case you are interested in algorithm performance, I think there are a couple of algorithms that have better performance than just sorting the array, one (QuickSelect) is indicated by @bruce-feist's answer and is very well explained.
[Java implementation: https://discuss.leetcode.com/topic/14611/java-quick-select ]
But there is a variation of this algorithm named median of medians, you can find a good explanation on this link: http://austinrochford.com/posts/2013-10-28-median-of-medians.html
Java implementation of this: - https://stackoverflow.com/a/27719796/957979
Yes, you can use any of these popular tools:
This class will help and then initialize the class with the init method.
import 'package:flutter/widgets.dart';
class SizeConfig {
static MediaQueryData _mediaQueryData;
static double screenWidth;
static double screenHeight;
static double blockSizeHorizontal;
static double blockSizeVertical;
static double _safeAreaHorizontal;
static double _safeAreaVertical;
static double safeBlockHorizontal;
static double safeBlockVertical;
void init(BuildContext context){
_mediaQueryData = MediaQuery.of(context);
screenWidth = _mediaQueryData.size.width;
screenHeight = _mediaQueryData.size.height;
blockSizeHorizontal = screenWidth/100;
blockSizeVertical = screenHeight/100;
_safeAreaHorizontal = _mediaQueryData.padding.left +
_mediaQueryData.padding.right;
_safeAreaVertical = _mediaQueryData.padding.top +
_mediaQueryData.padding.bottom;
safeBlockHorizontal = (screenWidth - _safeAreaHorizontal)/100;
safeBlockVertical = (screenHeight - _safeAreaVertical)/100;
}
}
then in your widgets dimension do this
Widget build(BuildContext context) {
SizeConfig().init(context);
return Container(
height: SizeConfig.safeBlockVertical * 10, //10 for example
width: SizeConfig.safeBlockHorizontal * 10, //10 for example
);}
All the credits to this post author: https://medium.com/flutter-community/flutter-effectively-scale-ui-according-to-different-screen-sizes-2cb7c115ea0a
You should chain the replace() together instead of assigning the result and replacing again.
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
.replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
.replace(/.bbbbbb/g,'/world\">Helloworld</a>');
See DEMO.
FYI, for the cases where your page is loading with other javascript libraries like mootools that are conflicting with the $
symbol, you can use jQuery
instead.
For instance, jQuery.fn.jquery
or jQuery().jquery
would work just fine:
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
MS Access - joining tables in an update query... how to make it updatable
Or you could write your own function for it (which is what I ended up doing).
function Join-Path-Recursively($PathParts) {
$NumberOfPathParts = $PathParts.Length;
if ($NumberOfPathParts -eq 0) {
return $null
} elseif ($NumberOfPathParts -eq 1) {
return $PathParts[0]
} else {
return Join-Path -Path $PathParts[0] -ChildPath $(Join-Path-Recursively -PathParts $PathParts[1..($NumberOfPathParts-1)])
}
}
You could then call the function like this:
Join-Path-Recursively -PathParts @("C:", "Program Files", "Microsoft Office")
Join-Path-Recursively @("C:", "Program Files", "Microsoft Office")
This has the advantage of having the exact same behaviour as the normal Join-Path function and not depending on the .NET Framework.
You can use a native Filter Validator
filter_var($url, FILTER_VALIDATE_URL);
Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto:. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.
Example:
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
die('Not a valid URL');
}
I had this same error, even when I only had one child under the TouchableHighlight
. The issue was that I had a few others commented out but incorrectly. Make sure you are commenting out appropriately: http://wesbos.com/react-jsx-comments/
You do not have any elements in the list so can't access the first element.
They are stored in the CGI fieldstorage object.
import cgi
form = cgi.FieldStorage()
print "The user entered %s" % form.getvalue("uservalue")
An example on how to use that would be great. There is a couple of examples at the Qt forum, but you're right that the official documentation should be expanded.
QJsonDocument
on its own indeed doesn't produce anything, you will have to add the data to it. That's done through the QJsonObject
, QJsonArray
and QJsonValue
classes. The top-level item needs to be either an array or an object (because 1
is not a valid json document, while {foo: 1}
is.)
Workbooks.Open
does work too.
Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", Local:=True
this works/is needed because i use Excel in germany and excel does use "," to separate .csv by default because i use an english installation of windows. even if you use the code below excel forces the "," separator.
Workbooks.Open ActiveWorkbook.Path & "\Test.csv", , , 6, , , , , ";"
and Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", , , 4
+variants of this do not work(!)
why do they even have the delimiter parameter if it is blocked by the Local parameter ?! this makes no sense at all. but now it works.
My answer is a mod of some prior answers from @JoeMills and @user.
Get a cURL
command to log into server:
Modify cURL command to be able to save session cookie after login
-H 'Cookie: <somestuff>'
curl
at beginning -c login_cookie.txt
'login_cookie.txt'
in the same folderCall a new web page using this new cookie that requires you to be logged in
curl -b login_cookie.txt <url_that_requires_log_in>
I have tried this on Ubuntu 20.04 and it works like a charm.
A vertical tab was the opposite of a line feed i.e. it went upwards by one line. It had nothing to do with tab positions. If you want to prove this, try it on an RS232 terminal.
This URL return to player actual video_id
https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA
Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.
Integer has no method length. Try string
var testvar={};
testvar[1]="2";
alert(testvar[1].length);
Under browsers supporting js 1.8:
[i for(i in obj)]
If you change your html code a bit - remove the ids
<ul id='myid'>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
Then the jquery code you want is...
$("#myid li").click(function() {
alert($(this).prevAll().length+1);
});?
You don't need to place any ids, just keep on adding li items.
Take a look at demo
Useful links
1,1:
select 1 from dual
union all select 1 from dual
1:
select 1 from dual
union select 1 from dual
Instead of ISNULL()
, use NVL()
.
T-SQL:
SELECT ISNULL(SomeNullableField, 'If null, this value') FROM SomeTable
PL/SQL:
SELECT NVL(SomeNullableField, 'If null, this value') FROM SomeTable
First initialize Property values
MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());
DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);
context.registerBeanDefinition("beanName", connectionFactory);
Add to the list of beans
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));
As a continues to @chaokunyang answer, I want to put here the script I write that does the work:
"requirements.txt" file
docker==4.4.0
Packer side: file name: "create-offline-python3.6-dependencies-repository.sh"
#!/usr/bin/env bash
# This script follows the steps described in this link:
# https://stackoverflow.com/a/51646354/8808983
LIBRARIES_DIR="python3.6-wheelhouse"
if [ -d ${LIBRARIES_DIR} ]; then
rm -rf ${LIBRARIES_DIR}/*
else
mkdir ${LIBRARIES_DIR}
fi
pip download -r requirements.txt -d ${LIBRARIES_DIR}
files_to_add=("requirements.txt" "install-python-libraries-offline.sh")
for file in "${files_to_add[@]}"; do
echo "Adding file ${file}"
cp "$file" ${LIBRARIES_DIR}
done
tar -cf ${LIBRARIES_DIR}.tar ${LIBRARIES_DIR}
Installer side: file name: "install-python-libraries-offline.sh"
#!/usr/bin/env bash
# This script follows the steps described in this link:
# https://stackoverflow.com/a/51646354/8808983
# This file should run during the installation process from inside the libraries directory, after it was untared:
# pythonX-wheelhouse.tar -> untar -> pythonX-wheelhouse
# |
# |--requirements.txt
# |--install-python-libraries-offline.sh
pip3 install -r requirements.txt --no-index --find-links .
Best practice is to mark function async void
only if it is fire and forget method, if you want to await on, you should mark it as async Task
.
In case if you still want to await, then wrap it like so await Task.Run(() => blah())
Docotic.Pdf library may be used to accomplish the task.
Here is sample code:
PdfDocument document = new PdfDocument();
document.Open("file.pdf");
int pageCount = document.PageCount;
The library will parse as little as possible so performance should be ok.
Disclaimer: I work for Bit Miracle.
There is a version of string.Split
that takes an array of strings and a StringSplitOptions
parameter:
Why do you use new Date instead of a static UTC string?
function clearListCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++){
var spcook = cookies[i].split("=");
document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";
}
}
You just declare the property the normal way using a generic type:
public MyType<string> PropertyName { get; set; }
If you want to call predefined methods to do something in the get or set, implement the property getter/setter to call those methods.
Am I missing something? You can just convert offer_date in the comparison:
SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
offer_rate > 0
Thanks @AkhlD and @Sachin Janani for suggesting changes in .conf
file.
Following code solved my issue:
1) Added import org.apache.log4j.{Level, Logger}
in import section
2) Added following line after creation of spark context object i.e. after val sc = new SparkContext(conf)
:
val rootLogger = Logger.getRootLogger()
rootLogger.setLevel(Level.ERROR)
Try this option which I can see is not yet listed above :
<a href="" ng-click="do()">Click</a>
You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.
I've just done this in a grunt
project of ours. We needed a newer version of connect, since 2.7.3
. was causing trouble for us. So I created a file named npm-shrinkwrap.json
:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "[email protected]",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect@~2.7.3"
}
}
}
}
}
npm
should automatically pick it up while doing the install for the project.
(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)
You can do it by making form and displaying it using ShowDialogBox....
Form.ShowDialog Method
- Shows the form as a modal dialog box.
Example:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
Jest documentation recommends the following:
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. In Jest it's simple to run only one test - just temporarily change that
test
command to atest.only
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
or
it.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
No idea if this will work or not but my only thought so far: right click the jar file in file tree within AS and select "Add as library..."
EDIT: You can do "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.
EDIT 2: This fix should work for all similar incidents and is not a twitter4j specific resolution.
HTML4/XHTML1 requires
<script type="...">...</script>
HTML5 faces the fact that there is only one scripting language on the web, and allows
<script>...</script>
The latter works in any browser that supports scripting (NN2+).
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
I had the exact same question as you had and I think I should share how I started to understand it by a few really simple examples (note that it only covers the common use cases).
There are two common use cases in Scala using implicit
.
Examples are as follows
Using it on a variable. As you can see, if the implicit
keyword is used in the last parameter list, then the closest variable will be used.
// Here I define a class and initiated an instance of this class
case class Person(val name: String)
val charles: Person = Person("Charles")
// Here I define a function
def greeting(words: String)(implicit person: Person) = person match {
case Person(name: String) if name != "" => s"$name, $words"
case _ => "$words"
}
greeting("Good morning") // Charles, Good moring
val charles: Person = Person("")
greeting("Good morning") // Good moring
Using it on a function. As you can see, if the implicit
is used on the function, then the closest type conversion method will be used.
val num = 10 // num: Int (of course)
// Here I define a implicit function
implicit def intToString(num: Int) = s"$num -- I am a String now!"
val num = 10 // num: Int (of course). Nothing happens yet.. Compiler believes you want 10 to be an Int
// Util...
val num: String = 10 // Compiler trust you first, and it thinks you have `implicitly` told it that you had a way to covert the type from Int to String, which the function `intToString` can do!
// So num is now actually "10 -- I am a String now!"
// console will print this -> val num: String = 10 -- I am a String now!
Hope this can help.
An easy way to serialize Enum is using @JsonFormat annotation. @JsonFormat can configure the serialization of a Enum in three ways.
@JsonFormat.Shape.STRING
public Enum OrderType {...}
uses OrderType::name as the serialization method. Serialization of OrderType.TypeA is “TYPEA”
@JsonFormat.Shape.NUMBER
Public Enum OrderTYpe{...}
uses OrderType::ordinal as the serialization method. Serialization of OrderType.TypeA is 1
@JsonFormat.Shape.OBJECT
Public Enum OrderType{...}
treats OrderType as a POJO. Serialization of OrderType.TypeA is {"id":1,"name":"Type A"}
JsonFormat.Shape.OBJECT is what you need in your case.
A little more complicated way is your solution, specifying a serializer for the Enum.
Check out this reference: https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.html
I suppose this would help:
<%!
String someOutput() {
return "Some Output";
}
%>
...
<%= someOutput() %>
Anyway, it isn't a good idea to have code in a view.
In my case, IIS suddenly stoped working, and after that Windows process activation service was unable to restart.
The solution to fix this was:
Hope it will be usefull.
You can execute
git status -s
This will show modified files name and then by copying the interested file path you can see changes using git diff
git diff <filepath + filename>
Wrong. That doesn't work for me.
For me this one works:
curl
-H 'SOAPACTION: "urn:samsung.com:service:MainTVAgent2:1#CheckPIN"'
-X POST
-H 'Content-type: text/xml'
-d @/tmp/pinrequest.xml
192.168.1.5:52235/MainTVServer2/control/MainTVAgent2
The PATCH
method is the correct choice here as you're updating an existing resource - the group ID. PUT
should only be used if you're replacing a resource in its entirety.
Further information on partial resource modification is available in RFC 5789. Specifically, the PUT
method is described as follows:
Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.
Check out section 5.14.2. Moving files and folders (or check out "move" in the Index of the help) of the TortoiseSVN help. You do a move via right-dragging. It also mentions that you need to commit from the parent folder to make it "one" revision. This works for doing the change in a working copy.
(Note that the SVN items in the following image will only show up if the destination folder has already been added to the repository.)
You can also do the move via the Repo Browser (section 5.23. The Repository Browser of the help).
I faced the same problem and I've found a pretty clean solution: After Html.fromHtml() you can run an AsyncTask that iterates over all the tags, fetches the images and then displays them.
Here you can find some code that you can use (but it needs some customization): https://gist.github.com/1190397
You should refer to the current element and not all elements matching your selector.
$("#mainMenu td").click(function() {
$(this).css('background-color', '#EDEDED');
});
I´d also recommend you to use CSS classes instead of setting the CSS properties this way.
That would be something like;
$("#mainMenu td").click(function() {
$(this).addClass('selected');
});
together with;
#mainMenu td.selected {
background-color: #EDEDED; }
this will send a form with preloader :
var a=$('#yourform').serialize();
$.ajax({
type:'post',
url:'receiver url',
data:a,
beforeSend:function(){
launchpreloader();
},
complete:function(){
stopPreloader();
},
success:function(result){
alert(result);
}
});
i'have some trick to make a form data post reformed with random method http://www.jackart4.com/article.html
str.contains("!=") ^ str.startsWith("not(")
looks better for me than
str.contains("!=") != str.startsWith("not(")
You can get rid of the first line. You don't need import java.lang.*;
Just change your 5th line to:
public static void main(String [] args) throws Exception
If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test
rather than the default unittest
module.
Consider these two examples, which do the same thing:
Example 1 (unittest):
import unittest
class LearningCase(unittest.TestCase):
def test_starting_out(self):
self.assertEqual(1, 1)
def main():
unittest.main()
if __name__ == "__main__":
main()
Example 2 (pytest):
def test_starting_out():
assert 1 == 1
Assuming that both files are named test_unittesting.py
, how do we run the tests?
Example 1 (unittest):
cd /path/to/dir/
python test_unittesting.py
Example 2 (pytest):
cd /path/to/dir/
py.test
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
In eclipse click file then select switch workspace then browse and select another folder. Now repeat the same process and this time there will be no error :)
Use substring()
and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
A parallel can be made of fractions and whole numbers. Some fractions eg 1/7 cannot be represented in decimal form without lots and lots of decimals. Because floating point is binary based the special cases change but the same sort of accuracy problems present themselves.
On my 10.6 system:
vhosts folder:
owner:root
group:wheel
permissions:755
vhost.conf files:
owner:root
group:wheel
permissions:644
@STEVER's answer is satisfactory. However, I thought it may be useful to post a slightly different approach. I use a method called isValue which returns true for all values except null, undefined, NaN, and Infinity. Lumping in NaN with null and undefined is the real benefit of the function for me. Lumping Infinity in with null and undefined is more debatable, but frankly not that interesting for my code because I practically never use Infinity.
The following code is inspired by Y.Lang.isValue. Here is the source for Y.Lang.isValue.
/**
* A convenience method for detecting a legitimate non-null value.
* Returns false for null/undefined/NaN/Infinity, true for other values,
* including 0/false/''
* @method isValue
* @static
* @param o The item to test.
* @return {boolean} true if it is not null/undefined/NaN || false.
*/
angular.isValue = function(val) {
return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
};
Or as part of a factory
.factory('lang', function () {
return {
/**
* A convenience method for detecting a legitimate non-null value.
* Returns false for null/undefined/NaN/Infinity, true for other values,
* including 0/false/''
* @method isValue
* @static
* @param o The item to test.
* @return {boolean} true if it is not null/undefined/NaN || false.
*/
isValue: function(val) {
return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
};
})
use
pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();
will give result as yourcontent
as is
This code is write on your form load. It display all the Tour in database when user type letter in combo box. This code automatically suggest and append the right choice as user want.
con.Open();
cmd = new SqlCommand("SELECT DISTINCT Tour FROM DetailsTB", con);
SqlDataReader sdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sdr);
combo_search2.DisplayMember = "Tour";
combo_search2.DroppedDown = true;
List<string> list = new List<string>();
foreach (DataRow row in dt.Rows)
{
list.Add(row.Field<string>("Tour"));
}
this.combo_search2.Items.AddRange(list.ToArray<string>());
combo_search2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
combo_search2.AutoCompleteSource = AutoCompleteSource.ListItems;
con.Close();
I ran into this issue, and while it's true that ~/.npm
should be owned by your user, npm
was not installing the modules there.
What actually solved my issue is this command:
npm config set prefix ~/.npm
It will make sure that all your global installation will go under this prefix. And it's important that your user owns this directory.
you can also use .between()
method
emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp[emp["Salary"].between(60000, 61000)]
Output
there is also another way to resolve this issue. lets say you have two tables Table1 and Table2. and it is required to fetch all entries of Table1 not referred/present in Table2 using Criteria query. So go ahead like this...
List list=new ArrayList();
Criteria cr=session.createCriteria(Table1.class);
cr.add(Restrictions.sqlRestriction("this_.id not in (select t2.t1_id from Table2 t2 )"));
.
.
. . . It will perform all the subquery function directly in SQL without including 1000 or more parameters in SQL converted by Hibernate framework. It worked for me. Note: You may need to change SQL portion as per your requirement.
Others are correct in saying that setting button.enabled = false
doesn't prevent the button from triggering. However, I found that setting button.visible = false
does work. The button disappears and can't be clicked until you set visible
to true
again.
string Folder = Directory.GetParent(path).Name;
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
Alternatively, you can also use a special function known as the linear-gradient() function to split browser screen into two equal halves. Check out the following code snippet:
body
{
background-image:linear-gradient(90deg, lightblue 50%, skyblue 50%);
}
Here, linear-gradient() function accepts three arguments
90deg
for vertical division of screen.( Similarly, you can use 180deg
for horizontal division of screen)lightblue
color is used to represent the left half of the screen.skyblue
color has been used to represent the right half of the split screen.
Here, 50%
has been used for equal division of the browser screen. You can use any other value if you don't want an equal division of the screen.
Hope this helps. :)
Happy Coding!The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
NSE website has changed and the older scripts are semi-optimum to current website. This snippet can gather daily details of security. Details include symbol, security type, previous close, open price, high price, low price, average price, traded quantity, turnover, number of trades, deliverable quantities and ratio of delivered vs traded in percentage. These conveniently presented as list of dictionary form.
from requests import get
from csv import DictReader
from bs4 import BeautifulSoup as Soup
from datetime import date
from io import StringIO
SECURITY_NAME="3MINDIA" # Change this to get quote for another stock
START_DATE= date(2017, 1, 1) # Start date of stock quote data DD-MM-YYYY
END_DATE= date(2017, 9, 14) # End date of stock quote data DD-MM-YYYY
BASE_URL = "https://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?symbol={security}&segmentLink=3&symbolCount=1&series=ALL&dateRange=+&fromDate={start_date}&toDate={end_date}&dataType=PRICEVOLUMEDELIVERABLE"
def getquote(symbol, start, end):
start = start.strftime("%-d-%-m-%Y")
end = end.strftime("%-d-%-m-%Y")
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Referer': 'https://cssspritegenerator.com',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
url = BASE_URL.format(security=symbol, start_date=start, end_date=end)
d = get(url, headers=hdr)
soup = Soup(d.content, 'html.parser')
payload = soup.find('div', {'id': 'csvContentDiv'}).text.replace(':', '\n')
csv = DictReader(StringIO(payload))
for row in csv:
print({k:v.strip() for k, v in row.items()})
if __name__ == '__main__':
getquote(SECURITY_NAME, START_DATE, END_DATE)
Besides this is relatively modular and ready to use snippet.
Sorry late to the party, but here is mine - cater for table with a schema and funny column and table names. Yes I had some of them.
SELECT
'ALTER TABLE [' + TABLE_SCHEMA + '].[' + TABLE_NAME
+ '] ALTER COLUMN [' + COLUMN_NAME + '] ' + DATA_TYPE
+ '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS nvarchar(100))
+ ') COLLATE ' + 'Latin1_General_CI_AS'
+ CASE WHEN IS_NULLABLE = 'YES' THEN ' NULL' ELSE ' NOT NULL' END
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
DATA_TYPE like '%char'
I found an easy way to run Visual Studio as administrator. I did it in windows 10 but I believe it would work on any windows.
1.3.1 fixed it.
Just update your extension and you should be good to go
An integer starting with 0 will cause fatal error as of PHP 7, because it might interpret it as an octal character.
Invalid octal literals
Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.
So you might want to remove leading zeros from your integer, first:
$var = ltrim($var, 0);
The problem here is that I don't know what is expected. With your current setup, invoking the plugin on the command line would just work:
$ mvn exec:exec [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Q3491937 [INFO] task-segment: [exec:exec] [INFO] ------------------------------------------------------------------------ [INFO] [exec:exec {execution: default-cli}] [INFO] laptop [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ ...
The global configuration
is used, the hostname
command is executed (laptop
is my hostname). In other words, the plugin works as expected.
Now, if you want a plugin to get executed as part of the build, you have to bind a goal on a specific phase. For example, to bind it on compile
:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<id>some-execution</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>hostname</executable>
</configuration>
</plugin>
And then:
$ mvn compile [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Q3491937 [INFO] task-segment: [compile] [INFO] ------------------------------------------------------------------------ [INFO] [resources:resources {execution: default-resources}] [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory /home/pascal/Projects/Q3491937/src/main/resources [INFO] [compiler:compile {execution: default-compile}] [INFO] Nothing to compile - all classes are up to date [INFO] [exec:exec {execution: some-execution}] [INFO] laptop [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ ...
Note that you can specify a configuration
inside an execution
.
In vue cli-3 You can define the variable in main.js like
window.basurl="http://localhost:8000/";
And you can also access this variable in any component by using the the window.basurl
Here, W and H are width and height of input, F are filter dimensions, P is padding size (i.e., number of rows or columns to be padded)
For SAME padding:
For VALID padding:
Check this out. Just use float and get rid of relative.
#icons{float:left;}
Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml
contains the necessary slf4j dependencies, e.g.:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.
Examples:
Load URL into ImageView without generating a bitmap:
Picasso.with(context) // Context
.load("http://abc.imgur.com/gxsg.png") // URL or file
.into(imageView); // An ImageView object to show the loaded image
Load URL into ImageView by generating a bitmap:
Picasso.with(this)
.load(artistImageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
/* Save the bitmap or do something with it here */
// Set it in the ImageView
theView.setImageBitmap(bitmap)
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
There are many more options available in Picasso. Here is the documentation.