LinkedIn has updated their api and the sharing url's no longer works. Now you can only use the url
query parameter. Any other parameter is going to be removed from the url by LinkedIn.
Now you're forced to use oAuth and interact with the linkedin API to share content on behalf of a user.
Specify the version you want in the 'dependencies' section of your package.json, then from your root project folder in the console/terminal run this:
npm install
For example, the following will specifically install v4.3.4
"dependencies": {
"@angular/common": "4.3.4",
"@angular/compiler": "4.3.4",
"@angular/core": "4.3.4",
"@angular/forms": "4.3.4",
"@angular/http": "4.3.4",
"@angular/platform-browser": "4.3.4",
"@angular/platform-browser-dynamic": "4.3.4",
"@angular/router": "4.3.4",
}
You can also add the following modifiers to the version number to vary how specific you need the version to be:
Updates you to the most recent major version, as specified by the first number:
^4.3.0
will load the latest 4.x.x release, but will not load 5.x.x
Update you to the most recent minor version, as specified by the second number:
~4.3.0
will load the latest 4.3.x release, but will not load 4.4.x
You're calling both wait
and notifyAll
without using a synchronized
block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify
(wait
and notifyAll
have similar documentation but refer to notify
for the fullest description):
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Only one thread will be able to actually exit wait
at a time after notifyAll
as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.
Another solution if you don't want to modify your settings:
Download jms-1.1.jar from JBoss repository then:
mvn install:install-file -DgroupId=javax.jms -DartifactId=jms -Dversion=1.1 -Dpackaging=jar -Dfile=jms-1.1.jar
All output:
scriptname &>/dev/null
Portable:
scriptname >/dev/null 2>&1
Portable:
scriptname >/dev/null 2>/dev/null
For newer bash (no portable):
scriptname &>-
INSERT INTO Destination SELECT * FROM Source;
See SQL As Understood By SQLite: INSERT for a formal definition.
You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:
span {
background: url(button.png) no-repeat 0 0;
}
a {
width: 32px;
height: 32px;
text-align: left;
background: rgb(255,255,255);
-webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
-moz-transition: background 300ms ease-in 200ms;
-o-transition: background 300ms ease-in 200ms;
transition: background 300ms ease-in 200ms;
}
a:hover {
background: rgba(255,255,255,0);
}
Via Enterprise Manager (SSMS)...
To see the SQL you can then right click on the Table
> Script Table As
> Create To
Simplest solution without extra extensions, enums, classes and etc.:
NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise()
Consider adding this to your CSS to resolve the problem:
.btn {
width: 20%;
margin-left: 40%;
margin-right: 30%;
}
Why do you need to attach it to the HTML? Just bind the function with hover
$("div.system_box").hover(function(){ mousin },
function() { mouseout });
If you do insist to have JS references inside the html, which is usualy a bad idea you can use:
onmouseover="yourJavaScriptCode()"
<div class="system_box" data-target="sms_box">
...
$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });
Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.
From PEP 328:
Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.
Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.
import java.awt.MouseInfo;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class MyClass {
public static void main(String[] args) throws InterruptedException{
while(true){
//Thread.sleep(100);
System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x +
", " +
MouseInfo.getPointerInfo().getLocation().y + ")");
}
}
}
Around 4gb/hr is quite common.
For sending get request with parameter i use
$http.get('urlPartOne\\'+parameter+'\\urlPartTwo')
By this you can use your own url string
The problem is clearly not with the javascript. Here's a quick snippet to show you the working of the code.
document.getElementById('points').value = 100;
As you can see, the javascript perfectly assigns the new value to the input element. It would be helpful if you could elaborate more on the issue.
You can achieve the following by using a single line in your spinner declaration in XML:
Just add this: style="@android:style/Widget.Holo.Light.Spinner"
This is a default generated style in android. It doesn't contain borders around it though. For that you'd better search something on google.
Hope this helps.
UPDATE: AFter a lot of digging I got something which works well for introducing border around spinner.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="8dp"
android:top="8dp">
<shape>
<solid android:color="@android:color/white" />
<corners android:radius="4dp" />
<stroke
android:width="2dp"
android:color="#9E9E9E" />
<padding
android:bottom="16dp"
android:left="8dp"
android:right="16dp"
android:top="16dp" />
</shape>
</item>
</layer-list>
Place this in the drawable folder and use it as a background for spinner. Like this:
<RelativeLayout
android:id="@+id/speaker_relative_layout"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:background="@drawable/spinner_style"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Spinner
android:id="@+id/select_speaker_spinner"
style="@style/Widget.AppCompat.DropDownItem.Spinner"
android:layout_width="match_parent"
android:layout_height="70dp"
android:entries="@array/select_speaker_spinner_array"
android:spinnerMode="dialog" />
</RelativeLayout>
long
is equivalent to long int
, just as short
is equivalent to short int
. A long int
is a signed integral type that is at least 32 bits, while a long long
or long long int
is a signed integral type is at least 64 bits.
This doesn't necessarily mean that a long long
is wider than a long
. Many platforms / ABIs use the LP64
model - where long
(and pointers) are 64 bits wide. Win64 uses the LLP64
, where long
is still 32 bits, and long long
(and pointers) are 64 bits wide.
There's a good summary of 64-bit data models here.
long double
doesn't guarantee much other than it will be at least as wide as a double
.
Here is your solution for the problem,
$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
if(ord($i) % 2 != 0)
$letter[] .= $i;
}
print_r($letter);
You need to get the ASCII value for that character which will solve your problem.
Here is ord doc and working code.
For your requirement, you can do like this,
for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
$letter[] .= $i;
}
print_r($letter);
Here set $x as per your requirement.
The values can be retrieved during the parsing:
var yahoo = [], j = `[{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]`_x000D_
_x000D_
var data = JSON.parse(j, function(key, value) { _x000D_
if ( value.website === "yahoo" ) yahoo.push(value); _x000D_
return value; })_x000D_
_x000D_
console.log( yahoo )
_x000D_
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
Using alternative dplyr package:
library("dplyr") # or library("tidyverse")
df <- df %>% mutate(id = row_number())
I would suggest something like:
$text =~ m{(.*)$find(.*)};
$text = $1 . $replace . $2;
It is quite readable and seems to be safe. If multiple replace is needed, it is easy:
while ($text =~ m{(.*)$find(.*)}){
$text = $1 . $replace . $2;
}
If you prefer using Java's Calendar API you can try this,
Date startingTime = Calendar.getInstance().getTime();
//later on
Date now = Calendar.getInstance().getTime();
long timeElapsed = now.getTime() - startingTime.getTime();
They do this with some basic javascript, but this does not actually hide your HTML source! In many browsers you can simply go to view->source on the menu. Even if you couldn't, it is trivial to simply load up a debugging proxy like Fiddler, or packet-sniff the connection.
It is impossible to effectively hide the HTML, JavaScript, or any other resource sent to the client. Impossible, and isn't all that useful either.
Furthermore, don't try to disable right-click, as there are many other items on that menu (such as print!) that people use regularly.
For people who have an Ant build process, you can generate a version number for a project on git with this target:
<target name="generate-version">
<exec executable="git" outputproperty="version.revisions">
<arg value="log"/>
<arg value="--oneline"/>
</exec>
<resourcecount property="version.revision" count="0" when="eq">
<tokens>
<concat>
<filterchain>
<tokenfilter>
<stringtokenizer delims="\r" />
</tokenfilter>
</filterchain>
<propertyresource name="version.revisions" />
</concat>
</tokens>
</resourcecount>
<echo>Revision : ${version.revision}</echo>
<exec executable="git" outputproperty="version.hash">
<arg value="rev-parse"/>
<arg value="--short"/>
<arg value="HEAD"/>
</exec>
<echo>Hash : ${version.hash}</echo>
<exec executable="git" outputproperty="version.branch">
<arg value="rev-parse"/>
<arg value="--abbrev-ref"/>
<arg value="HEAD"/>
</exec>
<echo>Branch : ${version.branch}</echo>
<exec executable="git" outputproperty="version.diff">
<arg value="diff"/>
</exec>
<condition property="version.dirty" value="" else="-dirty">
<equals arg1="${version.diff}" arg2=""/>
</condition>
<tstamp>
<format property="version.date" pattern="yyyy-mm-dd.HH:mm:ss" locale="en,US"/>
</tstamp>
<echo>Date : ${version.date}</echo>
<property name="version" value="${version.revision}.${version.hash}.${version.branch}${version.dirty}.${version.date}" />
<echo>Version : ${version}</echo>
<echo file="version.properties" append="false">version = ${version}</echo>
</target>
The result looks like this:
generate-version:
[echo] Generate version
[echo] Revision : 47
[echo] Hash : 2af0b99
[echo] Branch : master
[echo] Date : 2015-04-20.15:04:03
[echo] Version : 47.2af0b99.master-dirty.2015-04-20.15:04:03
The dirty flag is here when you have file(s) not committed when you generate the version number. Because usually, when you build/package your application, every code modification has to be in the repository.
In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.
Here's something you might want to do:
public class Foo
{
public void fee()
{
//do stuff
}
public static void main (String[]arg)
{
Foo foo = new Foo();
foo.fee();
}
}
Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.
It isn't possible to do it the way you've defined ldap_get
. However, if you define ldap_get
like this:
def ldap_get ( base_dn, filter, attrs=nil, scope=LDAP::LDAP_SCOPE_SUBTREE )
Now you can:
ldap_get( base_dn, filter, X )
But now you have problem that you can't call it with the first two args and the last arg (the same problem as before but now the last arg is different).
The rationale for this is simple: Every argument in Ruby isn't required to have a default value, so you can't call it the way you've specified. In your case, for example, the first two arguments don't have default values.
I missed the obvious answer using hex numbers for the fromRGB constructor:
Color.fromRGBO(0xb7, 0x40, 0x93, 1),
You can also dynamically create a class by using DynamicExpressions.
Since 'Dictionary's have compact initializers and handle key collisions, you will want to do something like this.
var list = new Dictionary<string, string> {
{
"EmployeeID",
"int"
}, {
"EmployeeName",
"String"
}, {
"Birthday",
"DateTime"
}
};
Or you might want to use a JSON converter to construct your serialized string object into something manageable.
Then using System.Linq.Dynamic;
IEnumerable<DynamicProperty> props = list.Select(property => new DynamicProperty(property.Key, Type.GetType(property.Value))).ToList();
Type t = DynamicExpression.CreateClass(props);
The rest is just using System.Reflection.
object obj = Activator.CreateInstance(t);
t.GetProperty("EmployeeID").SetValue(obj, 34, null);
t.GetProperty("EmployeeName").SetValue(obj, "Albert", null);
t.GetProperty("Birthday").SetValue(obj, new DateTime(1976, 3, 14), null);
}
I recommend to use both, prop and attr because I had problems with Chrome and I solved it using both functions.
if ($(':checkbox').is(':checked')){
$(':checkbox').prop('checked', true).attr('checked', 'checked');
}
else {
$(':checkbox').prop('checked', false).removeAttr('checked');
}
The objects in the std::set
are stored as const StudentT
. So when you try to call getId()
with the const
object the compiler detects a problem, mainly you're calling a non-const member function on const object which is not allowed because non-const member functions make NO PROMISE not to modify the object; so the compiler is going to make a safe assumption that getId()
might attempt to modify the object but at the same time, it also notices that the object is const; so any attempt to modify the const object should be an error. Hence compiler generates an error message.
The solution is simple: make the functions const as:
int getId() const {
return id;
}
string getName() const {
return name;
}
This is necessary because now you can call getId()
and getName()
on const objects as:
void f(const StudentT & s)
{
cout << s.getId(); //now okay, but error with your versions
cout << s.getName(); //now okay, but error with your versions
}
As a sidenote, you should implement operator<
as :
inline bool operator< (const StudentT & s1, const StudentT & s2)
{
return s1.getId() < s2.getId();
}
Note parameters are now const
reference.
Don't Create 9-patch images for launcher icons . You have to make separate image for each one.
LDPI - 36 x 36
MDPI - 48 x 48
HDPI - 72 x 72
XHDPI - 96 x 96
XXHDPI - 144 x 144
XXXHDPI - 192 x 192.
WEB - 512 x 512 (Require when upload application on Google Play)
Note: WEB(512 x 512) image is used when you upload your android application on Market.
|| Android App Icon Size ||
All Devices
hdpi=281*164
mdpi=188*110
xhdpi=375*219
xxhdpi=563*329
xxxhdpi=750*438
48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)
The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();
Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);
Hope this helps.
I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.
To check for Collection be empty or null
public static boolean isEmpty(Collection obj) {
return obj == null || obj.isEmpty();
}
or use Apache Commons CollectionUtils.isEmpty()
To check if Map is empty or null
public static boolean isEmpty(Map<?, ?> value) {
return value == null || value.isEmpty();
}
or use Apache Commons MapUtils.isEmpty()
To check for String empty or null
public static boolean isEmpty(String string) {
return string == null || string.trim().isEmpty();
}
or use Apache Commons StringUtils.isBlank()
To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.
This answer is in javaScript:
function getCharFromNumber(columnNumber){
var dividend = columnNumber;
var columnName = "";
var modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = String.fromCharCode(65 + modulo).toString() + columnName;
dividend = parseInt((dividend - modulo) / 26);
}
return columnName;
}
Just in case you have a preference for how negative numbers are formatted:
p "%x" % -1 #=> "..f"
p -1.to_s(16) #=> "-1"
Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.
https://github.com/marcj/css-element-queries
It contains a ResizeSensor class you can use for that purpose.
new ResizeSensor(jQuery('#mainContent'), function(){
console.log('main content dimension changed');
});
Disclaimer: I wrote this library
I assume you want to make modal use as much screen space as possible on phones. I've made a plugin to fix this UX problem of Bootstrap modals on mobile phones, you can check it out here - https://github.com/keaukraine/bootstrap-fs-modal
All you will need to do is to apply modal-fullscreen
class and it will act similar to native screens of iOS/Android.
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");
}
}
}
You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.
Of course the "You shall not instantiate an item of this class" statement has been violated, but if this is the logic behind that, then we should all throw
AssertionErrors
everywhere, and that is obviously not what happens.
The code isn't saying the user shouldn't call the zero-args constructor. The assertion is there to say that as far as the programmer is aware, he/she has made it impossible to call the zero-args constructor (in this case by making it private
and not calling it from within Example
's code). And so if a call occurs, that assertion has been violated, and so AssertionError
is appropriate.
In a Vue regular setup, /assets
is not served.
The images become src="data:image/png;base64,iVBORw0K...YII="
strings, instead.
require()
To get the images from JS code, use require('../assets.myImage.png')
. The path must be relative (see below).
So your code would be:
var icon = L.icon({
iconUrl: require('./assets/img.png'), // was iconUrl: './assets/img.png',
// iconUrl: require('@/assets/img.png'), // use @ as alternative, depending on the path
// ...
});
For example, say you have the following folder structure:
- src
+- assets
- myImage.png
+- components
- MyComponent.vue
If you want to reference the image in MyComponent.vue
, the path sould be ../assets/myImage.png
Here's a DEMO CODESANDBOX showing it in action.
Learn more about how to navigate through the parse tree in BeautifulSoup
. Parse tree has got tags
and NavigableStrings
(as THIS IS A TEXT). An example
from BeautifulSoup import BeautifulSoup
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
'</html>']
soup = BeautifulSoup(''.join(doc))
print soup.prettify()
# <html>
# <head>
# <title>
# Page title
# </title>
# </head>
# <body>
# <p id="firstpara" align="center">
# This is paragraph
# <b>
# one
# </b>
# .
# </p>
# <p id="secondpara" align="blah">
# This is paragraph
# <b>
# two
# </b>
# .
# </p>
# </body>
# </html>
To move down the parse tree you have contents
and string
.
contents is an ordered list of the Tag and NavigableString objects contained within a page element
if a tag has only one child node, and that child node is a string, the child node is made available as tag.string, as well as tag.contents[0]
For the above, that is to say you can get
soup.b.string
# u'one'
soup.b.contents[0]
# u'one'
For several children nodes, you can have for instance
pTag = soup.p
pTag.contents
# [u'This is paragraph ', <b>one</b>, u'.']
so here you may play with contents
and get contents at the index you want.
You also can iterate over a Tag, this is a shortcut. For instance,
for i in soup.body:
print i
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
A simpler solution may be(python 3):
import urllib.request
import os
os.chdir("D:\\comic") #your path
i=1;
s="00000000"
while i<1000:
try:
urllib.request.urlretrieve("http://www.gunnerkrigg.com//comics/"+ s[:8-len(str(i))]+ str(i)+".jpg",str(i)+".jpg")
except:
print("not possible" + str(i))
i+=1;
You probably want the isinstance
builtin function:
self.data = data if isinstance(data, list) else self.parse(data)
$date= new DateTime($row['your_date']) ;
echo $date->format('Y-m-d');
I) if you need to calculate the elapsed time in seconds between two timestamp columns try this:
SELECT
extract ( day from (end_timestamp - start_timestamp) )*86400
+ extract ( hour from (end_timestamp - start_timestamp) )*3600
+ extract ( minute from (end_timestamp - start_timestamp) )*60
+ extract ( second from (end_timestamp - start_timestamp) )
FROM table_name
II) if you want to just show the time difference in character format try this:
SELECT to_char (end_timestamp - start_timestamp) FROM table_name
I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
Try add this command in your build.gradle
So for running configure that shape:
I had same problem , instead @Entity I used following code for getting records
List<Map<String, Object>> list = null;
list = incidentHibernateTemplate.execute(new HibernateCallback<List<Map<String, Object>>>() {
@Override
public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery("SELECT * from table where appcode = :app");
query.setParameter("app", apptype);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
return query.list();
}
});
I used following code for update
private @Autowired HibernateTemplate incidentHibernateTemplate;
Integer updateCount = 0;
updateCount = incidentHibernateTemplate.execute((Session session) -> {
Query<?> query = session
.createSQLQuery("UPDATE tablename SET key = :apiurl, data_mode = :mode WHERE apiname= :api ");
query.setParameter("apiurl", url);
query.setParameter("api", api);
query.setParameter("mode", mode);
return query.executeUpdate();
}
);
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
For OSX:
I had installed this via Anaconda, and had a hell of a time getting it to work. What helped was adding the Anaconda bin AND pkgs folder to my PATH.
Since I use fishshell, I did it in my ~/.config/fish/config.fish
file like this:
set -g -x PATH $PATH /Users/cbrevik/anaconda/bin /Users/cbrevik/anaconda/pkgs
If you use fishshell like me, this answer will probably save you some trouble later using pandas as well.
I write out a rule in web.config after $locationProvider.html5Mode(true)
is set in app.js
.
Hope, helps someone out.
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
In my index.html I added this to <head>
<base href="/">
Don't forget to install url rewriter for iis on server.
Also if you use Web Api and IIS, this match url will not work out, as it will change your api calls. So add third input(third line of condition) and give out a pattern that will exclude calls from www.yourdomain.com/api
example = new String[example.length];
If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.
Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
How about -
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))
if seconds is None
then it converts the local time to UTC time else converts the passed in time to UTC.
I use when I do a big commit, above all when I remove more files from the repository.. after, the commits are faster
Change It like this, It worked for me. Hope It helps. firs I did
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
Then I Changed Like this...
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
Here are two approaches:
@echo off
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%
::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%
::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set "" &::
;;set "}}==%%#"" &::
::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%
::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%
If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.
This code works form me. Include the jquery.js file.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
var headerDivWidth=0;
var contentDivWidth=0;
function fixHeader(){
var contentDivId = "contentDiv";
var headerDivId = "headerDiv";
var header = document.createElement('table');
var headerRow = document.getElementById('tableColumnHeadings');
/*Start : Place header table inside <DIV> and place this <DIV> before content table*/
var headerDiv = "<div id='"+headerDivId+"' style='width:500px;overflow-x:hidden;overflow-y:scroll' class='tableColumnHeadings'><table></table></div>";
$(headerRow).wrap(headerDiv);
$("#"+headerDivId).insertBefore("#"+contentDivId);
/*End : Place header table inside <DIV> and place this <DIV> before content table*/
fixColumnWidths(headerDivId,contentDivId);
}
function fixColumnWidths(headerDivId,contentDivId){
/*Start : Place header row cell and content table first row cell inside <DIV>*/
var contentFirstRowCells = $('#'+contentDivId+' table tr:first-child td');
for (k = 0; k < contentFirstRowCells.length; k++) {
$( contentFirstRowCells[k] ).wrapInner( "<div ></div>");
}
var headerFirstRowCells = $('#'+headerDivId+' table tr:first-child td');
for (k = 0; k < headerFirstRowCells.length; k++) {
$( headerFirstRowCells[k] ).wrapInner( "<div></div>");
}
/*End : Place header row cell and content table first row cell inside <DIV>*/
/*Start : Fix width for columns of header cells and content first ror cells*/
var headerColumns = $('#'+headerDivId+' table tr:first-child td div:first-child');
var contentColumns = $('#'+contentDivId+' table tr:first-child td div:first-child');
for (i = 0; i < contentColumns.length; i++) {
if (i == contentColumns.length - 1) {
contentCellWidth = contentColumns[i].offsetWidth;
}
else {
contentCellWidth = contentColumns[i].offsetWidth;
}
headerCellWidth = headerColumns[i].offsetWidth;
if(contentCellWidth>headerCellWidth){
$(headerColumns[i]).css('width', contentCellWidth+"px");
$(contentColumns[i]).css('width', contentCellWidth+"px");
}else{
$(headerColumns[i]).css('width', headerCellWidth+"px");
$(contentColumns[i]).css('width', headerCellWidth+"px");
}
}
/*End : Fix width for columns of header and columns of content table first row*/
}
function OnScrollDiv(Scrollablediv) {
document.getElementById('headerDiv').scrollLeft = Scrollablediv.scrollLeft;
}
function radioCount(){
alert(document.form.elements.length);
}
</script>
<style>
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
th,td
{
padding:5px;
}
</style>
</head>
<body onload="fixHeader();">
<form id="form" name="form">
<div id="contentDiv" style="width:500px;height:100px;overflow:auto;" onscroll="OnScrollDiv(this)">
<table>
<!--tr id="tableColumnHeadings" class="tableColumnHeadings">
<td><div>Firstname</div></td>
<td><div>Lastname</div></td>
<td><div>Points</div></td>
</tr>
<tr>
<td><div>Jillsddddddddddddddddddddddddddd</div></td>
<td><div>Smith</div></td>
<td><div>50</div></td>
</tr-->
<tr id="tableColumnHeadings" class="tableColumnHeadings">
<td> </td>
<td>Firstname</td>
<td>Lastname</td>
<td>Points</td>
</tr>
<tr style="height:0px">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr >
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID" onclick="javascript:radioCount();"/></td>
<td>Jillsddddddddddddddddddddddddddd</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>Eve</td>
<td>Jackson</td>
<td>9400000000000000000000000000000</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td><div>Jillsddddddddddddddddddddddddddd</div></td>
<td><div>Smith</div></td>
<td><div>50</div></td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>Eve</td>
<td>Jackson</td>
<td>9400000000000000000000000000000</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
</form>
</body>
</html>
There's no simple, elegant CSS analog for colspan
.
Searches on this very issue will return a variety of solutions that include a bevy of alternatives, including absolute positioning, sizing, along with a similar variety of browser- and circumstance-specific caveats. Read, and make the best informed decision you can based on what you find.
The easiest way for setting the current date is.
<input name="date" type="date" value="<?php echo date('Y-m-j'); ?>" required>
tl;dr
post-JDK8 : Use AssertJ or custom lambdas to assert exceptional behaviour.
pre-JDK8 : I will recommend the old good try
-catch
block. (Don't forget to add a fail()
assertion before the catch
block)
Regardless of Junit 4 or JUnit 5.
the long story
It is possible to write yourself a do it yourself try
-catch
block or use the JUnit tools (@Test(expected = ...)
or the @Rule ExpectedException
JUnit rule feature).
But these ways are not so elegant and don't mix well readability wise with other tools. Moreover, JUnit tooling does have some pitfalls.
The try
-catch
block you have to write the block around the tested behavior and write the assertion in the catch block, that may be fine but many find that this style interrupts the reading flow of a test. Also, you need to write an Assert.fail
at the end of the try
block. Otherwise, the test may miss one side of the assertions; PMD, findbugs or Sonar will spot such issues.
The @Test(expected = ...)
feature is interesting as you can write less code and then writing this test is supposedly less prone to coding errors. But this approach is lacking in some areas.
Also as the expectation is placed around in the method, depending on how the tested code is written then the wrong part of the test code can throw the exception, leading to false-positive test and I'm not sure that PMD, findbugs or Sonar will give hints on such code.
@Test(expected = WantedException.class)
public void call2_should_throw_a_WantedException__not_call1() {
// init tested
tested.call1(); // may throw a WantedException
// call to be actually tested
tested.call2(); // the call that is supposed to raise an exception
}
The ExpectedException
rule is also an attempt to fix the previous caveats, but it feels a bit awkward to use as it uses an expectation style, EasyMock users know very well this style. It might be convenient for some, but if you follow Behaviour Driven Development (BDD) or Arrange Act Assert (AAA) principles the ExpectedException
rule won't fit in those writing style. Aside from that it may suffer from the same issue as the @Test
way, depending on where you place the expectation.
@Rule ExpectedException thrown = ExpectedException.none()
@Test
public void call2_should_throw_a_WantedException__not_call1() {
// expectations
thrown.expect(WantedException.class);
thrown.expectMessage("boom");
// init tested
tested.call1(); // may throw a WantedException
// call to be actually tested
tested.call2(); // the call that is supposed to raise an exception
}
Even the expected exception is placed before the test statement, it breaks your reading flow if the tests follow BDD or AAA.
Also, see this comment issue on JUnit of the author of ExpectedException
. JUnit 4.13-beta-2 even deprecates this mechanism:
Pull request #1519: Deprecate ExpectedException
The method Assert.assertThrows provides a nicer way for verifying exceptions. In addition, the use of ExpectedException is error-prone when used with other rules like TestWatcher because the order of rules is important in that case.
So these above options have all their load of caveats, and clearly not immune to coder errors.
There's a project I became aware of after creating this answer that looks promising, it's catch-exception.
As the description of the project says, it let a coder write in a fluent line of code catching the exception and offer this exception for the latter assertion. And you can use any assertion library like Hamcrest or AssertJ.
A rapid example taken from the home page :
// given: an empty list
List myList = new ArrayList();
// when: we try to get the first element of the list
when(myList).get(1);
// then: we expect an IndexOutOfBoundsException
then(caughtException())
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessage("Index: 1, Size: 0")
.hasNoCause();
As you can see the code is really straightforward, you catch the exception on a specific line, the then
API is an alias that will use AssertJ APIs (similar to using assertThat(ex).hasNoCause()...
). At some point the project relied on FEST-Assert the ancestor of AssertJ. EDIT: It seems the project is brewing a Java 8 Lambdas support.
Currently, this library has two shortcomings :
At the time of this writing, it is noteworthy to say this library is based on Mockito 1.x as it creates a mock of the tested object behind the scene. As Mockito is still not updated this library cannot work with final classes or final methods. And even if it was based on Mockito 2 in the current version, this would require to declare a global mock maker (inline-mock-maker
), something that may not what you want, as this mock maker has different drawbacks that the regular mock maker.
It requires yet another test dependency.
These issues won't apply once the library supports lambdas. However, the functionality will be duplicated by the AssertJ toolset.
Taking all into account if you don't want to use the catch-exception tool, I will recommend the old good way of the try
-catch
block, at least up to the JDK7. And for JDK 8 users you might prefer to use AssertJ as it offers may more than just asserting exceptions.
With the JDK8, lambdas enter the test scene, and they have proved to be an interesting way to assert exceptional behaviour. AssertJ has been updated to provide a nice fluent API to assert exceptional behaviour.
And a sample test with AssertJ :
@Test
public void test_exception_approach_1() {
...
assertThatExceptionOfType(IOException.class)
.isThrownBy(() -> someBadIOOperation())
.withMessage("boom!");
}
@Test
public void test_exception_approach_2() {
...
assertThatThrownBy(() -> someBadIOOperation())
.isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
@Test
public void test_exception_approach_3() {
...
// when
Throwable thrown = catchThrowable(() -> someBadIOOperation());
// then
assertThat(thrown).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
With a near-complete rewrite of JUnit 5, assertions have been improved a bit, they may prove interesting as an out of the box way to assert properly exception. But really the assertion API is still a bit poor, there's nothing outside assertThrows
.
@Test
@DisplayName("throws EmptyStackException when peeked")
void throwsExceptionWhenPeeked() {
Throwable t = assertThrows(EmptyStackException.class, () -> stack.peek());
Assertions.assertEquals("...", t.getMessage());
}
As you noticed assertEquals
is still returning void
, and as such doesn't allow chaining assertions like AssertJ.
Also if you remember name clash with Matcher
or Assert
, be prepared to meet the same clash with Assertions
.
I'd like to conclude that today (2017-03-03) AssertJ's ease of use, discoverable API, the rapid pace of development and as a de facto test dependency is the best solution with JDK8 regardless of the test framework (JUnit or not), prior JDKs should instead rely on try
-catch
blocks even if they feel clunky.
This answer has been copied from another question that don't have the same visibility, I am the same author.
Use DATEDIFF
Select I.Fee
From Item I
WHERE DATEDIFF(day, GETDATE(), I.DateCreated) < 365
In build.gradle
change minSdkVersion 13
to minSdkVersion 8
Thats all you need to do. I solved my problem by only doing this.
defaultConfig {
applicationId "com.example.sabrim.sbrtest"
minSdkVersion 8
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
Many of the suggestions unfortunately do not work for all Markdown viewers/editors, for instance, the popular Markdown Viewer Chrome extension, but they do work with iA Writer.
What does seem to work across both of these popular programs (and might work for your particular application) is to use HTML comment blocks ('<!-- -->')
:
| <!-- --> | <!-- --> |
|-------------|-------------|
| Foo | Bar |
Like some of the earlier suggestions stated, this does add an empty header row in your Markdown viewer/editor. In iA Writer, it's aesthetically small enough that it doesn't get in my way too much.
The following modification of Rômulo's answer works for me on Python 2 and 3 (2.7.12 and 3.6.1):
import os
import subprocess
process = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:
line = process.stdout.readline()
if line != '':
os.write(1, line)
else:
break
Forward declare class B
and swap order of A
and B
definitions: 1st B
and 2nd A
. You can not call methods of forward declared B
class.
I think the answer you are after is implied (if not stated) by Vinko's answer, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
You probably can combine the two tests on the second line into one with:
if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '-a
' and do recommend using separate simple tests combined with &&
. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).
You can find the details of these, and other related shell parameter expansions, the test
or [
command and conditional expressions in the Bash manual.
I was recently asked by email about this answer with the question:
You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
Wouldn't this accomplish the same?
if [ -z "${VAR}" ]; then echo VAR is not set at all; fi
Fair question - the answer is 'No, your simpler alternative does not do the same thing'.
Suppose I write this before your test:
VAR=
Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:
(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo JL:1 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:1 VAR is not set at all; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo JL:2 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:2 VAR is not set at all; fi
)
The output is:
JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all
In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the ${VAR=value}
and ${VAR:=value}
notations make. Ditto for ${VAR-value}
and ${VAR:-value}
, and ${VAR+value}
and ${VAR:+value}
, and so on.
As Gili points out in his answer, if you run bash
with the set -o nounset
option, then the basic answer above fails with unbound variable
. It is easily remedied:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
Or you could cancel the set -o nounset
option with set +u
(set -u
being equivalent to set -o nounset
).
I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with Popen
, but it wasn't possible in my situation.
What I ended up doing is something like:
commands = '''
echo "a"
echo "b"
echo "c"
echo "d"
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out
So I first create the child bash process and after I tell it what to execute. This approach removes the limitations of passing the command directly to the Popen
constructor.
if you have already pushed your commit then. do
git checkout origin/<remote-branch> <filename>
git commit --amend
AND If you have not pushed the changes on the server you can use
git reset --soft HEAD~1
Wanted to add numexpr into the mix:
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)
Would only make sense for larger arrays with millions... or if you hitting a memory limits.
I just installed SQL Developer 4.0.0.13 and the SetJavaHome
can now be overridden by a user-specific configuration file (not sure if this is new to 4.0.0.13 or not).
The location of this user-specific configuration file can be seen in the user.conf
property under 'Help -> About' on the 'Properties' tab. For example, mine was set to:
C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0\product.conf
On Windows 7.
The first section of this file is used to set the JDK that SQLDeveloper should use:
#
# By default, the product launcher will search for a JDK to use, and if none
# can be found, it will ask for the location of a JDK and store its location
# in this file. If a particular JDK should be used instead, uncomment the
# line below and set the path to your preferred JDK.
#
SetJavaHome C:\Program Files (x86)\Java\jdk1.7.0_03
This setting overrides the setting in sqldeveloper.conf
max(may$Ozone, na.rm = TRUE)
Without $Ozone
it will filter in the whole data frame, this can be learned in the swirl library.
I'm studying this course on Coursera too ~
In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
but it showing some error like below:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
Solution: we have to write like this:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
Wrap your widget tree inside a SingleChildScrollView
body: SingleChildScrollView(
child: Stack(
children: <Widget>[
new Container(
decoration: BoxDecoration(
image: DecorationImage(...),
new Column(children: [
new Container(...),
new Container(...... ),
new Padding(
child: SizedBox(
child: RaisedButton(..),
),
....
...
); // Single child scroll view
Remember, SingleChildScrollView can only have one direct widget (Just like ScrollView in Android)
Considering the previous answers, it is necessary to be careful with globalized characters.
Suppose the name of the file is: "Esdrújula prenda ñame - güena.jpg"
Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]
HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly]
UrlEncode result to download: "Esdrújula+prenda+ñame+-+güena.jpg" [OK]
Then, you need almost always to use the UrlEncode over the file name. Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.
Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");
or with class aid:
var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
Response.AddHeader("Content-Disposition", cd.ToString());
The System.Net.Mime.ContentDisposition class takes care of quotes.
For posterity, I ran into this with an azure function, using the azure durable function / durable tasks framework. It turns out I had an outdated version of the azure functions runtime installed locally. updating it fixed it.
mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// event when click home button
}
});
in mycase this code work perfect
I modifie this list and add a List to the samples try this
Pseudocode
Sample {
List<String> values;
List<String> getList() {
return values}
}
for(Sample s : list) {
if(s.getString.getList.contains("three") {
return s;
}
}
This is certainly something that has a lot of traps. I was working with Paolo Bergantino's answer, and realising that even that has some limitations. I found working with string representations of dates a good place to quickly find some of the main problems. Start with an input string like this:
'12-2-2019 5:1:48.670'
and set up Paolo's function like this:
function count(re, str) {
if (typeof re !== "string") {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
var cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
I wanted the regular expression to be passed in, so that the function is more reusable, secondly, I wanted the parameter to be a string, so that the client doesn't have to make the regex, but simply match on the string, like a standard string utility class method.
Now, here you can see that I'm dealing with issues with the input. With the following:
if (typeof re !== "string") {
return 0;
}
I am ensuring that the input isn't anything like the literal 0
, false
, undefined
, or null
, none of which are strings. Since these literals are not in the input string, there should be no matches, but it should match '0'
, which is a string.
With the following:
re = (re === '.') ? ('\\' + re) : re;
I am dealing with the fact that the RegExp constructor will (I think, wrongly) interpret the string '.'
as the all character matcher \.\
Finally, because I am using the RegExp constructor, I need to give it the global 'g'
flag so that it counts all matches, not just the first one, similar to the suggestions in other posts.
I realise that this is an extremely late answer, but it might be helpful to someone stumbling along here. BTW here's the TypeScript version:
function count(re: string, str: string): number {
if (typeof re !== 'string') {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
const cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
this should be on here: it works anyway. And it looks good compared to the above ones.
hlsl code
float3 Hue(float H)
{
half R = abs(H * 6 - 3) - 1;
half G = 2 - abs(H * 6 - 2);
half B = 2 - abs(H * 6 - 4);
return saturate(half3(R,G,B));
}
half4 HSVtoRGB(in half3 HSV)
{
return half4(((Hue(HSV.x) - 1) * HSV.y + 1) * HSV.z,1);
}
float3 is 16 bit precision vector3 data type, i.e. float3 hue() is returns a data type (x,y,z) e.g. (r,g,b), half is same with half precision, 8bit, a float4 is (r,g,b,a) 4 values.
if (!$(row).hasClass("changed")) {
// do your stuff
}
should be handled as a whitespace.
should be handled as two whitespaces
' ' can be handled as a non interesting whitespace
' ' + ' ' can be handled as a single ' '
java.net.URLEncoder.encode(String s, String encoding)
can help too. It follows the HTML form encoding application/x-www-form-urlencoded
.
URLEncoder.encode(query, "UTF-8");
On the other hand, Percent-encoding (also known as URL encoding) encodes space with %20
. Colon is a reserved character, so :
will still remain a colon, after encoding.
You can add the SVG as background-image
of an empty :after
or :before
.
Here you go:
.anchor:before {
display: block;
content: ' ';
background-image: url('../images/anchor.svg');
background-size: 28px 28px;
height: 28px;
width: 28px;
}
colorRampPalette
could be your friend here:
colfunc <- colorRampPalette(c("black", "white"))
colfunc(10)
# [1] "#000000" "#1C1C1C" "#383838" "#555555" "#717171" "#8D8D8D" "#AAAAAA"
# [8] "#C6C6C6" "#E2E2E2" "#FFFFFF"
And just to show it works:
plot(rep(1,10),col=colfunc(10),pch=19,cex=3)
Action Sheet in iOS10 with Swift3.0. Follow this link.
@IBAction func ShowActionSheet(_ sender: UIButton) {
// Create An UIAlertController with Action Sheet
let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)
// Create UIAlertAction for UIAlertController
let addAction = UIAlertAction(title: "Add", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Add")
})
let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Edit")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Delete")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// Add UIAlertAction in UIAlertController
optionMenuController.addAction(addAction)
optionMenuController.addAction(saveAction)
optionMenuController.addAction(deleteAction)
optionMenuController.addAction(cancelAction)
// Present UIAlertController with Action Sheet
self.present(optionMenuController, animated: true, completion: nil)
}
You can try using a regex like this:
$s = preg_replace('|/.*$|', '', $s);
sometimes, regex are slower though, so if performance is an issue, make sure to benchmark this properly and use an other alternative with substrings if it's more suitable for you.
In C#, Array.Resize
is the simplest method to resize any array to new size, e.g.:
Array.Resize<LinkButton>(ref area, size);
Here, i want to resize the array size of LinkButton array:
<LinkButton>
= specifies the array type
ref area
= ref is a keyword and 'area' is the array name
size
= new size array
try like this
if (!(a | b)) {
//blahblah
}
It's same with
if (a | b) {}
else {
// blahblah
}
For a more modern solution, and if there is no need to support legacy browsers, you can do this:
.frame {_x000D_
display: flex;_x000D_
/**_x000D_
Uncomment 'justify-content' below to center horizontally._x000D_
? Read below for a better way to center vertically and horizontally._x000D_
**/_x000D_
_x000D_
/* justify-content: center; */_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
img {_x000D_
height: auto;_x000D_
_x000D_
/**_x000D_
? To center this image both vertically and horizontally,_x000D_
in the .frame rule above comment the 'justify-content'_x000D_
and 'align-items' declarations,_x000D_
then uncomment 'margin: auto;' below._x000D_
**/_x000D_
_x000D_
/* margin: auto; */_x000D_
}_x000D_
_x000D_
/* Styling stuff not needed for demo */_x000D_
.frame {_x000D_
max-width: 900px;_x000D_
height: 200px;_x000D_
margin: auto;_x000D_
background: #222;_x000D_
}_x000D_
p {_x000D_
max-width: 900px;_x000D_
margin: 20px auto 0;_x000D_
}_x000D_
img {_x000D_
width: 150px;_x000D_
}
_x000D_
<div class="frame">_x000D_
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9988/hand-pointing.png">_x000D_
</div>
_x000D_
Here's a Pen: http://codepen.io/ricardozea/pen/aa0ee8e6021087b6e2460664a0fa3f3e
The code in elyase's answer https://stackoverflow.com/a/27928411/4240413 does not actually work. Notice that sse is a scalar, and then it tries to iterate through it. The following code is a modified version. Not amazingly clean, but I think it works more or less.
class LinearRegression(linear_model.LinearRegression):
def __init__(self,*args,**kwargs):
# *args is the list of arguments that might go into the LinearRegression object
# that we don't know about and don't want to have to deal with. Similarly, **kwargs
# is a dictionary of key words and values that might also need to go into the orginal
# LinearRegression object. We put *args and **kwargs so that we don't have to look
# these up and write them down explicitly here. Nice and easy.
if not "fit_intercept" in kwargs:
kwargs['fit_intercept'] = False
super(LinearRegression,self).__init__(*args,**kwargs)
# Adding in t-statistics for the coefficients.
def fit(self,x,y):
# This takes in numpy arrays (not matrices). Also assumes you are leaving out the column
# of constants.
# Not totally sure what 'super' does here and why you redefine self...
self = super(LinearRegression, self).fit(x,y)
n, k = x.shape
yHat = np.matrix(self.predict(x)).T
# Change X and Y into numpy matricies. x also has a column of ones added to it.
x = np.hstack((np.ones((n,1)),np.matrix(x)))
y = np.matrix(y).T
# Degrees of freedom.
df = float(n-k-1)
# Sample variance.
sse = np.sum(np.square(yHat - y),axis=0)
self.sampleVariance = sse/df
# Sample variance for x.
self.sampleVarianceX = x.T*x
# Covariance Matrix = [(s^2)(X'X)^-1]^0.5. (sqrtm = matrix square root. ugly)
self.covarianceMatrix = sc.linalg.sqrtm(self.sampleVariance[0,0]*self.sampleVarianceX.I)
# Standard erros for the difference coefficients: the diagonal elements of the covariance matrix.
self.se = self.covarianceMatrix.diagonal()[1:]
# T statistic for each beta.
self.betasTStat = np.zeros(len(self.se))
for i in xrange(len(self.se)):
self.betasTStat[i] = self.coef_[0,i]/self.se[i]
# P-value for each beta. This is a two sided t-test, since the betas can be
# positive or negative.
self.betasPValue = 1 - t.cdf(abs(self.betasTStat),df)
You can describe your css selection like cascading style sheet dows:
protected override void When()
{
SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
}
You can change Apaches httpd.conf by clicking (in xampp control panel) apache/conf/httpd.conf
and adjust the entries for DocumentRoot
and the corresponding Directory
entry.
Just Ctrl+F for "htdocs" and change the entries to your new path.
See screenshot:
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">
For what it's worth I had this issue and had to go into cPanel where I saw the error message
"Attention! Please register your email IDs used in non-smtp mails through cpanel plugin. Unregistered email IDs will not be allowed in non-smtp emails sent through scripts. Go to Mail section and find "Registered Mail IDs" plugin in paper_lantern theme."
Registering the emails in cPanel (Register Mail IDs) and waiting 10 mins got mine to work.
Hope that helps someone.
When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:
<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />
or the same with image/vnd.microsoft.icon
, and it will work with all browsers.
Note: There is no IANA specification for the MIME-type image/x-icon
, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon
.
The only case in which there is a difference is if you were trying to use an .ico file in an <img>
tag (which is pretty unusual).
Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon
. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico
files as images, use png
.
Escape your HTML tags ...
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
UserResult nextFrag= new UserResult();
this.getFragmentManager().beginTransaction()
.replace(R.id.content_frame, nextFrag, null)
.addToBackStack(null)
.commit();
}
Determine if 2 lists have the same elements, regardless of order?
Inferring from your example:
x = ['a', 'b']
y = ['b', 'a']
that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).
set(x) == set(y) # prefer this if elements are hashable
In the case that the elements are hashable, but non-unique, the collections.Counter
also works semantically as a multiset, but it is far slower:
from collections import Counter
Counter(x) == Counter(y)
Prefer to use sorted
:
sorted(x) == sorted(y)
if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.
An empirical experiment concludes that one should prefer set
, then sorted
. Only opt for Counter
if you need other things like counts or further usage as a multiset.
First setup:
import timeit
import random
from collections import Counter
data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:] # copy the list into a new one
def sets_equal():
return set(data) == set(data2)
def counters_equal():
return Counter(data) == Counter(data2)
def sorted_lists_equal():
return sorted(data) == sorted(data2)
And testing:
>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844
So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.
When a query takes that long, I would advice to run it asynchronously and use a callback function for when it's complete.
I don't have much experience with ASP.NET, but maybe you can use AJAX for this asynchronous behavior.
Typically a web page should load in mere seconds, not minutes. Don't keep your users waiting for so long!
The inner join will give the result of matched records between two tables where as the cross join gives you the possible combinations between two tables.
You can redirect output to a file and then read the file:
return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close
Use the rails style sheet tag to link your main.css like this
<%= stylesheet_link_tag "main" %>
Go to
config/initializers/assets.rb
Once inside the assets.rb
add the following code snippet just below the Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( main.css )
Restart your server.
I have an idea, which can work and it most likely to be very fast. You can sub-sample an image to say 80x60 resolution or comparable, and convert it to grey scale (after subsampling it will be faster). Process both images you want to compare. Then run normalised sum of squared differences between two images (the query image and each from the db), or even better Normalised Cross Correlation, which gives response closer to 1, if both images are similar. Then if images are similar you can proceed to more sophisticated techniques to verify that it is the same images. Obviously this algorithm is linear in terms of number of images in your database so even though it is going to be very fast up to 10000 images per second on the modern hardware. If you need invariance to rotation, then a dominant gradient can be computed for this small image, and then the whole coordinate system can be rotated to canonical orientation, this though, will be slower. And no, there is no invariance to scale here.
If you want something more general or using big databases (million of images), then you need to look into image retrieval theory (loads of papers appeared in the last 5 years). There are some pointers in other answers. But It might be overkill, and the suggest histogram approach will do the job. Though I would think combination of many different fast approaches will be even better.
As per the Javadoc, the MimeMessage#setText()
sets a default mime type of text/plain
, while you need text/html
. Rather use MimeMessage#setContent()
instead.
message.setContent(someHtmlMessage, "text/html; charset=utf-8");
For additional details, see:
How about this:
import sys
import subprocess
theproc = subprocess.Popen("myscript.py", shell = True)
theproc.communicate() # ^^^^^^^^^^^^
This tells subprocess
to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.
Additionally, this will search the PATH for "myscript.py" - which could be desirable.
It's not working because console.log() it's not in a "executable area" of the class "App".
A class is a structure composed by attributes and methods.
The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()
console.log('It works here')_x000D_
_x000D_
@Component({..)_x000D_
export class App {_x000D_
s: string = "Hello2";_x000D_
_x000D_
constructor() {_x000D_
console.log(this.s) _x000D_
} _x000D_
}
_x000D_
Think of class like a plain javascript object.
Would it make sense to expect this to work?
class: {_x000D_
s: string,_x000D_
console.log(s)_x000D_
}
_x000D_
If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.
I wrote small js-utility to crop and resize image on front-end. Here is link on GitHub project. Also you can get blob from final image to send it.
import imageSqResizer from './image-square-resizer.js'
let resizer = new imageSqResizer(
'image-input',
300,
(dataUrl) =>
document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);
//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;
If after 6 years you still have the issue, this should solve it :)
cols = [c for c in df.columns if df[c].dtype in ['object', 'datetime64[ns]']]
Two options…
format-detection
meta tag.To remove all auto-formatting for telephone numbers, add this to the head
of your html
document:
<meta name="format-detection" content="telephone=no">
View more Apple-Specific Meta Tag Keys.
Note: If you have phone numbers on the page with these numbers you should manually format them as links:
<a href="tel:+1-555-555-5555">1-555-555-5555</a>
css
?Two css
options:
Target links with href
values starting with tel
by using this css attribute selector:
a[href^="tel"] {
color: inherit; /* Inherit text color of parent element. */
text-decoration: none; /* Remove underline. */
/* Additional css `propery: value;` pairs here */
}
Alternatively, you can when you can’t set a meta tag—such as in html email—wrap phone numbers in link/anchor tags (<a href=""></a>
) and then target their styles using css similar to the following and adjust the specific properties you need to reset:
a[x-apple-data-detectors] {
color: inherit !important;
text-decoration: none !important;
font-size: inherit !important;
font-family: inherit !important;
font-weight: inherit !important;
line-height: inherit !important;
}
If you want to target specific links, use classes on your links and then update the css selector above to a[x-apple-data-detectors].class-name
.
Here is what I write to get the timestamp in millionseconds.
#include<sys/time.h>
long long timeInMilliseconds(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
I was in your shoes for a while and finally ended up using node.js, because it can do hybrid solutions like having web and socket server in one. So php backend can submit requests thru http to node web server and then broadcast it with websocket. Very efficiant way to go.
pull vs fetch:
The way I understand this, is that git pull
is simply a git fetch
followed by git merge
. I.e. you fetch the changes from a remote branch and then merge it into the current branch.
merge vs rebase:
A merge will do as the command says; merge the differences between current branch and the specified branch (into the current branch). I.e. the command git merge another_branch
will the merge another_branch
into the current branch.
A rebase works a bit differently and is kind of cool. Let's say you perform the command git rebase another_branch
. Git will first find the latest common version between the current branch and another_branch
. I.e. the point before the branches diverged. Then git will move this divergent point to the head of the another_branch
. Finally, all the commits in the current branch since the original divergent point are replayed from the new divergent point. This creates a very clean history, with fewer branches and merges.
However, it is not without pitfalls! Since the version history is "rewritten", you should only do this if the commits only exists in your local git repo. That is: Never do this if you have pushed the commits to a remote repo.
The explanation on rebasing given in this online book is quite good, with easy-to-understand illustrations.
pull with rebasing instead of merge
I'm actually using rebase quite a lot, but usually it is in combination with pull:
git pull --rebase
will fetch remote changes and then rebase instead of merge. I.e. it will replay all your local commits from the last time you performed a pull. I find this much cleaner than doing a normal pull with merging, which will create an extra commit with the merges.
I'm not sure there's a clear-cut definition of "framework". Sometimes a large set of libraries is called a framework, but I think the typical use of the word is closer to the definition aioobe brought.
This very nice article sums up the difference between just a set of libraries and a framework:
A framework can be defined as a set of libraries that say “Don’t call us, we’ll call you.”
How does a framework help you? Because instead of writing something from scratch, you basically just extend a given, working application. You get a lot of productivity this way - sometimes the resulting application can be far more elaborate than you could have done on your own in the same time frame - but you usually trade in a lot of flexibility.
It obtains a reference to the class object with the FQCN (fully qualified class name) oracle.jdbc.driver.OracleDriver
.
It doesn't "do" anything in terms of connecting to a database, aside from ensure that the specified class is loaded by the current classloader. There is no fundamental difference between writing
Class<?> driverClass = Class.forName("oracle.jdbc.driver.OracleDriver");
// and
Class<?> stringClass = Class.forName("java.lang.String");
Class.forName("com.example.some.jdbc.driver")
calls show up in legacy code that uses JDBC because that is the legacy way of loading a JDBC driver.
From The Java Tutorial:
In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method
Class.forName
. This methods required an object of typejava.sql.Driver
. Each JDBC driver contains one or more classes that implements the interfacejava.sql.Driver
.
...
Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the methodClass.forName
.)
I guess compatible way:
hash=`genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5`
but I prefer
hash="$(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)"
Use the tee
command:
echo "hello" | tee logfile.txt
Add this code on values anim
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:duration="@android:integer/config_longAnimTime"
android:fromXScale="0.2"
android:fromYScale="0.2"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"/>
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="@android:integer/config_longAnimTime"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
</set>
call on styles.xml
<style name="DialogScale">
<item name="android:windowEnterAnimation">@anim/scale_in</item>
<item name="android:windowExitAnimation">@anim/scale_out</item>
</style>
In Java code: set Onclick
public void onClick(View v) {
fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
// Dialogs.fab_onclick(R.style.DialogScale, "Scale");
}
setup on method:
alertDialog.getWindow().getAttributes().windowAnimations = type;
To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:
JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);
And if you have an image:
JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);
But, I believe you want to make the label such that there are only 2 words on 1 line.
In that case try this:
String urText="<html>You can<br>use basic HTML<br>in Swing<br> components,"
+"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);
The case of if abc == nil
is used when you are declaring a var and want to force unwrap and then check for null. Here you know this can be nil
and you can check if != nil
use the NSString
functions from foundation.
In case of String?
you are not aware what is wrapped at runtime and hence you have to use if-let and perform the check.
You were doing following but without "!". Hope this clears it.
From apple docs look at this:
let assumedString: String! = "An implicitly unwrapped optional string."
You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:
if assumedString != nil {
println(assumedString)
}
// prints "An implicitly unwrapped optional string."
Xavi's code was allmost fully working. But when navigating to another page, submitting a form, then being redirected to the page with my tabs was not loading the saved tab at all.
localStorage to the rescue (slightly changed Nguyen's code):
$('a[data-toggle="tab"]').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab != null) {
$('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
}
I had this same problem in a Maven project. After creating the src/test/java folder within the project the error went away.
I found a pretty good and simple tutorial about this issue. I think it works great (and though it supports IE, I just tell my clients to use other browsers):
CSS background transparency without affecting child elements, through RGBa and filters
From there you can add gradient support, etc.
if you have this error :
configure: error: Either a previously installed pkg-config or "glib-2.0 >= 2.16" could not be found. Please set GLIB_CFLAGS and GLIB_LIBS to the correct values or pass --with-internal-glib to configure to use the bundled copy.
Instead of do this command :
$ ./configure && make install
Do that :
./configure --with-internal-glib && make install
use
=VLOOKUP(D4,F4:G9,2)
with the range F4:G9:
0 0.1
1 0.15
5 0.2
15 0.3
30 1
100 1.3
and D4
being the value in question, e.g. 18.75
-> result: 0.3
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
I would use the following code in C# (VB.NET is not as simple).
The code assigns the value if it is not null/DBNull, otherwise it asigns the default which could be set to the LHS value allowing the compiler to ignore the assign.
oSomeObject.IntMemeber = oRow["Value"] as int? ?? iDefault;
oSomeObject.StringMember = oRow["Name"] as string ?? sDefault;
$.validator.addMethod("mydate", function (value, element) {
return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);
});
you can input like yyyy-mm-dd
also yyyy/mm/dd
but can't judge the the size of the month sometime Feb just 28 or 29 days.
SELECT length(actual_project_name),actual_project_name,
SUBSTRING_INDEX(actual_project_name,'-',1) as aaaaaa,
SUBSTRING_INDEX(actual_project_name, '-', -1) as actual_project_number,
concat(SUBSTRING_INDEX(actual_project_name,'-',1),SUBSTRING_INDEX(actual_project_name, '-', -1)) as a
FROM ctts.test22
order by
SUBSTRING_INDEX(actual_project_name,'-',1) asc,cast(SUBSTRING_INDEX(actual_project_name, '-', -1) as unsigned) asc
You can use a tool like Valgrind to do this.
I don't recommend storing passwords in a script, but this is a way to what you indicate:
use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );
say ( $user_table{ $name } eq $password ? 'You have gained access.'
: 'Access denied!'
);
Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>
You can use a subquery:
SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');
and if you need to show all columns from both tables:
SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'
You shouldn't be calling .ToString()
.
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString
and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString()
.
Html.Raw
returns an HtmlString
instance that wraps the original string.
The Razor page output knows not to escape HtmlString
instances.
However, calling HtmlString.ToString()
just returns the original string
value again; it doesn't accomplish anything.
You don't have that many options.
You'll probably want to use one of:
node-soap
)You can also use the following code to open new page in new tab.
<asp:Button ID="Button1" runat="server" Text="Go"
OnClientClick="window.open('yourPage.aspx');return false;"
onclick="Button3_Click" />
And just call Response.Redirect("yourPage.aspx"); behind button event.
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
The -jar
option only works if the JAR file is an executable JAR file, which means it must have a manifest file with a Main-Class
attribute in it.
If it's not an executable JAR, then you'll need to run the program with something like:
java -cp app.jar com.somepackage.SomeClass
where com.somepackage.SomeClass
is the class that contains the main
method to run the program.
You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:
$ ls | egrep '.+\..+'
If you log the
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./csr.pem', 'utf8')
};
You might notice there are invalid characters due to improper encoding.
There is a property for this called keyboardType
.
What you'll want to do is replace where you have strings @"Number Pad
and @"Default
with UIKeyboardTypeNumberPad
and UIKeyboardTypeDefault
.
Your new code should look something like this:
if(user is prompted for numeric input only)
[textField setKeyboardType:UIKeyboardTypeNumberPad];
else if(user is prompted for alphanumeric input)
[textField setKeyboardType:UIKeyboardTypeDefault];
Good Luck!
break
would stop the foreach
loop completely, continue
would skip to the next DataRow
.
The possibility could be, the SSH might not be enabled on your server/system.
sudo apt update
sudo apt install openssh-server
Now try to access the server/system with following command
ssh username@ip_address
I'm not absolutely sure I got your question correctly, but it seems you want something like this:
Class c = null;
try {
c = Class.forName("com.path.to.ImplementationType");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
T interfaceType = null;
try {
interfaceType = (T) c.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Where T can be defined in method level or in class level, i.e. <T extends InterfaceType>
Your receiver:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, YourService.class);
context.startService(myIntent);
}
}
Your AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcast.receiver.example"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
<activity android:name=".BR_Example"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
<receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
<!-- Adding the permission -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
The answer depends on what do you need a loop for.
of course you can have a loop similar to Java:
for i in xrange(len(my_list)):
but I never actually used loops like this,
because usually you want to iterate
for obj in my_list
or if you need an index as well
for index, obj in enumerate(my_list)
or you want to produce another collection from a list
map(some_func, my_list)
[somefunc[x] for x in my_list]
also there are itertools
module that covers most of iteration related cases
also please take a look at the builtins like any
, max
, min
, all
, enumerate
I would say - do not try to write Java-like code in python. There is always a pythonic way to do it.
String jsonErrorString=((HttpClientErrorException)exception).getResponseBodyAsString();
JSONObject jsonObj=null;
String errorDetails=null;
String status=null;
try {
jsonObj = new JSONObject(jsonErrorString);
int index =jsonObj.getString("detail").indexOf(":");
errorDetails=jsonObj.getString("detail").substring(index);
status=jsonObj.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
item.put("status", status);
item.put("errordetailMsg", errorDetails);
Best way to swap images with javascript with left vertical clickable thumbnails
SCRIPT FILE: function swapImages() {
window.onload = function () {
var img = document.getElementById("img_wrap");
var imgall = img.getElementsByTagName("img");
var firstimg = imgall[0]; //first image
for (var a = 0; a <= imgall.length; a++) {
setInterval(function () {
var rand = Math.floor(Math.random() * imgall.length);
firstimg.src = imgall[rand].src;
}, 3000);
imgall[1].onmouseover = function () {
//alert("what");
clearInterval();
firstimg.src = imgall[1].src;
}
imgall[2].onmouseover = function () {
clearInterval();
firstimg.src = imgall[2].src;
}
imgall[3].onmouseover = function () {
clearInterval();
firstimg.src = imgall[3].src;
}
imgall[4].onmouseover = function () {
clearInterval();
firstimg.src = imgall[4].src;
}
imgall[5].onmouseover = function () {
clearInterval();
firstimg.src = imgall[5].src;
}
}
}
}
This can be achieved with the writing-mode
property. If you set an element's writing-mode
to a vertical writing mode, such as vertical-lr
, its descendants' percentage values for padding and margin, in both dimensions, become relative to height instead of width.
From the spec:
. . . percentages on the margin and padding properties, which are always calculated with respect to the containing block width in CSS2.1, are calculated with respect to the inline size of the containing block in CSS3.
The definition of inline size:
A measurement in the inline dimension: refers to the physical width (horizontal dimension) in horizontal writing modes, and to the physical height (vertical dimension) in vertical writing modes.
Example, with a resizable element, where horizontal margins are relative to width and vertical margins are relative to height.
.resize {_x000D_
width: 400px;_x000D_
height: 200px;_x000D_
resize: both;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
height: 100%;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.middle {_x000D_
writing-mode: vertical-lr;_x000D_
margin: 0 10%;_x000D_
width: 80%;_x000D_
height: 100%;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
writing-mode: horizontal-tb;_x000D_
margin: 10% 0;_x000D_
width: 100%;_x000D_
height: 80%;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="resize">_x000D_
<div class="outer">_x000D_
<div class="middle">_x000D_
<div class="inner"></div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Using a vertical writing mode can be particularly useful in circumstances where you want the aspect ratio of an element to remain constant, but want its size to scale in correlation to its height instead of width.
same problem happened to me, From this
I have faced the same issue, to solve it:
1- delete
(or move
) the projects folder (AndroidStudioProjects
).
2- Run
the Android-Studio (a WELCOME screen will started).
3- From Welcome Screen choose, "Configure
-> Project Defaults
-> Project Structure
)
4- Under Platform Settings choose SDKs
.
5- Select Android SDK
-> right_click delete
.
6- Right_click
-> New Sdk
-> Android SDK
-> choose your SDK dir
-> then OK
.
7- Choose the Build target
-> apply
-> OK
. enjoy
You can use this simple script to see commits that are not merged
#!/bin/bash
# Show commits that exists only on branch and not in current
# Usage:
# git branch-notmerge <branchname>
#
# Setup git alias
# git config alias.branch-notmerge [path/to/this/script]
grep -Fvf <(git log --pretty=format:'%H - %s') <(git log $1 --pretty=format:'%H - %s')
You can use also tool git-wtf that will display state of branches
string::npos
is a constant (probably -1
) representing a non-position. It's returned by method find
when the pattern was not found.
if you are using XDocument.Load(url);
to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException
See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."
A simplified shortcut I've tried is this:
int x[] = {1,2,3};
String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
System.out.println(printableText);
It will print
1
2
3
No loops required in this approach and it is best for small arrays only
The canvas
element provides a toDataURL
method which returns a data:
URL that includes the base64-encoded image data in a given format. For example:
var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default
Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.
The toDataURL
method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.
For more information see the MDN docs on the canvas
API, which includes details on toDataURL
, and the Wikipedia article on the data:
URI scheme, which includes details on the format of the URI you'll receive from this call.
Using Java Web Start, you can install multiple JRE, then call what you need. On win, you can make a .bat file:
1- online version: <your_JRE_version\bin\javaws.exe> -localfile -J-Djnlp.application.href=<the url of .jnlp file.jnlp> -localfile -J "<path_temp_jnlp_file_.jnlp>"
2- launch from cache: <your_JRE_version\bin\javaws.exe> -localfile -J "<path_of_your_local_jnlp_file.jnlp>"
curl -iv https://your.domain.io
That will give you cert and header output if you do not wish to use openssl command.
I met the same problems and tried many methods to solve it but doesn't work. Finally , I found the by my way. Some reference enter link description here
Hope my code can help someone future. I have been spent more than two days to solve it. Below is my Code:
//get current in useing excel
Process[] excelProcsOld = Process.GetProcessesByName("EXCEL");
Excel.Application myExcelApp = null;
Excel.Workbooks excelWorkbookTemplate = null;
Excel.Workbook excelWorkbook = null;
try{
//DO sth using myExcelApp , excelWorkbookTemplate, excelWorkbook
}
catch (Exception ex ){
}
finally
{
//Compare the EXCEL ID and Kill it
Process[] excelProcsNew = Process.GetProcessesByName("EXCEL");
foreach (Process procNew in excelProcsNew)
{
int exist = 0;
foreach (Process procOld in excelProcsOld)
{
if (procNew.Id == procOld.Id)
{
exist++;
}
}
if (exist == 0)
{
procNew.Kill();
}
}
}
I end up here while googling for the problem with not printable character. I use MySQL UTF-8
general_ci
and deal with polish language. For problematic strings I have to procced as follows:
text=text.replace('\xc2\xa0', ' ')
It is just fast workaround and you probablly should try something with right encoding setup.
Ordinarily adding '%' to the int value of a char will not work when encoding, the value is supposed to the the hex equivalent. e.g '/' is '%2F' not '%47'.
I think this is the best and concise solutions for both url encoding and decoding (No much header dependencies).
string urlEncode(string str){
string new_str = "";
char c;
int ic;
const char* chars = str.c_str();
char bufHex[10];
int len = strlen(chars);
for(int i=0;i<len;i++){
c = chars[i];
ic = c;
// uncomment this if you want to encode spaces with +
/*if (c==' ') new_str += '+';
else */if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') new_str += c;
else {
sprintf(bufHex,"%X",c);
if(ic < 16)
new_str += "%0";
else
new_str += "%";
new_str += bufHex;
}
}
return new_str;
}
string urlDecode(string str){
string ret;
char ch;
int i, ii, len = str.length();
for (i=0; i < len; i++){
if(str[i] != '%'){
if(str[i] == '+')
ret += ' ';
else
ret += str[i];
}else{
sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
ret += ch;
i = i + 2;
}
}
return ret;
}
private String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
DateFormat dateFormat = new SimpleDateFormat(" d'" + dayNumberSuffix + "' MMMM yyyy");
return dateFormat.format(currentCalDate.getTime());
}
private String getDayNumberSuffix(int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.
Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:
/pages/en/faqs/faq-page1.html
Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them
index.html
is:
/pages/en/faqs/index.html
if called from /pages/en/faqs/faq-page1.html
/pages/index.html
if called from /pages/example.html
There are also two special directory names: .
and ..
:
.
means "current directory"..
means "parent directory"You can use them to build relative paths:
../index.html
is /pages/en/index.html
if called from /pages/en/faqs/faq-page1.html
../../index.html
is /pages/index.html
if called from /pages/en/faqs/faq-page1.html
Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:
In case anyone arrives here via google looking for the opposite (i.e. how to replace all NAs in a data.frame with 0), the answer is
df[is.na(df)] <- 0
OR
Using dplyr / tidyverse
library(dplyr)
mtcars %>% replace(is.na(.), 0)
I had problems with this recently, i use this code and work fine for me.
var data = 'Peter';
db.User.find({'name' : new RegExp(data, 'i')}, function(err, docs){
cb(docs);
});
Use directly /Peter/i
work, but i use '/'+data+'/i'
and not work for me.
Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code
class Program
{
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";
//duplicate file path
string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile);
Console.ReadKey();
}
}
Source: File I/O in C# (Read, Write, Delete, Copy file using C#)
With the help of user=User.query.filter_by(username=form.username.data).first()
statement you will get the specified user in user
variable.
Now you can change the value of the new object variable like user.no_of_logins += 1
and save the changes with the session
's commit method.
for MacOS, make sure you know where the GO install
export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin
You can use OPENROWSET for this. Have a look. I've also included the sp_configure code to enable Ad Hoc Distributed Queries, in case it isn't already enabled.
CREATE PROC getBusinessLineHistory
AS
BEGIN
SELECT * FROM sys.databases
END
GO
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
SELECT * INTO #MyTempTable FROM OPENROWSET('SQLNCLI', 'Server=(local)\SQL2008;Trusted_Connection=yes;',
'EXEC getBusinessLineHistory')
SELECT * FROM #MyTempTable
The move_uploaded_file
will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file
You can use PHP to add a stylesheet for IE 10
Like:
if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
<link rel="stylesheet" type="text/css" href="../ie10.css" />
}
Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.
So, if you register the scroll
event handler and check window.pageYOffset
inside that event handler, everything works just fine.
Yes you can put the break-point on client side page in Visual studio
First Put the debugger in java-script code and run the page in browser
debugger
After that open your page in browser and view the inspect element you see the following view
Use jQuery
.In the HTML page -
<button type="button">Click Me</button>
<script>
$(document).ready(function() {
$("button").click(function(){
$.ajax({
url:"php_page.php", //the page containing php script
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
})
</script>
Php page -
echo "Hello";
MySQL is most likely in STRICT mode.
Try running SET GLOBAL sql_mode=''
or edit your my.cnf to make sure you aren't setting STRICT_ALL_TABLES
or the like.
Do not forget to verify if your text editor encodes properly your code in UTF-8.
Otherwise, you may have invisible characters that are not interpreted as UTF-8.
You should add reference to PresentationCore.dll.
You can do like below to achieve your result:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
You have to invoke this class on the top of your page or class :
using System.Configuration;
Then you can use this Method that returns the connection string to be ready to passed to the sqlconnection object to continue your work as follows:
private string ReturnConnectionString()
{
// Put the name the Sqlconnection from WebConfig..
return ConfigurationManager.ConnectionStrings["DBWebConfigString"].ConnectionString;
}
Just to make a clear clarification this is the value in the web Config:
<add name="DBWebConfigString" connectionString="....." /> </connectionStrings>
you can use follow code in asp.net core 2.0:
public IActionResult index()
{
return new ContentResult() { Content = "My error message", StatusCode = (int)HttpStatusCode.Unauthorized };
}
Don't BULK INSERT into your real tables directly.
I would always
dbo.Employee_Staging
(without the IDENTITY
column) from the CSV fileand then copy the data across to the real table with a T-SQL statement like:
INSERT INTO dbo.Employee(Name, Address)
SELECT Name, Address
FROM dbo.Employee_Staging
for those who can not solve this issue by any means, you can try this: manually map drive into the docker host:
https://github.com/docker/for-win/issues/466#issuecomment-416682825
The research is here: https://github.com/docker/for-win/issues/466#issuecomment-398305463
This answer describes a solution using MVVM.
This solution is great if you want to add a logging box to a window, that automatically scrolls to the bottom each time a new logging message is added.
Once these attached properties are added, they can be reused anywhere, so it makes for very modular and reusable software.
Add this XAML:
<TextBox IsReadOnly="True"
Foreground="Gainsboro"
FontSize="13"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
attachedBehaviors:TextBoxApppendBehaviors.AppendText="{Binding LogBoxViewModel.AttachedPropertyAppend}"
attachedBehaviors:TextBoxClearBehavior.TextBoxClear="{Binding LogBoxViewModel.AttachedPropertyClear}"
TextWrapping="Wrap">
Add this attached property:
public static class TextBoxApppendBehaviors
{
#region AppendText Attached Property
public static readonly DependencyProperty AppendTextProperty =
DependencyProperty.RegisterAttached(
"AppendText",
typeof (string),
typeof (TextBoxApppendBehaviors),
new UIPropertyMetadata(null, OnAppendTextChanged));
public static string GetAppendText(TextBox textBox)
{
return (string)textBox.GetValue(AppendTextProperty);
}
public static void SetAppendText(
TextBox textBox,
string value)
{
textBox.SetValue(AppendTextProperty, value);
}
private static void OnAppendTextChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if (args.NewValue == null)
{
return;
}
string toAppend = args.NewValue.ToString();
if (toAppend == "")
{
return;
}
TextBox textBox = d as TextBox;
textBox?.AppendText(toAppend);
textBox?.ScrollToEnd();
}
#endregion
}
And this attached property (to clear the box):
public static class TextBoxClearBehavior
{
public static readonly DependencyProperty TextBoxClearProperty =
DependencyProperty.RegisterAttached(
"TextBoxClear",
typeof(bool),
typeof(TextBoxClearBehavior),
new UIPropertyMetadata(false, OnTextBoxClearPropertyChanged));
public static bool GetTextBoxClear(DependencyObject obj)
{
return (bool)obj.GetValue(TextBoxClearProperty);
}
public static void SetTextBoxClear(DependencyObject obj, bool value)
{
obj.SetValue(TextBoxClearProperty, value);
}
private static void OnTextBoxClearPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if ((bool)args.NewValue == false)
{
return;
}
var textBox = (TextBox)d;
textBox?.Clear();
}
}
Then, if you're using a dependency injection framework such as MEF, you can place all of the logging-specific code into it's own ViewModel:
public interface ILogBoxViewModel
{
void CmdAppend(string toAppend);
void CmdClear();
bool AttachedPropertyClear { get; set; }
string AttachedPropertyAppend { get; set; }
}
[Export(typeof(ILogBoxViewModel))]
public class LogBoxViewModel : ILogBoxViewModel, INotifyPropertyChanged
{
private readonly ILog _log = LogManager.GetLogger<LogBoxViewModel>();
private bool _attachedPropertyClear;
private string _attachedPropertyAppend;
public void CmdAppend(string toAppend)
{
string toLog = $"{DateTime.Now:HH:mm:ss} - {toAppend}\n";
// Attached properties only fire on a change. This means it will still work if we publish the same message twice.
AttachedPropertyAppend = "";
AttachedPropertyAppend = toLog;
_log.Info($"Appended to log box: {toAppend}.");
}
public void CmdClear()
{
AttachedPropertyClear = false;
AttachedPropertyClear = true;
_log.Info($"Cleared the GUI log box.");
}
public bool AttachedPropertyClear
{
get { return _attachedPropertyClear; }
set { _attachedPropertyClear = value; OnPropertyChanged(); }
}
public string AttachedPropertyAppend
{
get { return _attachedPropertyAppend; }
set { _attachedPropertyAppend = value; OnPropertyChanged(); }
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Here's how it works:
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
awk is very cool, but why not keep it simple?
num=$(echo $var | grep -o "," | wc -l)
What about .GlobalEnv$a <- "new"
? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign()
function.
Rename-Computer was removed from CTP3 because there are a lot of things done when renaming a computer and MS either didn't want to recreate that process or couldn't include all of the necessary bits. I think Jefferey Snover said to just use netdom.exe instead, as that is the best practice for renaming a computer on the command-line. Not the answer you were looking for, but should point you in the right direction
In Jenkins , we have the format is as:
Minute(0-59) Hour(0-23) Day(1-7) Month(1-12) Day of the Week
You'll have to find the index of the person
in your persons
array, then use the array's splice
method:
$scope.persons.splice( $scope.persons.indexOf(person), 1 );
You might get better results if you try:
console.log(JSON.stringify(functor));
To my knowledge none of the given answers guarantee correct behavior with null termination. Until someone shows me differently I wrote my own static class for handling this with the following methods:
// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
int strlen = 0;
while
(
(startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
&& buffer[startIndex + strlen] != 0 // The typical null terimation check
)
{
++strlen;
}
return strlen;
}
// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
strlen = StringLength(buffer, startIndex);
byte[] c_str = new byte[strlen];
Array.Copy(buffer, startIndex, c_str, 0, strlen);
return Encoding.UTF8.GetString(c_str);
}
The reason for the startIndex
was in the example I was working on specifically I needed to parse a byte[]
as an array of null terminated strings. It can be safely ignored in the simple case
On your solution explorer window, right click to References, select Add Reference, go to .NET tab, find and add Microsoft.CSharp.
Alternatively add the Microsoft.CSharp NuGet package.
Install-Package Microsoft.CSharp
when you need to send files through a specific SSH port:
rsync -azP -e "ssh -p PORT_NUMBER" source destination
example
rsync -azP -e "ssh -p 2121" /path/to/files/source user@remoteip:/path/to/files/destination
In order to stay on the same page on submit you can leave action empty (action=""
) into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;"
) and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>
.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
You can stop a query which is being processed by this
Find the Id of the query process by => show processlist;
Then => kill id;
I use the Apache commons HTTP Client package to do this in my current project and it works fine with SSL and a self-signed cert (after installing it into cacerts like you mentioned). Please take a look at it here: