You are looking for the static method Math.Pow()
.
I got that error when I accidentally used load()
instead of source()
or readRDS()
.
From the git-branch manual page:
git branch --contains <commit>
Only list branches which contain the specified commit (HEAD if not specified). Implies
--list
.
git branch -r --contains <commit>
Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".
As noted by Carl Walsh, this applies only to the default refspec
fetch = +refs/heads/*:refs/remotes/origin/*
If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:
git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>
See also this git ready article.
The
--contains
tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.
$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date: Wed Apr 1 20:38:59 2009 -0400
Green all around, finally.
$ git branch --contains d590f2
tests
* master
Note: if the commit is on a remote tracking branch, add the -a
option.
(as MichielB comments below)
git branch -a --contains <commit>
MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry
:
Because
git cherry
compares the changeset rather than the commit id (sha1), you can usegit cherry
to find out if a commit you made locally has been applied<upstream>
under a different commit id.
For example, this will happen if you’re feeding patches<upstream>
via email rather than pushing or pulling commits directly.
__*__*__*__*__> <upstream>
/
fork-point
\__+__+__-__+__+__-__+__> <head>
(Here, the commits marked '-
' wouldn't show up with git cherry
, meaning they are already present in <upstream>
.)
It might be a workaround but this solved my problem:
ObjectListing listing = s3.listObjects( bucketName, prefix );
List<S3ObjectSummary> summaries = listing.getObjectSummaries();
while (listing.isTruncated()) {
listing = s3.listNextBatchOfObjects (listing);
summaries.addAll (listing.getObjectSummaries());
}
MY solution in maven 3.5.4 ,use nexus, in eclipse:
<dependency>
<groupId>yilin.sheng</groupId>
<artifactId>webspherecore</artifactId>
<version>LATEST</version>
</dependency>
then in eclipse: atl + F5
, and choose the force update of snapshots/release
it works for me.
You can ssh
directly from the Terminal on Mac, but you need to use a .PEM
key rather than the putty
.PPK
key. You can use PuttyGen on Windows to convert from .PEM
to .PPK
, I'm not sure about the other way around though.
You can also convert the key using putty
for Mac via port
or brew
:
sudo port install putty
or
brew install putty
This will also install puttygen
. To get puttygen
to output a .PEM
file:
puttygen privatekey.ppk -O private-openssh -o privatekey.pem
Once you have the key, open a terminal window and:
ssh -i privatekey.pem [email protected]
The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.
chmod go-rw privatekey.pem
import re
if re.search('(?i)Mandy Pande:', line):
...
You can push your local branch to a new remote branch like so:
git push origin master:test
(Assuming origin
is your remote, master
is your local branch name and test
is the name of the new remote branch, you wish to create.)
If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u
(on newer versions of Git) or --set-upstream
, so:
git push -u origin master:test
or
git push --set-upstream origin master:test
...will create a new remote branch, named test
, in remote repository origin
, based on your local master
, and setup your local master
to track it.
An array in PHP is a map of keys to values:
$array = array();
$array["yellow"] = 3;
$array["green"] = 4;
If you want to do something with each key-value-pair in your array, you can use the foreach
control structure:
foreach ($array as $key => $value)
The $array variable is the array you will be using. The $key and $value variables will contain a key-value-pair in every iteration of the foreach
loop. In this example, they will first contain "yellow" and 3, then "green" and 4.
You can use an alternative notation if you don't care about the keys:
foreach ($array as $value)
How about more simply: Select * from tblStudents where [name] = replace(YourName,"'","''")
please see below answer.
Custom_CameraActivity.java
public class Custom_CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* @return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:id="@+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Capture" />
</LinearLayout>
Add Below Lines to your androidmanifest.xml file
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
There is an in-built stopword list in NLTK
made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html
>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop]
['foo', 'bar', 'sentence']
I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?
Yes you can. MySQL connectors use TCP for connection, and in JS there is an little modified version of TCP client called Websocket. But you can't directly connect to MySQL server with websocket. You will need some 3rd party bridge between websocket and mysql. It receive query from websocket, send it to mysql, response result and resend to JS.
And this is my example bridge written in C# with websocket-sharp library:
class JSQLBridge : WebSocketBehavior
{
MySqlConnection conn;
protected override void OnMessage(MessageEventArgs e)
{
if (conn == null)
{
try
{
conn = new MySqlConnection(e.Data);
conn.Open();
}
catch (Exception exc)
{
Send(exc.Message);
}
}
else
{
try
{
MySqlCommand cmd = new MySqlCommand(e.Data, conn);
cmd.ExecuteNonQuery();
Send("success");
}
catch (Exception exc)
{
Send(exc.Message);
}
}
}
protected override void OnClose(CloseEventArgs e)
{
if (conn != null)
conn.Close();
}
}
JS side:
var ws = new WebSocket("ws://localhost/");
ws.send("server=localhost;user=root;database=mydb;");
ws.send("select * from users");
DECLARE @source varbinary(max),
@encoded_base64 varchar(max),
@decoded varbinary(max)
SET @source = CONVERT(varbinary(max), 'welcome')
-- Convert from varbinary to base64 string
SET @encoded_base64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable
("@source"))', 'varchar(max)')
-- Convert back from base64 to varbinary
SET @decoded = CAST(N'' AS xml).value('xs:base64Binary(sql:variable
("@encoded_base64"))', 'varbinary(max)')
SELECT
CONVERT(varchar(max), @source) AS [Source varchar],
@source AS [Source varbinary],
@encoded_base64 AS [Encoded base64],
@decoded AS [Decoded varbinary],
CONVERT(varchar(max), @decoded) AS [Decoded varchar]
This is usefull for encode and decode.
By Bharat J
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).
Difference between show() and css({'display':'block'})
Assuming you have this at the beginning:
<span id="thisElement" style="display: none;">Foo</span>
when you call:
$('#thisElement').show();
you will get:
<span id="thisElement" style="">Foo</span>
while:
$('#thisElement').css({'display':'block'});
does:
<span id="thisElement" style="display: block;">Foo</span>
so, yes there's a difference.
Difference between hide() and css({'display':'none'})
same as above but change these into hide() and display':'none'......
Another difference
When .hide()
is called the value of the display property is saved in jQuery's data cache, so when .show()
is called, the initial display value is restored!
I'm adding this answer (for myself) as relevant to custom formatting.
For underscore yyyy_MM_dd
REPLACE(SUBSTRING(CONVERT(VARCHAR, @dt, 120), 1, 10),'-','_')
you have to do like this in your project level gradle file
allprojects {
repositories {
jcenter()
maven { url "http://dl.appnext.com/" }
maven { url "https://maven.google.com" }
}
}
You coud try java.net.URLClassloader with the url of the folder/jar where your updated class resides and use it instead of the default classloader when creating a new thread.
This feature has been implemented in Postgres 9.1:
CREATE TABLE IF NOT EXISTS myschema.mytable (i integer);
For older versions, here is a function to work around it:
CREATE OR REPLACE FUNCTION create_mytable()
RETURNS void
LANGUAGE plpgsql AS
$func$
BEGIN
IF EXISTS (SELECT FROM pg_catalog.pg_tables
WHERE schemaname = 'myschema'
AND tablename = 'mytable') THEN
RAISE NOTICE 'Table myschema.mytable already exists.';
ELSE
CREATE TABLE myschema.mytable (i integer);
END IF;
END
$func$;
Call:
SELECT create_mytable(); -- call as many times as you want.
Notes:
The columns schemaname
and tablename
in pg_tables
are case-sensitive. If you double-quote identifiers in the CREATE TABLE
statement, you need to use the exact same spelling. If you don't, you need to use lower-case strings. See:
pg_tables
only contains actual tables. The identifier may still be occupied by related objects. See:
If the role executing this function does not have the necessary privileges to create the table you might want to use SECURITY DEFINER
for the function and make it owned by another role with the necessary privileges. This version is safe enough.
Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...
let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);
to prove it:
let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);
enjoy!
select right(convert(varchar(20),getdate(),100),7)
Look for the exact extension for your PHP version here
The Best solution to change background checkbox color
input[type=checkbox] {_x000D_
margin-right: 5px;_x000D_
cursor: pointer;_x000D_
font-size: 14px;_x000D_
width: 15px;_x000D_
height: 12px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:after {_x000D_
position: absolute;_x000D_
width: 10px;_x000D_
height: 15px;_x000D_
top: 0;_x000D_
content: " ";_x000D_
background-color: #ff0000;_x000D_
color: #fff;_x000D_
display: inline-block;_x000D_
visibility: visible;_x000D_
padding: 0px 3px;_x000D_
border-radius: 3px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "?";_x000D_
font-size: 12px;_x000D_
}
_x000D_
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
_x000D_
<input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>
_x000D_
Create a new XML by example named "shadow.xml" at DRAWABLE with the following code (you can modify it or find another better):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/middle_grey"/>
</shape>
</item>
<item android:left="2dp"
android:right="2dp"
android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
</shape>
</item>
</layer-list>
After creating the XML in the LinearLayout or another Widget you want to create shade, you use the BACKGROUND property to see the efect. It would be something like :
<LinearLayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:paddingRight="@dimen/margin_med"
android:background="@drawable/shadow"
android:minHeight="?attr/actionBarSize"
android:gravity="center_vertical">
I am not a coder, but you could save a few lines:
<div>
<select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
<option value="">hire me for real estate</option>
<option value="me!!!">Who is a good Broker? </option>
<option value="yes!!!">Can I buy a house with no down payment</option>
<option value="send me a note!">Get my contact info?</option>
</select>
</div>
<div id="less_is_more"></div>
Here is demo.
https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html
The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:
SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;
python3: Google "list comphrension" if the square bracket syntax is new to you.
with open('data.txt') as f:
lines = [ line.strip( ) for line in list(f) ]
You can get the LayoutParams
of parent LinearLayout
and apply to the individual views this way:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(8,8,8,8);
If you want to write less code in Kotlin
you can do this:
fun Context.openAppSystemSettings() {
startActivity(Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", packageName, null)
})
}
Based on Martin Konecny answer
Java Advanced Imaging is now open source, and provides the operations you need.
or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.
There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.
Although both elements deliver functionally the same result *, I strongly recommend you use <button>
:
input
suggests that the control is editable, or can be edited by the user; button
is far more explicit in terms of the purpose it servesinput[type="submit"]
do not display correctly in some casesPOST
/GET
request to the server* With the exception of <button type="button">
which by default has no specified behaviour.
In summary, I highly discourage use of <input type="submit" />
.
For JavaScript use this function:
function disableselect(e) {return false}
document.onselectstart = new Function (return false)
document.onmousedown = disableselect
to enable the selection use this:
function reEnable() {return true}
and use this function anywhere you want:
document.onclick = reEnable
If you created ImageView
from Java Class
ImageView img = new ImageView(this);
//Here we are setting the image in image view
img.setImageResource(R.drawable.my_image);
The correct version of your script is as follows;
FILE="cat test"
$FILE | \
while read CMD; do
echo $CMD
done
However this kind of indirection --putting your command in a variable named FILE-- is unnecessary. Use one of the solutions already provided. I just wanted to point out your mistake.
Update null elements with value in the same location in other. Combines a DataFrame with other DataFrame using func to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the union of the two.
df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
df1.combine_first(df2)
A B
0 1.0 3.0
1 0.0 4.0
write function like this to return an array
function secondsToTime($seconds) {
// extract hours
$hours = floor($seconds / (60 * 60));
// extract minutes
$divisor_for_minutes = $seconds % (60 * 60);
$minutes = floor($divisor_for_minutes / 60);
// extract the remaining seconds
$divisor_for_seconds = $divisor_for_minutes % 60;
$seconds = ceil($divisor_for_seconds);
// return the final array
$obj = array(
"h" => (int) $hours,
"m" => (int) $minutes,
"s" => (int) $seconds,
);
return $obj;
}
then simply call the function like this:
secondsToTime(100);
output is
Array ( [h] => 0 [m] => 1 [s] => 40 )
I recommend dynamically adding the elements, and if using jQuery or other JavaScript library, it is quite simple:
also look at prepend
and append
. Otherwise if you have an image tag like that, and you want to make it validate, then you might consider using a dummy image, such as a 1px transparent gif or png.
Try this -
select * from table where id in (3,4) or [name] in ('andy','paul');
# coding=utf-8
def my_function_get_list():
my_list = [0, 1, 2, 3, 4, 5]
# You may use map() to convert each item in the list to a string,
# and then join them to print my_list
print("Affichage de my_list [{0}]".format(', '.join(map(str, my_list))))
return my_list
my_result_list = [
(
number_in_my_list + 4, # Condition is False : append number_in_my_list + 4 in my_result_list
number_in_my_list * 2 # Condition is True : append number_in_my_list * 2 in my_result_list
)
[number_in_my_list % 2 == 0] # [Condition] If the number in my list is even
for number_in_my_list in my_function_get_list() # For each number in my list
]
print("Affichage de my_result_list [{0}]".format(', '.join(map(str, my_result_list))))
(venv) $ python list_comp.py
Affichage de my_list [0, 1, 2, 3, 4, 5]
Affichage de my_result_list [0, 5, 4, 7, 8, 9]
So, for you:
row = [('', unicode(x.strip()))[x is not None] for x in row]
The wb
indicates that the file is opened for writing in binary mode.
When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b
is excluded as in just w
or when you specify text mode with wt
), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n
) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe
or png
file.
Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.
References:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open
Close nodejs app
running in another shell.
Restart the terminal and run the program again.
Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port
and run the app.
To find the PID of the application that is using port:8000
$ fuser 8000/tcp
8000/tcp: 16708
Here PID is 16708 Now kill the process using the kill [PID]
command
$ kill 16708
realpath <path to the symlink file>
should do the trick.
I guess your app crashes because of NullPointerException
.
Change this
ListView lv = (ListView)getActivity().findViewById(R.id.lv_contact);
to
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
assuming listview belongs to the fragment layout.
The rest of the code looks alright
Edit:
Well since you said it is not working i tried it myself
adb shell killall -9 com.your.package.name
according to MAC "mandatory access control" you probably have the permission to kill process which is not started by root
have fun!
Edit the file xampp/mysql/bin/my.ini
Add
skip-grant-tables
under [mysqld]
For "Xamarin Android":
FindViewById<Button>(Resource.Id.Button1).Visibility = ViewStates.Gone;
Static member variables must be declared in the class and then defined outside of it!
There's no workaround, just put their actual definition in a source file.
From your description it smells like you're not using static variables the right way. If they never change you should use constant variable instead, but your description is too generic to say something more.
Static member variables always hold the same value for any instance of your class: if you change a static variable of one object, it will change also for all the other objects (and in fact you can also access them without an instance of the class - ie: an object).
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
Java enums don't have the same kind of enum-to-int mapping that they do in C++.
That said, all enums have a values
method that returns an array of possible enum values, so
MyEnum enumValue = MyEnum.values()[x];
should work. It's a little nasty and it might be better to not try and convert from int
s to Enum
s (or vice versa) if possible.
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
Double is a wrapper class,
The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.
The double data type,
The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
Check each datatype with their ranges : Java's Primitive Data Types.
Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double
You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.
$('#musics').on('change', '#want',function(e) {
$(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
var ans=$(this).val();
console.log(($('#want').is(':checked')));
});
If you're using executeScalar:
cmd.ExecuteScalar();
result_id=cmd.LastInsertedId.ToString();
There are some things to be considered in your code.
First, write those headers correctly. You will never see any server sending Content-type:application/pdf
, the header is Content-Type: application/pdf
, spaced, with capitalized first letters etc.
The file name in Content-Disposition
is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in "
not '
. Also, your last '
is missing.
Content-Disposition: inline
implies the file should be displayed, not downloaded. Use attachment
instead.
In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)
All that being said, your code should look more like this:
<?php
$filename = './pdf/jobs/pdffile.pdf';
$fileinfo = pathinfo($filename);
$sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);
header('Content-Type: application/pdf');
header("Content-Disposition: attachment; filename=\"$sendname\"");
header('Content-Length: ' . filesize($filename));
readfile($filename);
Content-Length
is optional but is also important if you want the user to be able to keep track of the download progress and detect if the download was interrupted. But when using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php
or after ?>
, not even an empty line.
You can access the fields by indexing the object array:
foreach (object[] item in selectedValues)
{
idTextBox.Text = item[0];
titleTextBox.Text = item[1];
contentTextBox.Text = item[2];
}
That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:
public class MyObject
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
Then you can do:
foreach (MyObject item in selectedValues)
{
idTextBox.Text = item.Id;
titleTextBox.Text = item.Title;
contentTextBox.Text = item.Content;
}
apache commons lang has a class SystemUtils.java you can use :
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
Try
<input type="number" pattern="^[0-9]" title='Only Number' min="1" step="1">
I hacked together some tool which attaches into a running Python process and injects some code to get a Python shell.
See here: https://github.com/albertz/pydbattach
Namenode enters into safemode when there is shortage of memory. As a result the HDFS becomes readable only. That means one can not create any additional directory or file in the HDFS. To come out of the safemode, the following command is used:
hadoop dfsadmin -safemode leave
If you are using cloudera manager:
go to >>Actions>>Leave Safemode
But it doesn't always solve the problem. The complete solution lies in making some space in the memory. Use the following command to check your memory usage.
free -m
If you are using cloudera, you can also check if the HDFS is showing some signs of bad health. It probably must be showing some memory issue related to the namenode. Allot more memory by following the options available. I am not sure what commands to use for the same if you are not using cloudera manager but there must be a way. Hope it helps! :)
Correct the ORACLE_HOME path.
There could be two oracle clients in the system.
I had the same issue, the reason being my ORACLE_HOME was pointed to the oracle installation which was not having the tns.ora file.
Changing the ORACLE_HOME to the Oracle directory which is having the tns.ora solved it.
tns.ora lies in client2\network\admin\
You can declare columns/variables as varchar2(n CHAR) and varchar2(n byte).
n CHAR means the variable will hold n characters. In multi byte character sets you don't always know how many bytes you want to store, but you do want to garantee the storage of a certain amount of characters.
n bytes means simply the number of bytes you want to store.
varchar is deprecated. Do not use it. What is the difference between varchar and varchar2?
You can use display: block
Example :
<!DOCTYPE html>
<html>
<body>
<p id="demo">Lorem Ipsum</p>
<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click Me!</button>
</body>
</html>
In Bash 4 (as well as ZSH 4.3.11):
cmd &>>outfile
just out of box
This is indirect answer, on the folder structure itself, very related.
A few years ago I had same question, took a folder structure but had to do a lot directory moving later on, because the folder was meant for a different purpose than that I have read on internet, that is, what a particular folder does has different meanings for different people on some folders.
Now, having done multiple projects, in addition to explanation in all other answers, on the folder structure itself, I would strongly suggest to follow the structure of Node.js itself, which can be seen at: https://github.com/nodejs/node. It has great detail on all, say linters and others, what file and folder structure they have and where. Some folders have a README that explains what is in that folder.
Starting in above structure is good because some day a new requirement comes in and but you will have a scope to improve as it is already followed by Node.js itself which is maintained over many years now.
Hope this helps.
I have also encountered this problem and this was my solution:
import os
def loadImports(path):
files = os.listdir(path)
imps = []
for i in range(len(files)):
name = files[i].split('.')
if len(name) > 1:
if name[1] == 'py' and name[0] != '__init__':
name = name[0]
imps.append(name)
file = open(path+'__init__.py','w')
toWrite = '__all__ = '+str(imps)
file.write(toWrite)
file.close()
This function creates a file (in the provided folder) named __init__.py
, which contains an __all__
variable that holds every module in the folder.
For example, I have a folder named Test
which contains:
Foo.py
Bar.py
So in the script I want the modules to be imported into I will write:
loadImports('Test/')
from Test import *
This will import everything from Test
and the __init__.py
file in Test
will now contain:
__all__ = ['Foo','Bar']
require_relative
is a convenient subset of require
require_relative('path')
equals:
require(File.expand_path('path', File.dirname(__FILE__)))
if __FILE__
is defined, or it raises LoadError
otherwise.
This implies that:
require_relative 'a'
and require_relative './a'
require relative to the current file (__FILE__
).
This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.
eval('require_relative("a.rb")')
raises LoadError
because __FILE__
is not defined inside eval
.
This is why you can't use require_relative
in RSpec tests, which get eval
ed.
The following operations are only possible with require
:
require './a.rb'
requires relative to the current directory
require 'a.rb'
uses the search path ($LOAD_PATH
) to require. It does not find files relative to current directory or path.
This is not possible with require_relative
because the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with /
or ./
or ../
), which is always the case for File.expand_path
.
The following operation is possible with both, but you will want to use require
as it is shorter and more efficient:
require '/a.rb'
and require_relative '/a.rb'
both require the absolute path.Reading the source
When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.
require:
VALUE rb_f_require(VALUE obj, VALUE fname) {
return rb_require_safe(fname, rb_safe_level());
}
require_relative:
VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
VALUE base = rb_current_realfilepath();
if (NIL_P(base)) {
rb_loaderror("cannot infer basepath");
}
base = rb_file_dirname(base);
return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}
This allows us to conclude that
require_relative('path')
is the same as:
require(File.expand_path('path', File.dirname(__FILE__)))
because:
rb_file_absolute_path =~ File.expand_path
rb_file_dirname1 =~ File.dirname
rb_current_realfilepath =~ __FILE__
You can do it this way:
xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "Name of the node to find")
where xml is a XDocument.
Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.
Based on Farhan Sahibole's answer:
header('Content-Disposition: attachment; filename=Image.png');
header('Content-Type: application/octet-stream'); // Downloading on Android might fail without this
ob_clean();
readfile($file);
This is all I needed for this to work. I stripped off anything that isn't required for this to work.
Key is to use ob_clean();
To revert to upstream/master do:
git checkout upstream/master -- myfile.txt
For anyone just looking to replace the extra ' ' (space) if day is less than 10 then use:
#define BUILD_DATE (char const[]) { __DATE__[0], __DATE__[1], __DATE__[2], __DATE__[3], (__DATE__[4] == ' ' ? '0' : __DATE__[4]), __DATE__[5], __DATE__[6], __DATE__[7], __DATE__[8], __DATE__[9], __DATE__[10], __DATE__[11] }
Output: Sep 06 2019
Just add http://download.eclipse.org/egit/updates to your Eclipse update manager.
You can use the VS code and install the Graphviz extension or,
C:\Program Files (x86)\Graphviz2.38\bin
(or your_installation_path/ bin) to your system variable
PATHdot music-recommender.dot -Tpng -o image.png
What you need to know in one place:
ASPNETCORE_
. :
as a separater. If the platform doesn't allow colons in environment variable keys, use __
instead.ApplicationHost.config
. Using the IIS Configuration Editor will cause your inputs to be written to the application's Web.config
-- and will be overwritten with the next deployment!For modifying ApplicationHost.config
, you want to use appcmd.exe
to make sure your modifications are consistent. Example: %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /+"environmentVariables.[name='ASPNETCORE_AWS:Region',value='eu-central-1']" /commit:site
Characters that are not URL-safe can be escaped as Unicode, like %u007b
for left curly bracket.
%systemroot%\system32\inetsrv\appcmd.exe list config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore
%systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /-"environmentVariables.[name='ASPNETCORE_MyKey',value='value-to-be-removed']" /commit:site
.There's one really important difference which is not mentioned anywhere.
take(1) emits 1, completes, unsubscribes
first() emits 1, completes, but doesn't unsubscribe.
It means that your upstream observable will still be hot after first() which is probably not expected behavior.
UPD: This referes to RxJS 5.2.0. This issue might be already fixed.
Using swift and Google Maps Api v3, this was the easiest way I was able to do it:
icon = GMSMarker.markerImageWithColor(UIColor.blackColor())
hope it helps someone.
Encapsulation helps in adhering to Single Responsibility principle and Abstraction helps in adhering to Code to Interface and not to implement.
Say I have a class for Car : Service Provider Class and Driver Class : Service Consumer Class.
For Abstraction : we define abstract Class for CAR and define all the abstract methods in it , which are function available in the car like : changeGear(), applyBrake().
Now the actual Car (Concrete Class i.e. like Mercedes , BMW will implement these methods in their own way and abstract the execution and end user will still apply break and change gear for particular concrete car instance and polymorphically the execution will happen as defined in concrete class.
For Encapsulation : Now say Mercedes come up with new feature/technology: Anti Skid Braking, while implementing the applyBrake(), it will encapsulate this feature in applyBrake() method and thus providing cohesion, and service consumer will still access by same method applyBrake() of the car object. Thus Encapsulation lets further in same concrete class implementation.
To set precision for double values DecimalFormat
is good technique. To use this class import java.text.DecimalFormat
and create object of it for example
double no=12.786;
DecimalFormat dec = new DecimalFormat("#0.00");
System.out.println(dec.format(no));
So it will print two digits after decimal point here it will print 12.79
I assume this is *nix?
Use "here document":
sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF
EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):
$ echo 'select 1 from dual;'|sqlplus -s user/pw
1
----------
1
$
It looks like psexec -h
is the way to do this:
-h If the target system is Windows Vista or higher, has the process
run with the account's elevated token, if available.
Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.
But it works on my machine.
For a number, it is tricky because if a numeric cell is empty
VBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.
The following check worked for me to see if there was an actual 0 entered into the cell:
If CStr(rng.value) = "0" then
'your code here'
End If
If using Windows and Powershell, you can use the following to delete all local branches that have been merged into the branch currently checked out:
git branch --merged | ? {$_[0] -ne '*'} | % {$_.trim()} | % {git branch -d $_}
Explanation
git
output for each remaining branch nameIt's worth running git branch --merged
by itself first just to make sure it's only going to remove what you expect it to.
(Ported/automated from http://railsware.com/blog/2014/08/11/git-housekeeping-tutorial-clean-up-outdated-branches-in-local-and-remote-repositories/.)
It looks like you are calling a non static member (a property or method, specifically setTextboxText
) from a static method (specifically SumData
). You will need to either:
Make the called member static also:
static void setTextboxText(int result)
{
// Write static logic for setTextboxText.
// This may require a static singleton instance of Form1.
}
Create an instance of Form1
within the calling method:
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
Passing in an instance of Form1
would be an option also.
Make the calling method a non-static instance method (of Form1
):
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
More info about this error can be found on MSDN.
Depending on the schema/account you are using to connect to the database, I would suspect you are missing a grant to the account you are using to connect to the database.
Connect as PCT account in the database, then grant the account you are using select access for the table.
grant select on pi_int to Account_used_to_connect
In date '?'
, the '?'
is a literal string with value ?
, not a parameter placeholder, so your query does not have any parameters. The date
is a shorthand cast from (literal) string to date. You need to replace date '?'
with ?
to actually have a parameter.
Also if you know it is a date, then use setDate(..)
and not setString(..)
to set the parameter.
try to put your script and link on the head like this:
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous">
</script>
</head>
<body>
<div class="row">
<h3 class="one">Text</h3>
<button class="btn btn-secondary pull-right">Button</button>
</div>
</body>
</html>
I know its already answered, but theres a better solution here use this code :
for ( Field f : context.getFields() ) {
if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
//DO String To JSON
}
/// And so on...
}
This way you can access variables from class without manually typing them..
Faster and better .. Hope this helps.
Cheers. :D
Just to complement the answer given by Thibaut Barrère.
I used
wget -r -nH --cut-dirs=5 -nc ftp://user:pass@server//absolute/path/to/directory
Note the double slash after the server name. If you don't put an extra slash the path is relative to the home directory of user.
-nH
avoids the creation of a directory named after the server name-nc
avoids creating a new file if it already exists on the destination (it is just skipped)--cut-dirs=5
allows to take the content of /absolute/path/to/directory and to put it in the directory where you launch wget. The number 5 is used to filter out the 5 components of the path. The double slash means an extra component.For Swift 3 & Swift 4 :
Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3
let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
//Do whatever you want here
})
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
Deprecated :
This is the swift version inspired by the checked response :
Display AlertView :
let alert = UIAlertView(title: "No network connection",
message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
alert.delegate = self
alert.show()
Add the delegate to your view controller :
class AgendaViewController: UIViewController, UIAlertViewDelegate
When user click on button, this code will be executed :
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
}
You can use pop()
:
x=[2,3,4,5,6,7]
print(x.pop(2))
Marshaling and serialization are loosely synonymous in the context of remote procedure call, but semantically different as a matter of intent.
In particular, marshaling is about getting parameters from here to there, while serialization is about copying structured data to or from a primitive form such as a byte stream. In this sense, serialization is one means to perform marshaling, usually implementing pass-by-value semantics.
It is also possible for an object to be marshaled by reference, in which case the data "on the wire" is simply location information for the original object. However, such an object may still be amenable to value serialization.
As @Bill mentions, there may be additional metadata such as code base location or even object implementation code.
The permissions for the storage
and vendor
folders should stay at 775
, for obvious security reasons.
However, both your computer and your server Apache need to be able to write in these folders. Ex: when you run commands like php artisan
, your computer needs to write in the logs file in storage
.
All you need to do is to give ownership of the folders to Apache :
sudo chown -R www-data:www-data /path/to/your/project/vendor
sudo chown -R www-data:www-data /path/to/your/project/storage
Then you need to add your computer (referenced by it's username
) to the group to which the server Apache belongs. Like so :
sudo usermod -a -G www-data userName
NOTE: Most frequently, groupName
is www-data
but in your case, replace it with _www
You can implement it directly i all your window html elements.
Like this :
HTMLElement.prototype.appendFirst = function(childNode) {
if (this.firstChild) {
this.insertBefore(childNode, this.firstChild);
}
else {
this.appendChild(childNode);
}
};
Probably somewhere you have DBconnection->close();
and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close();
in __destruct()
(because __destruct
is event, after which there will be a need for execution of queries)
This will for most of the objects for outputting in nodejs console
var util = require('util')_x000D_
function print (data){_x000D_
console.log(util.inspect(data,true,12,true))_x000D_
_x000D_
}_x000D_
_x000D_
print({name : "Your name" ,age : "Your age"})
_x000D_
Good references to the docs. Here's how you can guarantee the order regardless of the documentation / implementation:
k, v = zip(*d.iteritems())
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
You can make cross domain requests using the XMLHttpRequest
object. This is done using something called "Cross Origin Resource Sharing". See:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin
header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.
You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
JSONP is an alternative solution, but you could argue it's a bit of a hack.
This is common issue with floating points.
Use toFixed
in combination with parseFloat
.
Here is example in JavaScript:
function roundNumber(number, decimals) {
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
return parseFloat(newnumber);
}
0.1 + 0.2; //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3
What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.
If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
And in the directive:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// You actions here
console.log("I got the new value! ", newValue);
}
}, true);
}
};
});
MIME type of the CSV is text/csv according to RFC 4180.
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
Updated with feedback from Alan Moore
In PCRE and similar variants, you can actually create a regex that matches any line not containing a value:
^(?:(?!Andrea).)*$
This is called a tempered greedy token. The downside is that it doesn't perform well.
this happened to me a few days ago. I did a fresh installation and it still happened. as far as everyone sees and based on your server specs. most likely it is an infinite loop. it could be not on the PHP code itself but on the requests made to Apache.
lets say when you access this url http://localhost/mysite/page_with_multiple_requests
Check your Apache's access log if it receives multiple requests. trace that request and check out the code that might cause a 'bottleneck' to the system (mine's exec() when using sendmail). The bottleneck im talking about doesn't need to be an 'infinite loop'. It could be a function that takes sometime to finish. or maybe some of php's 'program execution functions'
You might need to check ajax requests too (the ones that execute when the page loads). if that ajax request redirects to the same url
e.g. httpx://localhost/mysite/page_with_multiple_requests
it would 'redo' the requests all over again
it would help if you post the random lines or the code itself where the script ends maybe there is a 'loop' code somewhere there. imho php won't just call random lines for nothing.
http://blog.piratelufi.com/2012/08/browser-sending-multiple-requests-at-once/
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
I found this approach useful. This way you do not need a class nor final
btnInsert.addMouseListener(new MouseAdapter() {
private Statement _statement;
public MouseAdapter setStatement(Statement _stmnt)
{
_statement = _stmnt;
return this;
}
@Override
public void mouseDown(MouseEvent e) {
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try {
_statement.executeUpdate(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}.setStatement(statement));
Some fixes I've used for this problem:
Check if the connection you want to share is shareable.
a. Press Win-key + r and run ncpa.cpl
b. Right click on the connection you want to share and go to properties
c. Go to sharing tab and check if sharing is enabled
Run devmgmt.msc
from the run console.
a. Expand the network adapters list
b. Right click -> properties on the adapter of the connection you want to share
c. Go to power management tab and enable allow this computer to turn off this device to save power
. Restart your laptop if you've made changes.
Check if airplane mode is disabled. You can enable airplane mode and then turn on the wi-fi, you can never know. Do disable airplane mode if it is on.
Use admin command prompt to run this command.
You have a line break <br>
in-between the second and third images in your markup. Get rid of that, and it'll show inline.
I'm getting the following error when compiling Adam Rosenfield's code on Windows. It turns out few things are missing from the code.
Error (Before)
C:\C\Codes>gcc time.c -o time
time.c:3:12: error: initializer element is not constant
time_t t = time(NULL);
^
time.c:4:16: error: initializer element is not constant
struct tm tm = *localtime(&t);
^
time.c:6:8: error: expected declaration specifiers or '...' before string constant
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:36: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:55: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:70: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:82: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:94: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:105: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
C:\C\Codes>
Solution
C:\C\Codes>more time.c
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
C:\C\Codes>
Compiling
C:\C\Codes>gcc time.c -o time
C:\C\Codes>
Final Output
C:\C\Codes>time
now: 2018-3-11 15:46:36
C:\C\Codes>
I hope this will helps others too
run cmd.exe
and do the following:
> cd "long path name"
> command
Then command.com will come up and display only short paths.
If you use a comma inbetween the strings and the variable, like this:
print "If there was a birth every 7 seconds, there would be: ", births, "births"
This can happen if you don't have mod_proxy_http
enabled
sudo a2enmod proxy_http
For me to get my https based load balancer working, i had to enable the following:
sudo a2enmod ssl
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http
If you use the Generate Scripts under SSMS, click the Advanced button. Under the 'Generate Scripts for the dependent objects' option, click True. By clicking that any dependencies of each object will also be scripted out in proper order.
Just use:
patch -p0 < path-file.patch
remember execute this command only from the folder location where you created the patch.
You can use the built in OnSelecting parameter of asp:SqlDataSource
Example: [.aspx file]
<asp:SqlDataSource ID="SqldsExample" runat="server"
SelectCommand="SELECT [SomeColumn], [AnotherColumn]
FROM [SomeTable]
WHERE [Dynamic_Variable_Column] = @DynamicVariable"
OnSelecting="SqldsExample_Selecting">
<SelectParameters>
<asp:Parameter Name="DynamicVariable" Type="String"/>
</SelectParameters>
Then in your code behind implement your OnSelecting method: [.aspx.cs]
protected void SqldsExample_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["@DynamicVariable"].Value = (whatever value you want);
}
You can also use this for the other types of DB operations just implement your own methods:
OnInserting="SqldsExample_Inserting"
OnUpdating="SqldsExample_Updating"
OnDeleting="SqldsExample_Deleting"
Vertical Bar UP For Down in red color :
using System;
using System.Windows.Forms;
using System.Drawing;
public class VerticalProgressBar : ProgressBar
{
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style |= 0x04;
return cp;
}
}
private SolidBrush brush = null;
public VerticalProgressBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
if (brush == null || brush.Color != this.ForeColor)
brush = new SolidBrush(this.ForeColor);
Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
if (ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawVerticalBar(e.Graphics, rec);
rec.Height = (int)(rec.Height * ((double)Value / Maximum)) - 4;
rec.Width = rec.Width - 4;
e.Graphics.FillRectangle(brush, 2, 2, rec.Width, rec.Height);
}
}
Initialy both dropdown have same option ,the option you select in firstdropdown is hidden in seconddropdown."value" is custom attribute which is unique.
$(".seconddropdown option" ).each(function() {
if(($(this).attr('value')==$(".firstdropdown option:selected").attr('value') )){
$(this).hide();
$(this).siblings().show();
}
});
If you're using SQL Server 2005 or later, use varchar(MAX)
. The text
datatype is deprecated and should not be used for new development work. From the docs:
Important
ntext
,text
, andimage
data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.
TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.
AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.
This question was already asked on https://tex.stackexchange.com/questions/10684/vertical-space-in-lists. The highest voted answer also mentioned the enumitem
package (here answered by Stefan), but I also like this one, which involves creating your own itemizing environment instead of loading a new package:
\newenvironment{myitemize}
{ \begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt} }
{ \end{itemize} }
Which should be used like this:
\begin{myitemize}
\item one
\item two
\item three
\end{myitemize}
try
pip3 install --user --upgrade pandas
Since Webpack v4, simply setting mode
in your Webpack config will set the NODE_ENV
for you (via DefinePlugin
). Docs here.
All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.
You can use Math.round(double)
function or simply do :
(int)(yourDoubleValue + 0.5d)
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
const
is for compile-time constants. You could just make it static readonly
, but that would only apply to the METRICS
variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");
You may want to use a ReadOnlyCollection<T>
to wrap it. For example:
public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
(new List<String> {
SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn,
SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });
ReadOnlyCollection<T>
just wraps a potentially-mutable collection, but as nothing else will have access to the List<T>
afterwards, you can regard the overall collection as immutable.
(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)
Whether you declare it as IList<string>
, IEnumerable<string>
, ReadOnlyCollection<string>
or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string>
would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T>
may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T>
could be handy - but inflexible.
Pleaes find the Function used in XMLHTTPREQUEST in Javascript for setting up the request headers.
...
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "http://www.example.com");
...
</script>
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
If you want to scroll the element you're over and prevent the window to scroll, here's a really useful function :
$('.Scrollable').on('DOMMouseScroll mousewheel', function(ev) {
var $this = $(this),
scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = $this.height(),
delta = (ev.type == 'DOMMouseScroll' ?
ev.originalEvent.detail * -40 :
ev.originalEvent.wheelDelta),
up = delta > 0;
var prevent = function() {
ev.stopPropagation();
ev.preventDefault();
ev.returnValue = false;
return false;
}
if (!up && -delta > scrollHeight - height - scrollTop) {
// Scrolling down, but this will take us past the bottom.
$this.scrollTop(scrollHeight);
return prevent();
} else if (up && delta > scrollTop) {
// Scrolling up, but this will take us past the top.
$this.scrollTop(0);
return prevent();
}
});
Apply the class "Scrollable" to your element and that's it!
l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]
Actually I got this to work. Consider the following snippet:
Method m;
Type[] genericParameterTypes = m.getGenericParameterTypes();
for (int i = 0; i < genericParameterTypes.length; i++) {
if( genericParameterTypes[i] instanceof ParameterizedType ) {
Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
//parameters[0] contains java.lang.String for method like "method(List<String> value)"
}
}
I'm using jdk 1.6
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
Outputs:
Hello here is a long ...
exec 'print "hello";' * 2
should work, but I'm kind of ashamed that I thought of it.
Update: Just thought of another one:
for _ in " "*10: print "hello"
If you are trying to load a file which is not in the same directory as your Java class, you've got to use the runtime directory structure rather than the one which appears at design time.
To find out what the runtime directory structure is, check your {root project dir}/target/classes directory. This directory is accessible via the "." URL.
Based on user4284592's answer, the following worked for me:
ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("./docs/doc.pdf").getFile());
with the following directory structure:
{root dir}/target/classes/docs/doc.pdf
Here's an explanation, so you don't just blindly copy and paste my code:
You can do this in pretty concise way using ResponseEntity
like this:
@GetMapping
ResponseEntity<Void> redirect() {
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create("http://www.yahoo.com"))
.build();
}
You could use the bootstrap grid system :
<div class="col-md-6 form-group">
<label for="textbox1">Label1</label>
<input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
<label for="textbox2">Label2</label>
<input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">
http://getbootstrap.com/css/#grid
Is that what you want to achieve?
After trying a skeleton project called "jsf-blank", which did not demonstrate this problem with xhtml files; I concluded that there was an unknown problem in my project. My solution may not have been too elegant, but it saved time. I backed up the code and other files I'd already developed, deleted the project, and started over - recreated the project. So far, I've added back most of the files and it looks pretty good.
I like being able to use foreach, so I made an extension method and a structure:
public struct EnumeratedInstance<T>
{
public long cnt;
public T item;
}
public static IEnumerable<EnumeratedInstance<T>> Enumerate<T>(this IEnumerable<T> collection)
{
long counter = 0;
foreach (var item in collection)
{
yield return new EnumeratedInstance<T>
{
cnt = counter,
item = item
};
counter++;
}
}
and an example use:
foreach (var ii in new string[] { "a", "b", "c" }.Enumerate())
{
Console.WriteLine(ii.item + ii.cnt);
}
One nice thing is that if you are used to the Python syntax, you can still use it:
foreach (var ii in Enumerate(new string[] { "a", "b", "c" }))
Maybe this is what you searched for :
function data() {
// your code
return $array;
}
$var = data();
foreach($var as $value) {
echo $value;
}
Besides the session cookie (which is kind of standard), I don't want to use extra cookies.
I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.
My solution without extra cookies is simple:
Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.
The main "index" page contains this JavaScript snippet:
// Intialize global variable CSRF_TOKEN to empty sting.
// This variable is set after a succesful login
window.CSRF_TOKEN = '';
// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
});
On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.
Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.
@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
resp.sendError(401);
} else
chain.doFilter(request, response);
}
You can either use the answer from the duplicate link pointed by nvm.
Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):
git pull -s recursive -X theirs
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".show-pwd").click(function(){
alert();
var x = $("#myInput");
if (x[0].type === "password") {
x[0].type = "text";
} else {
x[0].type = "password";
}
});
});
</script>
</head>
<body>
<p>Click the radio button to toggle between password visibility:</p>Password:
<input type="password" value="FakePSW" id="myInput">
<br>
<br>
<input type="checkbox" class="show-pwd">Show Password</body>
</html>
You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T>
here - usually ArrayList<T>
, but with plenty of other alternatives available.
You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T>
to start with.
Package & install are various phases in maven build lifecycle. package phase will execute all phases prior to that & it will stop with packaging the project as a jar. Similarly install phase will execute all prior phases & finally install the project locally for other dependent projects.
For understanding maven build lifecycle please go through the following link https://ayolajayamaha.blogspot.in/2014/05/difference-between-mvn-clean-install.html
This is really more of a serverfault-type question, but you can use netstat.
something like:
# netstat -lpnt | grep 6000 | grep ssh
This will tell you if there's an ssh process listening on the specified port. it will also tell you the PID of the process.
If you really want to double-check that the ssh process was started with the right options, you can then look up the process by PID in something like
# ps aux | grep PID
@zzzz's answer is mostly complete, but just to save others from having to dig through the referenced documentation you can run a single test in a package as follows:
go test packageName -run TestName
Note that you want to pass in the name of the test, not the file name where the test exists.
The -run
flag actually accepts a regex so you could limit the test run to a class of tests. From the docs:
-run regexp
Run only those tests and examples matching the regular
expression.
In my opinion its safer to use Custom Numeric Format Strings.
decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
The answer given by Francois results in listing all the cities from a country. But if the requirement is to list all the regions (cities + states + other regions etc) in a country or the establishments in the country, you can filter results accordingly by changing types.
List only cities in the country
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
List all cities, states and regions in the country
var options = {
types: ['(regions)'],
componentRestrictions: {country: "us"}
};
List all establishments — such as restaurants, stores, and offices in the country
var options = {
types: ['establishment'],
componentRestrictions: {country: "us"}
};
More information and options available at
https://developers.google.com/maps/documentation/javascript/places-autocomplete
Hope this might be useful to someone
I expect xxcopy has an option for that.
Bingo:
http://www.xxcopy.com/xxcopy27.htm#tag_231
2.3 By comparison with the file in destination
The switches in this group select files based on the
comparison between the files in the source and those in
the destination. They are often used for periodic backup
and directory synchronization purposes. These switches
were originally created as variations of directory backup.
They are also convenient for selecting files for deletion.
2.3.1 by Presence/Absence
The /BB and /U switches are the two switches which select
files by the pure presence or absence as the criteria.
Other switches in the this group (Group 2.3) are also
affected by the file in the destination, but for a
particular characteristics for comparison's sake.
/BB Selects files that are present in source but not in destination.
/U Selects files that are present in both source and destination.
-Adam
Here is a short tutorial:
Model:
namespace ImageUploadApp.Models
{
using System;
using System.Collections.Generic;
public partial class Image
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
}
View:
Create:
@model ImageUploadApp.Models.Image
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Index (for display):
@model IEnumerable<ImageUploadApp.Models.Image>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ImagePath)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImagePath)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
</td>
</tr>
}
</table>
Controller (Create)
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
img.ImagePath = file.FileName;
}
db.Image.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(img);
}
Hope this will help :)
Just use something like:
var author = $('meta[name=author]').attr('content');
Simplistically malloc
and free
work like this:
malloc
provides access to a process's heap. The heap is a construct in the C core library (commonly libc) that allows objects to obtain exclusive access to some space on the process's heap.
Each allocation on the heap is called a heap cell. This typically consists of a header that hold information on the size of the cell as well as a pointer to the next heap cell. This makes a heap effectively a linked list.
When one starts a process, the heap contains a single cell that contains all the heap space assigned on startup. This cell exists on the heap's free list.
When one calls malloc
, memory is taken from the large heap cell, which is returned by malloc
. The rest is formed into a new heap cell that consists of all the rest of the memory.
When one frees memory, the heap cell is added to the end of the heap's free list. Subsequent malloc
's walk the free list looking for a cell of suitable size.
As can be expected the heap can get fragmented and the heap manager may from time to time, try to merge adjacent heap cells.
When there is no memory left on the free list for a desired allocation, malloc
calls brk
or sbrk
which are the system calls requesting more memory pages from the operating system.
Now there are a few modification to optimize heap operations.
To remove every :
from the beginning of a string, you can use ltrim:
$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'
You have to put all your assets in app/public
folder, and to access them from your views you can use asset()
helper method.
Ex. you can retrieve assets/images/image.png
in your view as following:
<img src="{{asset('assets/images/image.png')}}">
Possibly:
select lpad(column, 8, 0) from table;
Edited in response to question from mylesg, in comments below:
ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT
I'm assuming that you used a query similar to:
UPDATE table SET columnName=lpad(nums,8,0);
If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:
First:
ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);
Second, run the update:
UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');
This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.
References:
You can either use:
import sys
sys.exit(...)
or:
raise SystemExit(...)
The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).
Crude, but does what you want, breaks the execution scope:
$(function(){
setTimeout(function(){
//Code to call
},1);
});
I was fetching a windows-1252 encoded file via cURL and the mb_detect_encoding(curl_exec($ch));
returned UTF-8. Tried utf8_encode(curl_exec($ch));
and the characters were correct.
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
A little bit deeper with 'SC' command, we are able to extract all 'Services Name' and got all 'QueryServiceConfig' :)
>SC QUERY > "%computername%-services.txt" [enter]
>FIND "SERVICE_NAME: " "%computername%-services.txt" /i > "%computername%-services-name.txt" [enter]
>NOTEPAD2 "%computername%-services-name.txt" [enter]
Then, continue with 'CMD'..
>FOR /F "DELIMS= SKIP=2" %S IN ('TYPE "%computername%-services-name.txt"') DO @SC QC "%S" >> "%computername%-services-list-config.txt" [enter]
>NOTEPAD2 "%computername%-services-list-config.txt" [enter]
Raw data is ready for feeding 'future batch file' so the result is look like this below!!!
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
| SERVICE_NAME | TYPE | START_TYPE | ERROR_CONTROL | BINARY_PATH_NAME | LOAD_ORDER_GROUP | TAG | DISPLAY_NAME | DEPENDENCIES | SERVICE_START_NAME |
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
+ WSearch | 10 WIN32_OWN_PROCESS | 2 AUTO_START (DELAYED) | 1 NORMAL | C:\Windows\system32\SearchIndexer.exe /Embedding | none | 0 | Windows Search | RPCSS | LocalSystem |
+ wuauserv | 20 WIN32_SHARE_PROCESS | 2 AUTO_START (DELAYED) | 1 NORMAL | C:\Windows\system32\svchost.exe -k netsvcs | none | 0 | Windows Update | rpcss | LocalSystem |
But, HTML will be pretty easier :D
Any bright ideas for improvement are welcome V^_^
Any of the following will work:
s = "true"
(s == 'true').real
1
(s == 'false').real
0
(s == 'true').conjugate()
1
(s == '').conjugate()
0
(s == 'true').__int__()
1
(s == 'opal').__int__()
0
def as_int(s):
return (s == 'true').__int__()
>>>> as_int('false')
0
>>>> as_int('true')
1
From the command line, use the --testNamePattern
or -t
flag:
jest -t 'fix-order-test'
This will only run tests that match the test name pattern you provide. It's in the Jest documentation.
Another way is to run tests in watch mode, jest --watch
, and then press P to filter the tests by typing the test file name or T to run a single test name.
If you have an it
inside of a describe
block, you have to run
jest -t '<describeString> <itString>'
Casting never needs a new
:
Collection<T> collection = myList;
You don't even make the cast explicit, because Collection
is a super-type of List
, so it will work just like this.
I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:
move Android to the top in the Order and Export tab and deselecting it.
Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!
Swift 3:
if let jsonString = styleDictionary as? String {
let objectData = jsonString.data(using: String.Encoding.utf8)
do {
let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers)
print(String(describing: json))
} catch {
// Handle error
print(error)
}
}
I have gone through many links but this answer helped me alot:
$scope.redirectPage = function (data) {
$window.open(data, "popup", "width=1000,height=700,left=300,top=200");
};
** data will be absolute url which you are hitting.
On your MainForm make a function to set the textbox the checks the InvokeRequired
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
return;
}
ActiveForm.Text += value;
}
although in your static method you can't just call.
WindowsFormsApplication1.Form1.AppendTextBox("hi. ");
you have to have a static reference to the Form1 somewhere, but this isn't really recommended or necessary, can you just make your SampleFunction not static if so then you can just call
AppendTextBox("hi. ");
It will append on a differnt thread and get marshalled to the UI using the Invoke call if required.
Full Sample
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(SampleFunction).Start();
}
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
return;
}
textBox1.Text += value;
}
void SampleFunction()
{
// Gets executed on a seperate thread and
// doesn't block the UI while sleeping
for(int i = 0; i<5; i++)
{
AppendTextBox("hi. ");
Thread.Sleep(1000);
}
}
}
You can disable SSL certificate checking by adding one or more of these command line parameters:
-Dmaven.wagon.http.ssl.insecure=true
- enable use of relaxed SSL check for user generated certificates.-Dmaven.wagon.http.ssl.allowall=true
- enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.-Dmaven.wagon.http.ssl.ignore.validity.dates=true
- ignore issues with certificate dates.Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/
Here's the oneliner for an easy copy-and-paste:
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true
Ajay Gautam suggested that you could also add the above to the ~/.mavenrc
file as not to have to specify it every time at command line:
$ cat ~/.mavenrc
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"
Maybe I'm wrong but I think that SQL query from view is a bad idea
This is my way
In controller
$model = new SomeModel();
$items=ArrayHelper::map(TableName::find()->all(),'id','name');
return $this->render('view',['model'=>$model, 'items'=>$items])
And in View
<?= Html::activeDropDownList($model, 'item_id',$items) ?>
Or using ActiveForm
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'item_id')->dropDownList($items) ?>
<?php ActiveForm::end(); ?>
(This is the KISS answer.)
Let's say you have several .java files in the current directory:
$ ls -1 *.java
javaFileName1.java
javaFileName2.java
Let's say each of them have a main()
method (so they are programs, not libs), then to compile them do:
javac *.java -d .
This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName
, so only one folder was generated with that name, so to execute each of them:
java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
If you are storing values via any programming language
Here is an example in C#
To store date you have to convert it first and then store it
insert table1 (foodate)
values (FooDate.ToString("MM/dd/yyyy"));
FooDate is datetime variable which contains your date in your format.
Ex:-
var value="Data-123";
var removeData=value.replace("Data-","");
alert(removeData);
Hopefully this will work for you.
You can also just Marshal.Copy the bitmap data. No intermediary memorystream etc. and a fast memory copy. This should work on both 24-bit and 32-bit bitmaps.
public static byte[] BitmapToByteArray(Bitmap bitmap)
{
BitmapData bmpdata = null;
try
{
bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
int numbytes = bmpdata.Stride * bitmap.Height;
byte[] bytedata = new byte[numbytes];
IntPtr ptr = bmpdata.Scan0;
Marshal.Copy(ptr, bytedata, 0, numbytes);
return bytedata;
}
finally
{
if (bmpdata != null)
bitmap.UnlockBits(bmpdata);
}
}
.
Use those queries to find all FKs:
Declare @SchemaName VarChar(200) = 'Schema Name'
Declare @TableName VarChar(200) = 'Table name'
-- Find FK in This table.
SELECT
'IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
This seems to happen from time to time with programs that are very sensitive to command lines, but one option is to just use the DOS path instead of the Windows path. This means that C:\Program Files\
would resolve to C:\PROGRA~1\
and generally avoid any issues with spacing.
To get the short path you can create a quick Batch file that echos the short path:
@ECHO OFF
echo %~s1
Which is then called as follows:
C:\>shortPath.bat "C:\Program Files"
C:\PROGRA~1
It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex
, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.
I realise this is a slightly old question, but it was driving me crazy too - and today I've found the solution that I believe the questioner was looking for (i.e. a direct mapping of Excel 2003's Web-->Address to the Excel 2010 Ribbon).
To customise the Ribbon, right-click on it and choose 'Customise the Ribbon'. You can make a new tab/group, or add this to an existing one. Choose to look in "All commands" and then the one you are after is simply called "Address". This puts a box with the full network path in it (that can be selected to copy) into the ribbon, just like Excel 2003.
I changed 3 things and then it works:
For the Python module import to work, you must have "src" in your path, not "gen_py/lib".
When processing an import like import gen_py.lib
, it looks for a module gen_py
, then looks for a submodule lib
.
As the module gen_py
won't be in "../gen_py/lib" (it'll be in ".."), the path you added will do nothing to help the import process.
Depending on where you're running it from, try adding the relative path to the "src" folder. Perhaps it's sys.path.append('..')
. You might also have success running the script while inside the src folder directly, via relative paths like python main/MyServer.py
Unit Testing - As the name suggests, this method tests at the object level. Individual software components are tested for any errors. Knowledge of the program is needed for this test and the test codes are created to check if the software behaves as it is intended to.
Functional Testing - Is carried out without any knowledge of the internal working of the system. The tester will try to use the system by just following requirements, by providing different inputs and testing the generated outputs. This test is also known as closed-box testing or black-box.
Acceptance Testing - This is the last test that is conducted before the software is handed over to the client. It is carried out to ensure that the developed software meets all the customer requirements. There are two types of acceptance testing - one that is carried out by the members of the development team, known as internal acceptance testing (Alpha testing), and the other that is carried out by the customer or end user known as (Beta testing)
Integration Testing - Individual modules that are already subjected to unit testing are integrated with one another. Generally the two approachs are followed :
1) Top-Down
2) Bottom-Up
ng serve
This command run in your terminal after your in project folder location like ~/my-app$
Then run the command - it will show the URl NG Live Development Server is listening on localhost:4200
Open your browser on http://localhost:4200
In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:
https://github.com/viniciuschiele/flask-apscheduler
A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:
from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'jobs:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 10
}
]
SCHEDULER_API_ENABLED = True
def job1(a, b):
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
app.run()
You could also get this error when JRE is not set. If so, try adding JRE System Library to your project.
Under Eclipse IDE:
Following are the references that may explain Architecture in more detail and a list of UML diagrams for software architecture. (I could not find listing of UML diagrams for software design )
UML 2 Diagram use for Architectural Models
Classification of UML diagrams
Classification of UML diagrams
Even after posting this answer, i myself is not clear which diagram is for architecture and which one for design :). Grady Booch, in his slide # 58, states that Classes, Interfaces and Collaborations are part of Design View and this Design View is one of the View of Architecture !!!
there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD')
and heredoc(<<<EOD)
strings
you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.
nowdoc strings will not expand variables just like single quotes.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
I struggled a bit with coming up with a bash function that wraps Peter Tillemans' answer but here's what I came up with:
function regex { perl -n -e "/$1/ && printf \"%s\n\", "'$1' }
I found this worked better than opsb's awk-based bash function for the following regular expression argument, because I do not want the "ms" to be printed.
'([0-9]*)ms$'
Another solution would be as below where the list is placed under a drop-down button.
<button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
>Markets<span class="caret"></span></button>
<ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
{{ form.markets }}
</ul>
Here is a SO thread where @Matt renders only the desired pixel into a 1x1 context by displacing the image so that the desired pixel aligns with the one pixel in the context.
FYI: Taken from: https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads
Overview
Support Packs for “SAP Crystal Reports, developer version for Microsoft Visual Studio” (SAP Crystal Reports for Visual Studio) are scheduled on a quarterly bases and support the following versions of Visual Studio:
Download Crystal Reports developer, for Microsoft Visual Studio
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
Solution based on Tonys answer:
DataGrid dg = sender as DataGrid;
User row = (User)dg.SelectedItems[0];
Console.WriteLine(row.UserID);
This one did it for me:
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata").val("bla");
$('#form1').append(input);
is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)
used the Firefox firebug to check whether the element was inserted.
Hidden elements do get posted back in the form collection, only read-only fields are discarded.
Michel
Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:
Date firstDate = new Date(ConstructorArgsHere);
Now you have a bit of a choice. If you don't pass in any arguments, and just do this,
Date firstDate = new Date();
it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:
Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);
It can be added by using:
$psql -d databaseName -c "CREATE EXTENSION dblink"
def pali(str1):
l=list(str1)
l1=l[::-1]
if l1==l:
print("yess")
else:
print("noo")
str1="abc"
a=pali(str1)
print(a)