If App Pool has trouble restarting or simply doesn't want to restart, verify if windows made recent update on ASP.NET v4.0 or other App Pool. That is what happend in my case. I simply restarted my computer, then restarted ASP.NET v4.0 App Pool and everything was working again!
In addition to Ishan's answer, if you want to draw programatically without user interaction, you can edit the class just a little like this.
public class DrawingCanvas extends View {
private Paint mPaint;
private Path mPath;
private boolean isUserInteractionEnabled = false;
public DrawingCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
mPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isUserInteractionEnabled) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPath.moveTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(event.getX(), event.getY());
invalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
}
return true;
}
public void moveCursorTo(float x, float y) {
mPath.moveTo(x, y);
}
public void makeLine(float toX, float toY) {
mPath.lineTo(toX, toY);
}
public void setUserInteractionEnabled(boolean userInteractionEnabled) {
isUserInteractionEnabled = userInteractionEnabled;
}
}
And then use it like
drawingCanvas.setUserInteractionEnabled(true) // to enable user interaction
drawingCanvas.setUserInteractionEnabled(true) // to disable user interaction
To Draw programatically
drawingCanvas.moveCursorTo(70f, 70f) // Move the cursor (Define starting point)
drawingCanvas.makeLine(200f, 200f) // End point (To where you need to draw)
Short circuit here means that the second condition won't be evaluated.
If ( A && B ) will result in short circuit if A is False.
If ( A && B ) will not result in short Circuit if A is True.
If ( A || B ) will result in short circuit if A is True.
If ( A || B ) will not result in short circuit if A is False.
At first I thought that this would work:
select DBMS_Random.Value(1,9) output
from ...
However, this does not generate an even distribution of output values:
select output,
count(*)
from (
select round(dbms_random.value(1,9)) output
from dual
connect by level <= 1000000)
group by output
order by 1
1 62423
2 125302
3 125038
4 125207
5 124892
6 124235
7 124832
8 125514
9 62557
The reasons are pretty obvious I think.
I'd suggest using something like:
floor(dbms_random.value(1,10))
Hence:
select output,
count(*)
from (
select floor(dbms_random.value(1,10)) output
from dual
connect by level <= 1000000)
group by output
order by 1
1 111038
2 110912
3 111155
4 111125
5 111084
6 111328
7 110873
8 111532
9 110953
I use the following code to test the empty line with or without white spaces.
if len(line.strip()) == 0 :
# do something with empty line
Theta is a shorthand way of referring to a special situtation where the big O and Omega are the same.
Thus, if one claims The Theta is expression q
, then they are also necessarily claiming that Big O is expression q
and Omega is expression q
.
Rough analogy:
If: Theta claims, "That animal has 5 legs." then it follows that: Big O is true ("That animal has less than or equal to 5 legs.") and Omega is true("That animal has more than or equal to 5 legs.")
It's only a rough analogy because the expressions aren't necessarily specific numbers, but instead functions of varying orders of magnitude such as log(n), n, n^2, (etc.).
_bitmapScaled.compress()
should do the trick. Check out the docs: http://developer.android.com/reference/android/graphics/Bitmap.html#compress(android.graphics.Bitmap.CompressFormat, int, java.io.OutputStream)
It's a little ugly (due to the scaling up), but it works on most newer browsers:
input[type=checkbox]_x000D_
{_x000D_
/* Double-sized Checkboxes */_x000D_
-ms-transform: scale(2); /* IE */_x000D_
-moz-transform: scale(2); /* FF */_x000D_
-webkit-transform: scale(2); /* Safari and Chrome */_x000D_
-o-transform: scale(2); /* Opera */_x000D_
transform: scale(2);_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
/* Might want to wrap a span around your checkbox text */_x000D_
.checkboxtext_x000D_
{_x000D_
/* Checkbox text */_x000D_
font-size: 110%;_x000D_
display: inline;_x000D_
}
_x000D_
<input type="checkbox" name="optiona" id="opta" checked />_x000D_
<span class="checkboxtext">_x000D_
Option A_x000D_
</span>_x000D_
<input type="checkbox" name="optionb" id="optb" />_x000D_
<span class="checkboxtext">_x000D_
Option B_x000D_
</span>_x000D_
<input type="checkbox" name="optionc" id="optc" />_x000D_
<span class="checkboxtext">_x000D_
Option C_x000D_
</span>
_x000D_
var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];_x000D_
var merged = [].concat.apply([], arrays);_x000D_
alert(merged);
_x000D_
From the LESS website:
If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:
@import "lib.css"; The directive will just be left as is, and end up in the CSS output.
As jitbit points out in the comments below, this is really only useful for development purposes, as you wouldn't want to have unnecessary @import
s consuming precious bandwidth.
Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration
class), you can use the valueOf
method of java.lang.Enum
subclass:
MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Laravel [5.4]
My solution was to use global session helper: session()
Its functionality is a little bit harder than $request->session().
writing:
session(['key'=>'value']);
pushing:
session()->push('key', $notification);
retrieving:
session('key');
I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.
C:\Users\USER\AppData\Roaming\Notepad++\backup
or
%AppData%\Notepad++\backup
Like this:
System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
string parentDirectory = myDirectory.Parent.FullName;
Good luck!
My preferred approach is using the SSH config file (described below), but there are a few possible solutions depending on your usages.
I think the best answer for this approach is christianbundy's reply to the accepted answer:
ssh -t example.com "cd /foo/bar; exec \$SHELL -l"
Using double quotes will allow you to use variables from your local machine, unless they are escaped (as $SHELL
is here). Alternatively, you can use single quotes, and all of the variables you use will be the ones from the target machine:
ssh -t example.com 'cd /foo/bar; exec $SHELL -l'
You can simplify the command by wrapping it in a bash function. Let's say you just want to type this:
sshcd example.com /foo/bar
You can make this work by adding this to your ~/.bashrc
:
sshcd () { ssh -t "$1" "cd \"$2\"; exec \$SHELL -l"; }
If you are using a variable that exists on the remote machine for the directory, be sure to escape it or put it in single quotes. For example, this will cd to the directory that is stored in the JBOSS_HOME
variable on the remote machine:
sshcd example.com \$JBOSS_HOME
If you'd like to see this behavior all the time for specific (or any) hosts with the normal ssh command without having to use extra command line arguments, you can set the RequestTTY
and RemoteCommand
options in your ssh config file.
For example, I'd like to type only this command:
ssh qaapps18
but want it to always behave like this command:
ssh -t qaapps18 'cd $JBOSS_HOME; exec $SHELL'
So I added this to my ~/.ssh/config
file:
Host *apps*
RequestTTY yes
RemoteCommand cd $JBOSS_HOME; exec $SHELL
Now this rule applies to any host with "apps" in its hostname.
For more information, see http://man7.org/linux/man-pages/man5/ssh_config.5.html
I came here for a similar problem I was facing with my table headers.
@MrMisterMan's answer, as well as others, were really helpful, but the borders were beating my game. So, I did some research to find the use rowspan.
Here's what I did and I guess it might help others facing something similar.
<table style="width: 100%; margin-top: 10px; font-size: 0.8em;" border="1px">_x000D_
<tr align="center" >_x000D_
<th style="padding:2.5px; width: 10%;" rowspan="2">Item No</th>_x000D_
<th style="padding:2.5px; width: 55%;" rowspan="2">DESCRIPTION</th>_x000D_
<th style="padding:2.5px;" rowspan="2">Quantity</th>_x000D_
<th style="padding:2.5px;" colspan="2">Rate per Item</th>_x000D_
<th style="padding:2.5px;" colspan="2">AMOUNT</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Rs.</th>_x000D_
<th>P.</th>_x000D_
<th>Rs.</th>_x000D_
<th>P.</th>_x000D_
</tr>_x000D_
</table>
_x000D_
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();
//if List not empty
if (!(sList.size() ==0)) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
Use this construction, to keep all input params but page
{!! $myItems->appends(Request::capture()->except('page'))->render() !!}
Why?
1) you strip down everything that added to request like that
$request->request->add(['variable' => 123]);
2) you don't need $request as input parameter for the function
3) you are excluding "page"
PS) and it works for Laravel 5.1
I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).
Add the permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Add receiver and service:
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="Launcher" />
Create class Launcher:
public class Launcher extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new AsyncTask<Service, Void, Service>() {
@Override
protected Service doInBackground(Service... params) {
Service service = params[0];
PackageManager pm = service.getPackageManager();
try {
Intent target = pm.getLaunchIntentForPackage("your.package.id");
if (target != null) {
service.startActivity(target);
synchronized (this) {
wait(3000);
}
} else {
throw new ActivityNotFoundException();
}
} catch (ActivityNotFoundException | InterruptedException ignored) {
}
return service;
}
@Override
protected void onPostExecute(Service service) {
service.stopSelf();
}
}.execute(this);
return START_STICKY;
}
}
Create class BootUpReceiver
to do action after android reboot.
For example launch MainActivity:
public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent target = new Intent(context, MainActivity.class);
target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(target);
}
}
It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).
This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.
The draft of HTML5 makes the attribute optional.
use this expression
var RegExpression = /^[a-zA-Z\s]*$/;
for more refer this http://tools.netshiftmedia.com
MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.
I found that this can happen if the referenced project is targeting a higher version of the framework than the project that is trying to use it. You can tell if this is the problem by going to the output window and looking for something similar to this:
The primary reference "my_reference" could not be resolved because it was built against the ".NETFramework,Version=v4.7.2" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.7".
The solution is to change the target framework of one or other of the projects.
First of all Arrays class is an utility class which contains no. of utility methods to operate on Arrays (thanks to Arrays class otherwise we would have needed to create our own methods to act on Array objects)
asList
method is one of the utility methods of Array
class ,it is static method thats why we can call this method by its class name (like Arrays.asList(T...a)
)ArrayList
object, it just returns a List reference to existing Array
object(so now after using asList
method, two references to existing Array
object gets created)List
object , may NOT work on this Array object using List
reference like
for example, Array
s size is fixed in length, hence you obviously can not add or remove elements from Array
object using this List
reference (like list.add(10)
or list.remove(10);
else it will throw UnsupportedOperationException)Array
s object ( as you are operating on existing Array object by using list reference)In first case you are creating a new Arraylist
object (in 2nd case only reference to existing Array object is created but not a new ArrayList
object) ,so now there are two different objects one is Array
object and another is ArrayList
object and no connection between them ( so changes in one object will not be reflected/affected in another object ( that is in case 2 Array
and Arraylist
are two different objects)
Integer [] ia = {1,2,3,4};
System.out.println("Array : "+Arrays.toString(ia));
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); // new ArrayList object is created , no connection between existing Array Object
list1.add(5);
list1.add(6);
list1.remove(0);
list1.remove(0);
System.out.println("list1 : "+list1);
System.out.println("Array : "+Arrays.toString(ia));
Integer [] ia = {1,2,3,4};
System.out.println("Array : "+Arrays.toString(ia));
List<Integer> list2 = Arrays.asList(ia); // creates only a (new ) List reference to existing Array object (and NOT a new ArrayList Object)
// list2.add(5); // it will throw java.lang.UnsupportedOperationException - invalid operation (as Array size is fixed)
list2.set(0,10); // making changes in existing Array object using List reference - valid
list2.set(1,11);
ia[2]=12; // making changes in existing Array object using Array reference - valid
System.out.println("list2 : "+list2);
System.out.println("Array : "+Arrays.toString(ia));
Mysql-native has been outdated so it became MySQL2 that is a new module created with the help of the original MySQL module's team. This module has more features and I think it has what you want as it has prepared statements(by using.execute()) like in PHP for more security.
It's also very active(the last change was from 2-1 days) I didn't try it before but I think it's what you want and more.
In case you want to have a default text as a sort of placeholder/hint but not considered a valid value (something like "complete here", "select your nation" ecc.) you can do something like this:
<select>_x000D_
<option value="" selected disabled hidden>Choose here</option>_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
<option value="3">Three</option>_x000D_
<option value="4">Four</option>_x000D_
<option value="5">Five</option>_x000D_
</select>
_x000D_
Yes - it appears you forgot to add yourself to the sysadmin role when installing SQL Server. If you are a local administrator on your machine, this blog post can help you use SQLCMD to get your account into the SQL Server sysadmin group without having to reinstall. It's a bit of a security hole in SQL Server, if you ask me, but it'll help you out in this case.
They must have included this as a feature, because now setting a different @JsonProperty
for a getter and setter results in exactly what you would expect (different property name during serialization and deserialization for the same field). Jackson version 2.6.7
Another possibility (esp. with multiple Oracle homes)
set ORACLE_SID=$SID
sqlplus /nolog
conn / as sysdba;
I look for good answer for this... and I found this:
First delete the 'no file chosen'
input[type="file"]{
font-size: 0px;
}
then work the button with the -webkit-file-upload-button
, this way:
input[type="file"]::-webkit-file-input-button{
font-size: 16px; /*normal size*/
}
hope this is what you were looking for, it works for me.
These are the changes to make:
CSS:
#container {
width: 100%;
height: 100%;
top: 0;
position: absolute;
visibility: hidden;
display: none;
background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
visibility: visible;
display: block;
}
.reveal-modal {
position: relative;
margin: 0 auto;
top: 25%;
}
/* Remove the left: 50% */
HTML:
<a href="#container">Reveal</a>
<div id="container">
<div id="exampleModal" class="reveal-modal">
........
<a href="#">Close Modal</a>
</div>
</div>
It skips all whitespace (spaces, tabs, new lines, etc.) by default. You can either change its behavior, or use a slightly different mechanism. To change its behavior, use the manipulator noskipws
, as follows:
cin >> noskipws >> a[i];
But, since you seem like you want to look at the individual characters, I'd suggest using get
, like this prior to your loop
cin.get( a, n );
Note: get
will stop retrieving chars from the stream if it either finds a newline char (\n
) or after n-1 chars. It stops early so that it can append the null character (\0
) to the array. You can read more about the istream
interface here.
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
It is possible to do (in the deployed repository)
git fetch
git checkout origin/master -- path/to/file
The fetch will download all the recent changes, but it will not put it in your current checked out code (working area).
The checkout will update the working tree with the particular file from the downloaded changes (origin/master
).
At least this works for me for those little small typo fixes, where it feels weird to create a branch etc just to change one word in a file.
You can use html and be a boss with simple things :
<embed src="music.mp3" width="3000" height="200" controls>
This will give you what you want in a pop-up.
for(var i = 0; i < users.Count; i++){
alert(users[i].id);
}
You should use "r"
for opening text files. Different operating systems have slightly different ways of storing text, and this will perform the correct translations so that you don't need to know about the idiosyncracies of the local operating system. For example, you will know that newlines will always appear as a simple "\n"
, regardless of where the code runs.
You should use "rb"
if you're opening non-text files, because in this case, the translations are not appropriate.
On your shell type my_print_defaults --help
At the bottom of the result, you should be able to see the file from which the server reads the configurations. It prints something like this:
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf
It is not necessary that onRestoreInstanceState will always be called after onSaveInstanceState.
Note that : onRestoreInstanceState will always be called, when activity is rotated (when orientation is not handled) or open your activity and then open other apps so that your activity instance is cleared from memory by OS.
What about System.getProperty("user.dir")
? It'll give you the working directory from where your program was launched.
See System Properties from the Java Tutorial for an overview of Java's System Properties.
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){_x000D_
return String.fromCharCode(parseInt(v, 16));_x000D_
}).join('');_x000D_
_x000D_
document.write(asciiVal);
_x000D_
Try The Below Code It Works In Normal State
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/TextLabel">
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Hiiiii"
android:id="@+id/edit_id"/>
</android.support.design.widget.TextInputLayout>
In Styles Folder TextLabel Code
<style name="TextLabel" parent="TextAppearance.AppCompat">
<!-- Hint color and label color in FALSE state -->
<item name="android:textColorHint">@color/Color Name</item>
<item name="android:textSize">20sp</item>
<!-- Label color in TRUE state and bar color FALSE and TRUE State -->
<item name="colorAccent">@color/Color Name</item>
<item name="colorControlNormal">@color/Color Name</item>
<item name="colorControlActivated">@color/Color Name</item>
</style>
Set To Main Theme of App,It Works Only Highlight State Only
<item name="colorAccent">@color/Color Name</item>
Update:
UnsupportedOperationException: Can't convert to color: type=0x2 in api 16 or below
Update:
Are you using Material Components Library
You can add below lines to your main theme
<item name="colorPrimary">@color/your_color</item> // Activated State
<item name="colorOnSurface">@color/your_color</item> // Normal State
or else do you want different colors in noraml state and activated state and with customization follow below code
<style name="Widget.App.TextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<item name="materialThemeOverlay">@style/ThemeOverlay.App.TextInputLayout</item>
<item name="shapeAppearance">@style/ShapeAppearance.App.SmallComponent</item> //Changes the Shape Apperance
<!--<item name="hintTextColor">?attr/colorOnSurface</item>--> //When you added this line it will applies only one color in normal and activate state i.e colorOnSurface color
</style>
<style name="ThemeOverlay.App.TextInputLayout" parent="">
<item name="colorPrimary">@color/colorPrimaryDark</item> //Activated color
<item name="colorOnSurface">@color/colorPrimary</item> //Normal color
<item name="colorError">@color/colorPrimary</item> //Error color
//Text Appearance styles
<item name="textAppearanceSubtitle1">@style/TextAppearance.App.Subtitle1</item>
<item name="textAppearanceCaption">@style/TextAppearance.App.Caption</item>
<!--Note: When setting a materialThemeOverlay on a custom TextInputLayout style, don’t forget to set editTextStyle to either a @style/Widget.MaterialComponents.TextInputEditText.* style or to a custom one that inherits from that.
The TextInputLayout styles set materialThemeOverlay that overrides editTextStyle with the specific TextInputEditText style needed. Therefore, you don’t need to specify a style tag on the edit text.-->
<item name="editTextStyle">@style/Widget.MaterialComponents.TextInputEditText.OutlinedBox</item>
</style>
<style name="TextAppearance.App.Subtitle1" parent="TextAppearance.MaterialComponents.Subtitle1">
<item name="fontFamily">@font/your_font</item>
<item name="android:fontFamily">@font/your_font</item>
</style>
<style name="TextAppearance.App.Caption" parent="TextAppearance.MaterialComponents.Caption">
<item name="fontFamily">@font/your_font</item>
<item name="android:fontFamily">@font/your_font</item>
</style>
<style name="ShapeAppearance.App.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent">
<item name="cornerFamily">cut</item>
<item name="cornerSize">4dp</item>
</style>
Add the below line to your main theme or else you can set style to textinputlayout in your xml
<item name="textInputStyle">@style/Widget.App.TextInputLayout</item>
As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval()
. If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:
// Use a named immediately-invoked function expression.
(function worker() {
$.get('ajax/test.html', function(data) {
// Now that we've completed the request schedule the next one.
$('.result').html(data);
setTimeout(worker, 5000);
});
})();
For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
Exit an app other way
I did this helper, though, that use no private stuff:
Exit(0);
To get the content of a directory you can use
$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"
Then you can loop over this variable as well:
for ($i=0; $i -lt $files.Count; $i++) {
$outfile = $files[$i].FullName + "out"
Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
An even easier way to put this is the foreach
loop (thanks to @Soapy and @MarkSchultheiss):
foreach ($f in $files){
$outfile = $f.FullName + "out"
Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.
'\u2060', // Word Joiner
'\u2061', // FUNCTION APPLICATION
'\u2062', // INVISIBLE TIMES
'\u2063', // INVISIBLE SEPARATOR
'\u2064', // INVISIBLE PLUS
'\u2066', // LEFT - TO - RIGHT ISOLATE
'\u2067', // RIGHT - TO - LEFT ISOLATE
'\u2068', // FIRST STRONG ISOLATE
'\u2069', // POP DIRECTIONAL ISOLATE
'\u206A', // INHIBIT SYMMETRIC SWAPPING
'\u206B', // ACTIVATE SYMMETRIC SWAPPING
'\u206C', // INHIBIT ARABIC FORM SHAPING
'\u206D', // ACTIVATE ARABIC FORM SHAPING
'\u206E', // NATIONAL DIGIT SHAPES
'\u206F', // NOMINAL DIGIT SHAPES
'\u200B', // Zero-Width Space
'\u200C', // Zero Width Non-Joiner
'\u200D', // Zero Width Joiner
'\u200E', // Left-To-Right Mark
'\u200F', // Right-To-Left Mark
'\u061C', // Arabic Letter Mark
'\uFEFF', // Byte Order Mark
'\u180E', // Mongolian Vowel Separator
'\u00AD' // soft-hyphen
Read file contents into a variable:
for /f "delims=" %%x in (version.txt) do set Build=%%x
or
set /p Build=<version.txt
Both will act the same with only a single line in the file, for more lines the for
variant will put the last line into the variable, while set /p
will use the first.
Using the variable – just like any other environment variable – it is one, after all:
%Build%
So to check for existence:
if exist \\fileserver\myapp\releasedocs\%Build%.doc ...
Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.
For example,
package main
import (
"flag"
"fmt"
"os"
"strconv"
)
func main() {
flag.Parse()
s := flag.Arg(0)
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
}
fmt.Println(s, i)
}
As mentioned on the addMethod documentation:
Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx
So yes, you have to add a method for each regular expression. The overhead is minimal, while it allows you to give the regex a name (not to be underestimated), a default message (handy) and the ability to reuse it a various places, without duplicating the regex itself over and over.
Use can use filter of Java 8, and create another list if you don't want to change the old list:
List<ProducerDTO> result = producersProcedureActive
.stream()
.filter(producer -> producer.getPod().equals(pod))
.collect(Collectors.toList());
if you want to align only this cells, you can do something like this:
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$sheet->getStyle("A1:B1")->applyFromArray($style);
But, if you want to apply this style to all cells, try this:
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$sheet->getDefaultStyle()->applyFromArray($style);
It sounds like you're using an incorrect address:
To access the Service I enter http://localhost/project/myService.svc/FileUpload
Assuming you mean this is the address you give your client code then I suspect it should actually be:
http://localhost/project/myService.svc
If you want to clean up the whole form, you can use such approach. This is your model into controller:
$scope.registrationForm = {
'firstName' : '',
'lastName' : ''
};
Your HTML:
<form class="form-horizontal" name="registrForm" role="form">
<input type="text" class="form-control"
name="firstName"
id="firstName"
ng-model="registrationForm.firstName"
placeholder="First name"
required> First name
<input type="text" class="form-control"
name="lastName"
id="lastName"
ng-model="registrationForm.lastName"
placeholder="Last name"
required> Last name
</form>
Then, you should clone/save your clear state by:
$scope.originForm = angular.copy($scope.registrationForm);
Your reset function will be:
$scope.resetForm = function(){
$scope.registrationForm = angular.copy($scope.originForm); // Assign clear state to modified form
$scope.registrForm.$setPristine(); // this line will update status of your form, but will not clean your data, where `registrForm` - name of form.
};
In such way you are able to clean up the whole your form
If you are trying to take a value from the same array and trying to update it, you can use the following code.
{ 'condition': {
'ts': [ '5a81625ba0ff65023c729022',
'5a8161ada0ff65023c728f51',
'5a815fb4a0ff65023c728dcd']}
If the collection is userData['condition']['ts'] and we need to
for i,supplier in enumerate(userData['condition']['ts']):
supplier = ObjectId(supplier)
userData['condition']['ts'][i] = supplier
The output will be
{'condition': { 'ts': [ ObjectId('5a81625ba0ff65023c729022'),
ObjectId('5a8161ada0ff65023c728f51'),
ObjectId('5a815fb4a0ff65023c728dcd')]}
$product_id = $this->input->get('id', TRUE);
echo $product_id;
installed openssl on mac with brew but nothing found on /usr/local/bin
where other brew installed bins are located. Found my fresh openssl here:
/usr/local/opt/openssl/bin/openssl
Run it like this:
/usr/local/opt/openssl/bin/openssl version
I don't want to update OS X openssl, while some OS stuff or other 3rd party apps may have dependency on older version.
I also don't mind longer path than just openssl
Writing this here for all the Googlers who are looking for location of openssl installed by brew.
For some git-commands you can specify --verbose
,
git 'command' --verbose
or
git 'command' -v
.
Make sure the switch is after the actual git command. Otherwise - it won't work!
Also useful:
git 'command' --dry-run
In my case, using Android Studio 4.0, the below solved the issue;
Add to 'gradle.properties' file;
android.injected.testOnly=false
I too had the same issue and I believe the code below is more simple and it is working for me,
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private String _body;
public MultiReadHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
_body = "";
BufferedReader bufferedReader = request.getReader();
String line;
while ((line = bufferedReader.readLine()) != null){
_body += line;
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(_body.getBytes());
return new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
in the filter java class,
HttpServletRequest properRequest = ((HttpServletRequest) req);
MultiReadHttpServletRequest wrappedRequest = new MultiReadHttpServletRequest(properRequest);
req = wrappedRequest;
inputJson = IOUtils.toString(req.getReader());
System.out.println("body"+inputJson);
Please let me know if you have any queries
You cannot undo the latest git add, but you can undo all add
s since the last commit. git reset
without a commit argument resets the index (unstages staged changes):
git reset
the
:checked
pseudo-class initially applies to such elements that have the HTML4selected
andchecked
attributes
Source: w3.org
So, this CSS works, although styling the color
is not possible in every browser:
option:checked { color: red; }
An example of this in action, hiding the currently selected item from the drop down list.
option:checked { display:none; }
_x000D_
<select>_x000D_
<option>A</option>_x000D_
<option>B</option>_x000D_
<option>C</option>_x000D_
</select>
_x000D_
To style the currently selected option in the closed dropdown as well, you could try reversing the logic:
select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */
You can get list of temp tables by following query :
select left(name, charindex('_',name)-1)
from tempdb..sysobjects
where charindex('_',name) > 0 and
xtype = 'u' and not object_id('tempdb..'+name) is null
Matlab
and R
translationsMatlab code
function [signals,avgFilter,stdFilter] = ThresholdingAlgo(y,lag,threshold,influence)
% Initialise signal results
signals = zeros(length(y),1);
% Initialise filtered series
filteredY = y(1:lag+1);
% Initialise filters
avgFilter(lag+1,1) = mean(y(1:lag+1));
stdFilter(lag+1,1) = std(y(1:lag+1));
% Loop over all datapoints y(lag+2),...,y(t)
for i=lag+2:length(y)
% If new value is a specified number of deviations away
if abs(y(i)-avgFilter(i-1)) > threshold*stdFilter(i-1)
if y(i) > avgFilter(i-1)
% Positive signal
signals(i) = 1;
else
% Negative signal
signals(i) = -1;
end
% Make influence lower
filteredY(i) = influence*y(i)+(1-influence)*filteredY(i-1);
else
% No signal
signals(i) = 0;
filteredY(i) = y(i);
end
% Adjust the filters
avgFilter(i) = mean(filteredY(i-lag:i));
stdFilter(i) = std(filteredY(i-lag:i));
end
% Done, now return results
end
Example:
% Data
y = [1 1 1.1 1 0.9 1 1 1.1 1 0.9 1 1.1 1 1 0.9 1 1 1.1 1 1,...
1 1 1.1 0.9 1 1.1 1 1 0.9 1 1.1 1 1 1.1 1 0.8 0.9 1 1.2 0.9 1,...
1 1.1 1.2 1 1.5 1 3 2 5 3 2 1 1 1 0.9 1,...
1 3 2.6 4 3 3.2 2 1 1 0.8 4 4 2 2.5 1 1 1];
% Settings
lag = 30;
threshold = 5;
influence = 0;
% Get results
[signals,avg,dev] = ThresholdingAlgo(y,lag,threshold,influence);
figure; subplot(2,1,1); hold on;
x = 1:length(y); ix = lag+1:length(y);
area(x(ix),avg(ix)+threshold*dev(ix),'FaceColor',[0.9 0.9 0.9],'EdgeColor','none');
area(x(ix),avg(ix)-threshold*dev(ix),'FaceColor',[1 1 1],'EdgeColor','none');
plot(x(ix),avg(ix),'LineWidth',1,'Color','cyan','LineWidth',1.5);
plot(x(ix),avg(ix)+threshold*dev(ix),'LineWidth',1,'Color','green','LineWidth',1.5);
plot(x(ix),avg(ix)-threshold*dev(ix),'LineWidth',1,'Color','green','LineWidth',1.5);
plot(1:length(y),y,'b');
subplot(2,1,2);
stairs(signals,'r','LineWidth',1.5); ylim([-1.5 1.5]);
R code
ThresholdingAlgo <- function(y,lag,threshold,influence) {
signals <- rep(0,length(y))
filteredY <- y[0:lag]
avgFilter <- NULL
stdFilter <- NULL
avgFilter[lag] <- mean(y[0:lag], na.rm=TRUE)
stdFilter[lag] <- sd(y[0:lag], na.rm=TRUE)
for (i in (lag+1):length(y)){
if (abs(y[i]-avgFilter[i-1]) > threshold*stdFilter[i-1]) {
if (y[i] > avgFilter[i-1]) {
signals[i] <- 1;
} else {
signals[i] <- -1;
}
filteredY[i] <- influence*y[i]+(1-influence)*filteredY[i-1]
} else {
signals[i] <- 0
filteredY[i] <- y[i]
}
avgFilter[i] <- mean(filteredY[(i-lag):i], na.rm=TRUE)
stdFilter[i] <- sd(filteredY[(i-lag):i], na.rm=TRUE)
}
return(list("signals"=signals,"avgFilter"=avgFilter,"stdFilter"=stdFilter))
}
Example:
# Data
y <- c(1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1)
lag <- 30
threshold <- 5
influence <- 0
# Run algo with lag = 30, threshold = 5, influence = 0
result <- ThresholdingAlgo(y,lag,threshold,influence)
# Plot result
par(mfrow = c(2,1),oma = c(2,2,0,0) + 0.1,mar = c(0,0,2,1) + 0.2)
plot(1:length(y),y,type="l",ylab="",xlab="")
lines(1:length(y),result$avgFilter,type="l",col="cyan",lwd=2)
lines(1:length(y),result$avgFilter+threshold*result$stdFilter,type="l",col="green",lwd=2)
lines(1:length(y),result$avgFilter-threshold*result$stdFilter,type="l",col="green",lwd=2)
plot(result$signals,type="S",col="red",ylab="",xlab="",ylim=c(-1.5,1.5),lwd=2)
This code (both languages) will yield the following result for the data of the original question:
Matlab
demonstration code(click to create data)
function [] = RobustThresholdingDemo()
%% SPECIFICATIONS
lag = 5; % lag for the smoothing
threshold = 3.5; % number of st.dev. away from the mean to signal
influence = 0.3; % when signal: how much influence for new data? (between 0 and 1)
% 1 is normal influence, 0.5 is half
%% START DEMO
DemoScreen(30,lag,threshold,influence);
end
function [signals,avgFilter,stdFilter] = ThresholdingAlgo(y,lag,threshold,influence)
signals = zeros(length(y),1);
filteredY = y(1:lag+1);
avgFilter(lag+1,1) = mean(y(1:lag+1));
stdFilter(lag+1,1) = std(y(1:lag+1));
for i=lag+2:length(y)
if abs(y(i)-avgFilter(i-1)) > threshold*stdFilter(i-1)
if y(i) > avgFilter(i-1)
signals(i) = 1;
else
signals(i) = -1;
end
filteredY(i) = influence*y(i)+(1-influence)*filteredY(i-1);
else
signals(i) = 0;
filteredY(i) = y(i);
end
avgFilter(i) = mean(filteredY(i-lag:i));
stdFilter(i) = std(filteredY(i-lag:i));
end
end
% Demo screen function
function [] = DemoScreen(n,lag,threshold,influence)
figure('Position',[200 100,1000,500]);
subplot(2,1,1);
title(sprintf(['Draw data points (%.0f max) [settings: lag = %.0f, '...
'threshold = %.2f, influence = %.2f]'],n,lag,threshold,influence));
ylim([0 5]); xlim([0 50]);
H = gca; subplot(2,1,1);
set(H, 'YLimMode', 'manual'); set(H, 'XLimMode', 'manual');
set(H, 'YLim', get(H,'YLim')); set(H, 'XLim', get(H,'XLim'));
xg = []; yg = [];
for i=1:n
try
[xi,yi] = ginput(1);
catch
return;
end
xg = [xg xi]; yg = [yg yi];
if i == 1
subplot(2,1,1); hold on;
plot(H, xg(i),yg(i),'r.');
text(xg(i),yg(i),num2str(i),'FontSize',7);
end
if length(xg) > lag
[signals,avg,dev] = ...
ThresholdingAlgo(yg,lag,threshold,influence);
area(xg(lag+1:end),avg(lag+1:end)+threshold*dev(lag+1:end),...
'FaceColor',[0.9 0.9 0.9],'EdgeColor','none');
area(xg(lag+1:end),avg(lag+1:end)-threshold*dev(lag+1:end),...
'FaceColor',[1 1 1],'EdgeColor','none');
plot(xg(lag+1:end),avg(lag+1:end),'LineWidth',1,'Color','cyan');
plot(xg(lag+1:end),avg(lag+1:end)+threshold*dev(lag+1:end),...
'LineWidth',1,'Color','green');
plot(xg(lag+1:end),avg(lag+1:end)-threshold*dev(lag+1:end),...
'LineWidth',1,'Color','green');
subplot(2,1,2); hold on; title('Signal output');
stairs(xg(lag+1:end),signals(lag+1:end),'LineWidth',2,'Color','blue');
ylim([-2 2]); xlim([0 50]); hold off;
end
subplot(2,1,1); hold on;
for j=2:i
plot(xg([j-1:j]),yg([j-1:j]),'r'); plot(H,xg(j),yg(j),'r.');
text(xg(j),yg(j),num2str(j),'FontSize',7);
end
end
end
You can use:
type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt
or something like this:
echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt
DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}
add to your using clause :
using System.Linq;
and add :
System.Data.DataSetExtensions
to references.
AFAIK, no, you can't. You have to remove it and recreate it. Actually, you can overwrite a symlink and thus update the pathname referenced by it:
$ ln -s .bashrc test
$ ls -al test
lrwxrwxrwx 1 pascal pascal 7 2009-09-23 17:12 test -> .bashrc
$ ln -s .profile test
ln: creating symbolic link `test': File exists
$ ln -s -f .profile test
$ ls -al test
lrwxrwxrwx 1 pascal pascal 8 2009-09-23 17:12 test -> .profile
EDIT: As the OP pointed out in a comment, using the --force
option will make ln
perform a system call to unlink()
before symlink()
. Below, the output of strace
on my linux box proving it:
$ strace -o /tmp/output.txt ln -s -f .bash_aliases test
$ grep -C3 ^unlink /tmp/output.txt
lstat64("test", {st_mode=S_IFLNK|0777, st_size=7, ...}) = 0
stat64(".bash_aliases", {st_mode=S_IFREG|0644, st_size=2043, ...}) = 0
symlink(".bash_aliases", "test") = -1 EEXIST (File exists)
unlink("test") = 0
symlink(".bash_aliases", "test") = 0
close(0) = 0
close(1) = 0
So I guess the final answer is "no".
EDIT: The following is copied from Arto Bendiken's answer over on unix.stackexchange.com, circa 2016.
This can indeed be done atomically with rename(2)
, by first creating the new symlink under a temporary name and then cleanly overwriting the old symlink in one go. As the man page states:
If newpath refers to a symbolic link the link will be overwritten.
In the shell, you would do this with mv -T
as follows:
$ mkdir a b
$ ln -s a z
$ ln -s b z.new
$ mv -T z.new z
You can strace
that last command to make sure it is indeed using rename(2)
under the hood:
$ strace mv -T z.new z
lstat64("z.new", {st_mode=S_IFLNK|0777, st_size=1, ...}) = 0
lstat64("z", {st_mode=S_IFLNK|0777, st_size=1, ...}) = 0
rename("z.new", "z") = 0
Note that in the above, both mv -T
and strace
are Linux-specific.
On FreeBSD, use mv -h
alternately.
Editor's note: This is how Capistrano has done it for years now, ever since ~2.15. See this pull request.
Well its too late may be to answer but here is what i did to get results back from the DialogFragment
. very similar to @brandon's answer.
Here i am calling DialogFragment
from a fragment, just place this code where you are calling your dialog.
FragmentManager fragmentManager = getFragmentManager();
categoryDialog.setTargetFragment(this,1);
categoryDialog.show(fragmentManager, "dialog");
where categoryDialog
is my DialogFragment
which i want to call and after this in your implementation of dialogfragment
place this code where you are setting your data in intent. The value of resultCode
is 1 you can set it or use system Defined.
Intent intent = new Intent();
intent.putExtra("listdata", stringData);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
getDialog().dismiss();
now its time to get back to to the calling fragment and implement this method. check for data validity or result success if you want with resultCode
and requestCode
in if condition.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//do what ever you want here, and get the result from intent like below
String myData = data.getStringExtra("listdata");
Toast.makeText(getActivity(),data.getStringExtra("listdata"),Toast.LENGTH_SHORT).show();
}
I just wanted to include a link to a resolution to an issue I was having with VS2008 and TFS08.
I accidently opened my solution without being connected to my network and was not able to get it "back the way it was" and had to rebind every time I openned.
I found the solution here; http://www.fkollmann.de/v2/post/Visual-Studio-2008-refuses-to-bind-to-TFS-or-to-open-solution-source-controlled.aspx
Basically, you need to open the "Connect to Team Foundation Server" and then "Servers..." once there, Delete/Remove your server and re-add it. This fixed my issue.
777
is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..
You said I am using windows 7.
if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone
and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.
If you want permission to be set on sub-directories
too then usually their is option to set permission recursively use that.
And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes
and write the following command
chmod 0777 module_installation/
for recursive
chmod -R 0777 module_installation/
Hope this will help you
Android 4.4 (Kit Kat) does have a new sniffing capability for Bluetooth. You should give it a try.
If you don’t own a sniffing device however, you aren’t necessarily out of luck. In many cases we can obtain positive results with a new feature introduced in Android 4.4: the ability to capture all Bluetooth HCI packets and save them to a file.
When the Analyst has finished populating the capture file by running the application being tested, he can pull the file generated by Android into the external storage of the device and analyze it (with Wireshark, for example).
Once this setting is activated, Android will save the packet capture to /sdcard/btsnoop_hci.log to be pulled by the analyst and inspected.
Type the following in case /sdcard/
is not the right path on your particular device:
adb shell echo \$EXTERNAL_STORAGE
We can then open a shell and pull the file: $adb pull /sdcard/btsnoop_hci.log and inspect it with Wireshark, just like a PCAP collected by sniffing WiFi traffic for example, so it is very simple and well supported:
You can enable this by going to Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log."
In .NET framework 3.5 and above you can use Enumerable.GroupBy
which returns an enumerable of enumerables of duplicate keys, and then filter out any of the enumerables that have a Count of <=1, then select their keys to get back down to a single enumerable:
var duplicateKeys = list.GroupBy(x => x)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
Note that on Python 3, it's not really fair to say any of:
str
s are UTFx for any x (eg. UTF8)
str
s are Unicode
str
s are ordered collections of Unicode characters
Python's str
type is (normally) a sequence of Unicode code points, some of which map to characters.
Even on Python 3, it's not as simple to answer this question as you might imagine.
An obvious way to test for ASCII-compatible strings is by an attempted encode:
"Hello there!".encode("ascii")
#>>> b'Hello there!'
"Hello there... ?!".encode("ascii")
#>>> Traceback (most recent call last):
#>>> File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)
The error distinguishes the cases.
In Python 3, there are even some strings that contain invalid Unicode code points:
"Hello there!".encode("utf8")
#>>> b'Hello there!'
"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>> File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed
The same method to distinguish them is used.
Place this on your model:
[DisplayName("Electric Fan")]
public bool ElectricFan { get; set; }
private string electricFanRate;
public string ElectricFanRate
{
get { return electricFanRate ?? (electricFanRate = "$15/month"); }
set { electricFanRate = value; }
}
And this in your cshtml:
<div class="row">
@Html.CheckBoxFor(m => m.ElectricFan, new { @class = "" })
@Html.LabelFor(m => m.ElectricFan, new { @class = "" })
@Html.DisplayTextFor(m => m.ElectricFanRate)
</div>
Which will output this:
If you click on the checkbox or the bold label it will check/uncheck the checkbox
The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:
^\d{1,45}$
where \d
is the same like [0-9]
.
Possible solutions:
Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.
If you use AWS you can use the load balancer to redirect the request to specific port based on the host.
l=[['A', 1], ['B', 2], ['C', 3]]
d={}
for i,j in l:
d.setdefault(i,j)
print(d)
Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:
phoneNumber = Regex.Replace(phoneNumber, "\\D", String.Empty);
I had similar Issue where we have GenericResponse object containing list of values
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
redisMatchedDriverUrl,
HttpMethod.POST,
requestEntity,
ResponseDTO.class
);
Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects
ObjectMapper mapper = new ObjectMapper();
List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
open the file named "jquery.fileupload-ui.js", you will see the code like this:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
autoUpload: false,
// The ID of the upload template:
uploadTemplateId: 'template-upload',
// The ID of the download template:
downloadTemplateId: 'template-download',
????
just add one line code --- the new attribute "acceptFileTypes",like this:
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
**acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,**
autoUpload: false,
// The ID of the upload template:
uploadTemplateId: 'template-upload',
// The ID of the download template:
downloadTemplateId: 'template-d
now you'll see everything is allright!~ you just take the attribute with a wrong place.
Use this code for sending attachment with upload file option using html form in phpmailer
<form method="post" action="" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Your Name *">
<input type="email" name="email" placeholder="Email *">
<textarea name="msg" placeholder="Your Message"></textarea>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="userfile" />
<input name="contact" type="submit" value="Submit Enquiry" />
</form>
<?php
if(isset($_POST["contact"]))
{
/////File Upload
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible invalid file upload !\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
////// Email
require_once("class.phpmailer.php");
require_once("class.smtp.php");
$mail_body = array($_POST['name'], $_POST['email'] , $_POST['msg']);
$new_body = "Name: " . $mail_body[0] . ", Email " . $mail_body[1] . " Description: " . $mail_body[2];
$d=strtotime("today");
$subj = 'New enquiry '. date("Y-m-d h:i:sa", $d);
$mail = new PHPMailer(); // create a new object
//$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only ,false = Disable
$mail->Host = "mail.yourhost.com";
$mail->Port = '465';
$mail->SMTPAuth = true; // enable
$mail->SMTPSecure = true;
$mail->IsHTML(true);
$mail->Username = "[email protected]"; //[email protected]
$mail->Password = "password";
$mail->SetFrom("[email protected]", "Your Website Name");
$mail->Subject = $subj;
$mail->Body = $new_body;
$mail->AddAttachment($uploadfile);
$mail->AltBody = 'Upload';
$mail->AddAddress("[email protected]");
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo '<p> Success </p> ';
}
}
?>
Use this link for reference.
I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.
public void Foo(int a, int b, int? c)
{
if(c.HasValue)
{
// do something with a,b and c
}
else
{
// do something with a and b only
}
}
TypeScript users:
I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.
In the test file, convert the import of the function from this:
import {foo} from '../foo_functions';
x = foo(y);
To this:
import * as FooFunctions from '../foo_functions';
x = FooFunctions.foo(y);
Then you can spy on FooFunctions.foo
:)
spyOn(FooFunctions, 'foo').and.callFake(...);
// ...
expect(FooFunctions.foo).toHaveBeenCalled();
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
For Spreedsheet + PHP 7, you must write instead of PHPExcel_Cell::columnIndexFromString
, \PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString
. And at the loop is a mistake, there you must <
not work with <=
. Otherwise, he takes a column too much into the loop.
BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;
So 2 basic things to get string visible in the different class:
//make sure you are importing the right R class
import your.namespace.R;
//don't forget about the context
public void some_method(Context context) {
context.getString(R.string.YOUR_STRING);
}
You can use self.data
in the clean_email
method to access the POST data before validation. It should contain a key called newsletter_sub
or newsletter_unsub
depending on which button was pressed.
# in the context of a django.forms form
def clean(self):
if 'newsletter_sub' in self.data:
# do subscribe
elif 'newsletter_unsub' in self.data:
# do unsubscribe
Here is a different solution for anyone interested. It uses the new For range in c++11
string str("(555) 555-5555");
string str2="";
for (const auto c: str){
if(!ispunct(c)){
str2.push_back(c);
}
}
str = str2;
//output: 555 5555555
cout<<str<<endl;
In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:
I was having this problem too and neither of these answers helped me. The issue was different, but the error was the described by the OP.
I check the logs of MySQL in /var/log/mysql
, and I saw this:
150309 5:03:19 [ERROR] /usr/sbin/mysqld: unknown variable 'lower_case_tables_names=1'
I opened the /etc/mysql/my.cnf
file and outcommented that line #
. After doing that, I was able to connect to the database.
Honestly I don't know what the problem was. The linode server was scheduled to restart due to maintenance, and this error came out of nowhere.
Try this one. It can handle scrolling as well and you can reuse the cells without the hassle of removing subviews you added before.
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
if( cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
cell.textLabel.text = [[NSArray arrayWithObjects:@"First",@"Second",@"Third",@"Forth",@"Fifth",@"Sixth",@"Seventh",@"Eighth",@"Nineth",@"Tenth",nil]
objectAtIndex:indexPath.row];
if (indexPath.row % 2) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
textField.placeholder = @"Enter Text";
textField.text = [inputTexts objectAtIndex:indexPath.row/2];
textField.tag = indexPath.row/2;
textField.delegate = self;
cell.accessoryView = textField;
[textField release];
} else
cell.accessoryView = nil;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[inputTexts replaceObjectAtIndex:textField.tag withObject:textField.text];
return YES;
}
- (void)viewDidLoad {
inputTexts = [[NSMutableArray alloc] initWithObjects:@"",@"",@"",@"",@"",nil];
[super viewDidLoad];
}
assert_has_calls
is another approach to this problem.
From the docs:
assert_has_calls (calls, any_order=False)
assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.
If any_order is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.
If any_order is True then the calls can be in any order, but they must all appear in mock_calls.
Example:
>>> from unittest.mock import call, Mock
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
Source: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls
Using the credentials helper command-line option:
git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin
In interface Builder. Select the UIButton -> Attributes Inspector -> Edge=Title and modify the edge insets
In your spring class, You can inject a bean annotated like as
@Autowired
@Qualifier("dbDataSource")
private DataSource dataSource;
and You add this in your context.xml
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
</beans:bean>
You can declare the JNDI resource in tomcat's server.xml using
<Resource name="jdbc/TestDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/TestDB"
username="pankaj"
password="pankaj123"
maxActive="100"
maxIdle="20"
minIdle="5"
maxWait="10000"/>
back to context.xml de spring add this
<ResourceLink name="jdbc/MyLocalDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" />
if, like this exmple you are injecting connection to database, make sure that MySQL jar is present in the tomcat lib directory, otherwise tomcat will not be able to create the MySQL database connection pool.
All the existing answers don't work for me because my case is a little bit different. It took me a few hours to get it to work. I'm using Eclipse.
My android project includes another normal java 1.6 project, which needs a 3rd party jar file. The trick is:
Hope this help those who have similar scenarios like mine.
You have to use absolute path to see if the file exists.
$abs_path = '/var/www/example.com/public_html/images/';
$file_url = 'http://www.example.com/images/' . $filename;
if (file_exists($abs_path . $filename)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
If you are writing for CMS or PHP framework then as far as I know all of them have defined constant for document root path.
e.g WordPress uses ABSPATH which can be used globally for working with files on the server using your code as well as site url.
Wordpress example:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
if (file_exists($image_path)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
I'm going an extra mile here :). Because this code would no need much maintenance and pretty solid, I would write it with as shorthand if statement:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
echo (file_exists($image_path))?'The file exists. URL:' . $file_url:'The file does not exist';
Shorthand IF statement explained:
$stringVariable = ($trueOrFalseComaprison > 0)?'String if true':'String if false';
var x = $($('div').html($('#container').clone())).html();
As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON (p.vTreasuryId = f.RFC) COLLATE Database_Default
std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
C++ FAQ: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1
Actually, a parent window can communicate with child or sibling windows or frames that have their own execution threads running.
You can make a class which extends org.xml.sax.helpers.DefaultHandler and call
start_<tag_name>(Attributes attrs);
and
end_<tag_name>();
For it is:
start_request_queue(attrs);
etc.
And then extends that class and implement xml configuration file parsers you want. Example:
... public void startElement(String uri, String name, String qname, org.xml.sax.Attributes attrs) throws org.xml.sax.SAXException { Class[] args = new Class[2]; args[0] = uri.getClass(); args[1] = org.xml.sax.Attributes.class; try { String mname = name.replace("-", ""); java.lang.reflect.Method m = getClass().getDeclaredMethod("start" + mname, args); m.invoke(this, new Object[] { uri, (org.xml.sax.Attributes)attrs }); }
catch (IllegalAccessException e) { throw new RuntimeException(e); }
catch (NoSuchMethodException e) { throw new RuntimeException(e); }
catch (java.lang.reflect.InvocationTargetException e) { org.xml.sax.SAXException se = new org.xml.sax.SAXException(e.getTargetException()); se.setStackTrace(e.getTargetException().getStackTrace()); }
and in a particular configuration parser:
public void start_Request(String uri, org.xml.sax.Attributes attrs) { // make sure to read attributes correctly System.err.println("Request, name="+ attrs.getValue(0); }
If you are running SQL Server in a local environment and not over a TCP/IP connection. Go to Protocols under SQL Server Configuration Manager, Properties, and disable TCP/IP. Once this is done then the error message will go away when restarting the service.
I offer one more solution in case it is worthful for someone else.
I have a history.js
file where I have the following:
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.pushLater = (...args) => setImmediate(() => history.push(...args))
export default history
Next, on my Root where I define my router I use the following:
import history from '../history'
import { Provider } from 'react-redux'
import { Router, Route, Switch } from 'react-router-dom'
export default class Root extends React.Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<Switch>
...
</Switch>
</Router>
</Provider>
)
}
}
Finally, on my actions.js
I import History and make use of pushLater
import history from './history'
export const login = createAction(
...
history.pushLater({ pathname: PATH_REDIRECT_LOGIN })
...)
This way, I can push to new actions after API calls.
Hope it helps!
Use this.getClass().getCanonicalName()
to get the full class name.
Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.
By omitting all parts of the head, the loop can also become infinite:
for (;;) {}
I have below solution which works correctly for me(After doing some Test cases). Extra Test cases are acceptable.
public class DateDiffernce
{
private int m_nDays = -1;
private int m_nWeek;
private int m_nMonth = -1;
private int m_nYear;
public int Days
{
get
{
return m_nDays;
}
}
public int Weeks
{
get
{
return m_nWeek;
}
}
public int Months
{
get
{
return m_nMonth;
}
}
public int Years
{
get
{
return m_nYear;
}
}
public void GetDifferenceBetwwenTwoDate(DateTime objDateTimeFromDate, DateTime objDateTimeToDate)
{
if (objDateTimeFromDate.Date > objDateTimeToDate.Date)
{
DateTime objDateTimeTemp = objDateTimeFromDate;
objDateTimeFromDate = objDateTimeToDate;
objDateTimeToDate = objDateTimeTemp;
}
if (objDateTimeFromDate == objDateTimeToDate)
{
//textBoxDifferenceDays.Text = " Same dates";
//textBoxAllDifference.Text = " Same dates";
return;
}
// If From Date's Day is bigger than borrow days from previous month
// & then subtract.
if (objDateTimeFromDate.Day > objDateTimeToDate.Day)
{
objDateTimeToDate = objDateTimeToDate.AddMonths(-1);
int nMonthDays = DateTime.DaysInMonth(objDateTimeToDate.Year, objDateTimeToDate.Month);
m_nDays = objDateTimeToDate.Day + nMonthDays - objDateTimeFromDate.Day;
}
// If From Date's Month is bigger than borrow 12 Month
// & then subtract.
if (objDateTimeFromDate.Month > objDateTimeToDate.Month)
{
objDateTimeToDate = objDateTimeToDate.AddYears(-1);
m_nMonth = objDateTimeToDate.Month + 12 - objDateTimeFromDate.Month;
}
//Below are best cases - simple subtraction
if (m_nDays == -1)
{
m_nDays = objDateTimeToDate.Day - objDateTimeFromDate.Day;
}
if (m_nMonth == -1)
{
m_nMonth = objDateTimeToDate.Month - objDateTimeFromDate.Month;
}
m_nYear = objDateTimeToDate.Year - objDateTimeFromDate.Year;
m_nWeek = m_nDays / 7;
m_nDays = m_nDays % 7;
}
}
this working
SELECT distinct filename
,last_value(dates)over (PARTITION BY filename ORDER BY filename)posd
,last_value(status)over (PARTITION BY filename ORDER BY filename )poss
FROM distemp.dbo.Shmy_table
The non-greedy regex modifiers are like their greedy counter-parts but with a ?
immediately following them:
* - zero or more
*? - zero or more (non-greedy)
+ - one or more
+? - one or more (non-greedy)
? - zero or one
?? - zero or one (non-greedy)
I know this is an old thread, but for any future visitors, the cause of this error is most likely because you haven't built your project from Build > Build Solution
. The reason you're getting this error when you try to run your project is because Visual Studio can't find the executable file that should be produced when you build your project.
I found this http://weblogs.asp.net/mikaelsoderstrom/archive/2010/07/30/add-namespaces-with-razor.aspx which explains how to add a custom namespace to all your razor pages.
Basically you can make this
using Microsoft.WebPages.Compilation;
public class PreApplicationStart
{
public static void InitializeApplication()
{
CodeGeneratorSettings.AddGlobalImport("Custom.Namespace");
}
}
and put the following code in your AssemblyInfo.cs
[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "InitializeApplication")]
the method InitializeApplication will be executed before Application_Start in global.asax
string d = "You hit ssomeones for 50 damage";
string a = "damage";
string b = "someone";
if (d.Contains(a) && d.Contains(b))
{
Response.Write(" " + d);
}
else
{
Response.Write("The required string not contain in d");
}
Just for completeness (and this is not at all recommended):
int length;
try
{
length = str.getBytes("UTF-16BE").length / 2
}
catch (UnsupportedEncodingException e)
{
throw new AssertionError("Cannot happen: UTF-16BE is always a supported encoding");
}
This works because a char
is a UTF-16 code unit, and str.length()
returns the number of such code units. Each UTF-16 code unit takes up 2 bytes, so we divide by 2. Additionally, there is no byte order mark written with UTF-16BE.
input type="range" min="0" max="50" value="0" style="margin-left: 6%;width: 88%;background-color: whitesmoke;"
above code changes range input style.....
A couple of problems, actually:
First, in that project you uploaded for us, the segue does not bear the "segue1" identifier:
no identifier
You should fill in that identifier if you haven't already.
Second, as you're pushing from table view to table view, you're calling initWithNibName to create a view controller. You really want to use instantiateViewControllerWithIdentifier.
A complete example for scripted pipepline:
stage('Build'){
withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
sh 'bash build.sh'
}
}
For example, I will create a table called users
as below and give a column named date
a default value NOW()
create table users_parent (
user_id varchar(50),
full_name varchar(240),
login_id_1 varchar(50),
date timestamp NOT NULL DEFAULT NOW()
);
Thanks
Sample 3 would be the worst performer out of them all because you are hitting up the database countless times for no apparent reason.
Loading the data into a temp table and then joining on that would be by far the fastest. After that the IN should work slightly faster than the group of ORs.
Use the split function.
static void Main(string[] args)
{
string s = "223232-1.jpg";
Console.WriteLine(s.Split('-')[0]);
s = "443-2.jpg";
Console.WriteLine(s.Split('-')[0]);
s = "34443553-5.jpg";
Console.WriteLine(s.Split('-')[0]);
Console.ReadKey();
}
If your string doesn't have a -
then you'll get the whole string.
Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.
Here is an example on how to parse a JSON string into a dynamic object:
string source = "{\r\n \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\", \r\n \"first_name\": \"Jerard\", \r\n \"last_name\": \"Jones\", \r\n \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n \"username\": \"Jerard.Jones\", \r\n \"gender\": \"female\", \r\n \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);
Happy coding!
The problem is that count is intended to count the indexes in an array, not the properties on an object, (unless it's a custom object that implements the Countable interface). Try casting the object, like below, as an array and seeing if that helps.
$total = count((array)$obj);
Simply casting an object as an array won't always work but being a simple stdClass object it should get the job done here.
Theory
When this issue is not caused by a bug in the application (e.g., duplicate class name):
This issue appears to present after a change is made to the application's project that results in a new build (e.g., code/reference/resource change). The issue appears to lie within the output of this new build: for various reasons Visual Studio is not replacing the entire contents of your application's obj/bin folders. This results in at least some of the contents of your application's bin folder being out of date.
When said issue occurs, clearing out the "Temporary ASP.NET Files" folder, alone, does not solve the problem. It cannot solve the problem, because the stale contents of your application's bin folder are copied back into the "Temporary ASP.NET Files" folder the next time your application is accessed, causing the issue to persist. The key is to remove all existing files and force Visual Studio to rebuild every object, so the next time your application is accessed the new bin files will be copied into the "Temporary ASP.NET Files" folder.
Solution
Explanation
Avoid using Activity implements OnMarkerClickListener, use a local OnMarkerClickListener
// Not a good idea
class MapActivity extends Activity implements OnMarkerClickListener {
}
You will need a map to lookup the original data model linked to the marker
private Map<Marker, Map<String, Object>> markers = new HashMap<>();
You will need a data model
private Map<String, Object> dataModel = new HashMap<>();
Put some data in the data model
dataModel.put("title", "My Spot");
dataModel.put("snipet", "This is my spot!");
dataModel.put("latitude", 20.0f);
dataModel.put("longitude", 100.0f);
When creating a new marker using a data model add both to the maker map
Marker marker = googleMap.addMarker(markerOptions);
markers.put(marker, dataModel);
For on click marker event, use a local OnMarkerClickListener:
@Override
public void onMapReady(GoogleMap googleMap) {
// grab for laters
this.googleMap = googleMap;
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Map dataModel = (Map)markers.get(marker);
String title = (String)dataModel.get("title");
markerOnClick(title);
return false;
}
});
mapView.onResume();
showMarkers();
ZoomAsync zoomAsync = new ZoomAsync();
zoomAsync.execute();
}
For displaying the info window retrieve the original data model from the marker map:
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Map dataModel = (Map)markers.get(marker);
String title = (String)dataModel.get("title");
infoWindowOnClick(title);
}
});
Actually the C++ standard (i.e. C++ 0x draft) says (tnx to @Xeo & @Ben Voigt for pointing that out to me):
23.2.4 Associative containers
5 For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. Keys in an associative container are immutable.
6 iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type.
So VC++ 2008 Dinkumware implementation is faulty.
Old answer:
You got that error because in certain implementations of the std lib the set::iterator
is the same as set::const_iterator
.
For example libstdc++ (shipped with g++) has it (see here for the entire source code):
typedef typename _Rep_type::const_iterator iterator;
typedef typename _Rep_type::const_iterator const_iterator;
And in SGI's docs it states:
iterator Container Iterator used to iterate through a set.
const_iterator Container Const iterator used to iterate through a set. (Iterator and const_iterator are the same type.)
On the other hand VC++ 2008 Express compiles your code without complaining that you're calling non const methods on set::iterator
s.
Alternative method with useEffect:
Parent:
const [refresh, doRefresh] = useState(0);
<Button onClick={() => doRefresh(prev => prev + 1)} />
<Children refresh={refresh} />
Children:
useEffect(() => {
performRefresh(); //children function of interest
}, [props.refresh]);
I don't think keyDown event is necessary in this case (please tell me why if I'm wrong). In my (non-jquery) script similar solution looks like that:
var _timer, _timeOut = 2000;
function _onKeyUp(e) {
clearTimeout(_timer);
if (e.keyCode == 13) { // close on ENTER key
_onCloseClick();
} else { // send xhr requests
_timer = window.setTimeout(function() {
_onInputChange();
}, _timeOut)
}
}
It's my first reply on Stack Overflow, so I hope this helps someone, someday:)
You can provide an explicit overload for the cast operator:
public static explicit operator maincs(sub1 val)
{
var ret = new maincs() { a = val.a, b = val.b, c = val.c };
return ret;
}
Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.
Another way you can do this is by using the substitute function. Substitute "(", ")" and "," with spaces. e.g.
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1, "(", " "), ")", " "), ",", " ")
Using http://blog.trolieb.com/trouble-multidimensional-arrays-swift/ as a start, I added generics to mine:
class Array2DTyped<T>{
var cols:Int, rows:Int
var matrix:[T]
init(cols:Int, rows:Int, defaultValue:T){
self.cols = cols
self.rows = rows
matrix = Array(count:cols*rows,repeatedValue:defaultValue)
}
subscript(col:Int, row:Int) -> T {
get{
return matrix[cols * row + col]
}
set{
matrix[cols * row + col] = newValue
}
}
func colCount() -> Int {
return self.cols
}
func rowCount() -> Int {
return self.rows
}
}
List<Integer>[] array;
array = new List<Integer>[10];
this the second case in @TofuBeer's answer is incorrect. because can't create arrays with generics. u can use:
List<List<Integer>> array = new ArrayList<>();
If you are using CodeIgniter and can't change php.ini, I added the following to the beginning of index.php:
date_default_timezone_set('GMT');
I faced to the same problem. I solved it by
HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath
and edit the default key with the output of
C:\> where python.exe
command.HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath\InstallGroup
and edit the default key with Python 3.4
Note: My python version is 3.4 and you need to replace 3.4 with your python version.
Normally you can find Registry entries for Python in HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\<version>
. You just need to copy those entries to HKEY_CURRENT_USER\Software\Python\PythonCore\<version>
Using aws s3 cp
from the AWS Command-Line Interface (CLI) will require the --recursive
parameter to copy multiple files.
aws s3 cp s3://myBucket/dir localdir --recursive
The aws s3 sync
command will, by default, copy a whole directory. It will only copy new/modified files.
aws s3 sync s3://mybucket/dir localdir
Just experiment to get the result you want.
Documentation:
As offer_date
is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date
SELECT
*
FROM
offers
WHERE
offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0
Also, by doing all the manipulation on the create_date
you only do the processing on one value.
Additionally, had you manipulated the offer_date
you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.
This should also work (even in SQL-Server 2005):
SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
AND Created < DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))
You can't use add_timestamps and null:false if you have existing records, so here is the solution :
def change
add_timestamps(:buttons, null: true)
Button.find_each { |b| b.update(created_at: Time.zone.now, updated_at: Time.zone.now) }
change_column_null(:buttons, :created_at, false)
change_column_null(:buttons, :updated_at, false)
end
Use the re.escape()
function for this:
escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.
def simplistic_plural(word, text):
word_or_plural = re.escape(word) + 's?'
return re.match(word_or_plural, text)
Use int()
on a boolean test:
x = int(x == 'true')
int()
turns the boolean into 1
or 0
. Note that any value not equal to 'true'
will result in 0
being returned.
You have an error in your code. This line:
for(int i=0;i<v[n];i++)
should be
for(int i=0;i<n;i++)
because you want to search n
places in your vector, not v[n]
places (which wouldn't mean anything)
What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.
A constant reference/ Reference to a constant is denoted by:
int const &i = j; //or Alternatively
const int &i = j;
i = 1; //Compilation Error
It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1
) of variable j
through const reference, i
will results in error:
assignment of read-only reference ‘i’
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99;
Doesn't change the reference, it assigns the value of the type to which the reference refers. References cannot be made to refer any other variable than the one they are bound to at Initialization.
First statement assigns the value y
to i
Second statement assigns the value 99
to i
Convert JavaScript object to json data
$("form").submit(function(event){
event.preventDefault();
var formData = $("form").serializeArray(); // Create array of object
var jsonConvertedData = JSON.stringify(formData); // Convert to json
consol.log(jsonConvertedData);
});
You can validate json data using http://jsonlint.com
You can define first the width of the element as 0, floating right, and then on the event that you are about to show it.. it would be like
$('#the_element_to_slide_from_right_left').animate({ width:'your desired width' }, 600);
Simple as that.
a = 1.0123456789
dec = 3 # keep this many decimals
p = 10 # raise 10 to this power
a * 10 ** p // 10 ** (p - dec) / 10 ** dec
>>> 1.012
As of PHP 5.6 @$filePath
will not work in CURLOPT_POSTFIELDS
without CURLOPT_SAFE_UPLOAD
being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.
$fields = [
'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);
Easily achieved with the css property user-select set to all. Like this:
div.anyClass {_x000D_
user-select: all;_x000D_
}
_x000D_
Doing type('')
is effectively equivalent to str
and types.StringType
so type('') == str == types.StringType
will evaluate to "True
"
Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode)
or assert isinstance(obj, basestring)
, the latter of which was suggested in the comments by 007Brendan and is probably preferred.
isinstance()
is useful if you want to ask whether an object is an instance of a class, e.g:
class MyClass: pass
print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception
But for basic types, e.g. str
, unicode
, int
, float
, long
etc asking type(var) == TYPE
will work OK.
So if you want to build your SVG stuff piece by piece in JS, then don't just use createElement()
, those won't draw, use this instead:
var ci = document.createElementNS("http://www.w3.org/2000/svg", "circle");
If str.title() doesn't work for you, do the capitalization yourself.
One-liner:
>>> ' '.join([s[0].upper() + s[1:] for s in "they're bill's friends from the UK".split(' ')])
"They're Bill's Friends From The UK"
Clear example:
input = "they're bill's friends from the UK"
words = input.split(' ')
capitalized_words = []
for word in words:
title_case_word = word[0].upper() + word[1:]
capitalized_words.append(title_case_word)
output = ' '.join(capitalized_words)
I would consinder enclosing that select block within a div block and setting the border property like this:
<div style="border: 2px solid blue;">_x000D_
<select style="width: 100%;">_x000D_
<option value="Sal">Sal</option>_x000D_
<option value="Awesome">Awesome!</option>_x000D_
</select>_x000D_
</div>
_x000D_
You should be able to play with that to accomplish what you need.
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
If it's the case that the property is not set:
db.states.find({"cities.name": {"$exists": false}})
I've tested the above with a collection created with these two inserts:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
This worked for me:
$('input[name="sort_order"]').attr('value','XXX');
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
function Once() {
return this.constructor.instance || (this.constructor.instance = this);
}
function Application(name) {
let app = Once.call(this);
app.name = name;
return app;
}
If you are into classes:
class Once {
constructor() {
return this.constructor.instance || (this.constructor.instance = this);
}
}
class Application extends Once {
constructor(name) {
super();
this.name = name;
}
}
Test:
console.log(new Once() === new Once());
let app1 = new Application('Foobar');
let app2 = new Application('Barfoo');
console.log(app1 === app2);
console.log(app1.name); // Barfoo
You can use the --table
or -t
option, which will output a nice looking set of results
echo 'desc table_name' | mysql -uroot database -t
or some other method to pass a query to mysql, like:
mysql -uroot table_name --table < /tmp/somequery.sql
output:
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(30) | NO | | NULL | |
| email | varchar(75) | NO | | NULL | |
| password | varchar(128) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| last_login | datetime | NO | | NULL | |
| date_joined | datetime | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
if (set no count== off)
{ then it will keep data of how many records affected so reduce performance } else { it will not track the record of changes hence improve perfomace } }
I bet for sure, that this is because you didn't close the running instance of the program before trying to re-compile it.
Generally, ld.exe
returns 1 when it can't access required files. This usually includes
Access denied
)The program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld
to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible.
Now we get to the third point. Note that Windows not allow writing to a file when it's in use, so the running instance of your program prevents ld.exe
from writing the new linked program to it.
So next time be sure to close running programs before compiling.
You need to use some kind of file-transfer protocol (ftp, scp, etc), putty can't send remote files back to your computer. I use Win-SCP, which has a straightforward gui. Select SCP and you should be able to log in with the same ssh credentials and on the same port (probably 22) that you use with putty.
Change:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
To:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))
By default, most of distribution uses Ctrl+F12.
Some OS distribution (in my case Xubuntu) which uses Xcfe, overrides Ctrl+F12 to "Workspace 12" switch.
It's necessary because, more or less, when we import a project from git, it's not a maven project, so the maven dependencies are not in the build path.
Here's what I have done to turn a general project to a maven project.
general project-->java project right click the project, properties->project facets, click "java". This step will turn a general project into java project.
java project --> maven project right click project, configure-->convert to maven project At this moment, maven dependencies lib are still not in the build path. project properties, build path, add library, add maven dependencies lib
And wait a few seconds, when the dependencies are loaded, the project is ready!
Similar Question Here
Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.
The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.
from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))
# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111,
# variance=572.3611111111111, skewness=1.7791785448425341,
# kurtosis=1.9422716419666397)
putImageData
is probably faster than fillRect
natively. I think this because the fifth parameter can have different ways to be assigned (the rectangle color), using a string that must be interpreted.
Suppose you're doing that:
context.fillRect(x, y, 1, 1, "#fff")
context.fillRect(x, y, 1, 1, "rgba(255, 255, 255, 0.5)")`
context.fillRect(x, y, 1, 1, "rgb(255,255,255)")`
context.fillRect(x, y, 1, 1, "blue")`
So, the line
context.fillRect(x, y, 1, 1, "rgba(255, 255, 255, 0.5)")`
is the most heavy between all. The fifth argument in the fillRect
call is a bit longer string.
My computer had the wrong locale set.
I first did
>>> import locale
>>> locale.getpreferredencoding(False)
'ANSI_X3.4-1968'
locale.getpreferredencoding(False)
is the function called by open()
when you don't provide an encoding. The output should be 'UTF-8'
, but in this case it's some variant of ASCII.
Then I ran the bash command locale
and got this output
$ locale
LANG=
LANGUAGE=
LC_CTYPE="POSIX"
LC_NUMERIC="POSIX"
LC_TIME="POSIX"
LC_COLLATE="POSIX"
LC_MONETARY="POSIX"
LC_MESSAGES="POSIX"
LC_PAPER="POSIX"
LC_NAME="POSIX"
LC_ADDRESS="POSIX"
LC_TELEPHONE="POSIX"
LC_MEASUREMENT="POSIX"
LC_IDENTIFICATION="POSIX"
LC_ALL=
So, I was using the default Ubuntu locale, which causes Python to open files as ASCII instead of UTF-8. I had to set my locale to en_US.UTF-8
sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo dpkg-reconfigure locales
If you can't change the locale system wide, you can invoke all your Python code like this:
PYTHONIOENCODING="UTF-8" python3 ./path/to/your/script.py
or do
export PYTHONIOENCODING="UTF-8"
to set it in the shell you run that in.
declare
x number;
begin
x := myfunc(myargs);
end;
Alternatively:
select myfunc(myargs) from dual;
The compilation problem only occurs for me (gcc 4.3, ubuntu 8.10) if the three variables are global. The problem is that C doesn't work like a script languages, so you cannot take for granted that the initialization of u and t occur after the one of s. That's why you get a compilation error. Now, you cannot initialize t and y they way you did it before, that's why you will need a char*. The code that do the work is the following:
#include <stdio.h>
#include <stdlib.h>
#define STR "ABCD"
const char s[] = STR;
char* t;
char* u;
void init(){
t = malloc(sizeof(STR)-1);
t[0] = s[0];
t[1] = s[1];
t[2] = s[2];
t[3] = s[3];
u = malloc(sizeof(STR)-1);
u[0] = s[3];
u[1] = s[2];
u[2] = s[1];
u[3] = s[0];
}
int main(void) {
init();
puts(t);
puts(u);
return EXIT_SUCCESS;
}
This is for String and CSV file for swift 4.2 at 20181206 1610
var dataArray : [[String]] = []
let path = Bundle.main.path(forResource: "csvfilename", ofType: "csv")
let url = URL(fileURLWithPath: path!)
do {
let data = try Data(contentsOf: url)
let content = String(data: data, encoding: .utf8)
let parsedCSV = content?.components(separatedBy: "\r\n").map{ $0.components(separatedBy: ";") }
for line in parsedCSV!
{
dataArray.append(line)
}
}
catch let jsonErr {
print("\n Error read CSV file: \n ", jsonErr)
}
print("\n MohNada 20181206 1610 - The final result is \(dataArray) \n ")
You can use the HTML5 input of type number
It does not accept any characters in its declaration
<input type="number" [(model)]='myvar' min=0 max=100 step=5 />
Here is an example of its usage with angular 2 [(model)]
If your array of numbers always is starting with 1 and ending with X then you could use the following formula: sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
The onclick
property is all lower-case, and accepts a function, not a string.
document.getElementById("test").onclick = foo2;
See also addEventListener
.
Character.getNumericValue(c)
The java.lang.Character.getNumericValue(char ch)
returns the int
value that the specified Unicode character represents. For example, the character '\u216C'
(the roman numeral fifty) will return an int with a value of 50.
The letters A-Z in their uppercase ('\u0041' through '\u005A')
, lowercase ('\u0061' through '\u007A')
, and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A')
forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.
This method returns the numeric value of the character, as a nonnegative int value;
-2 if the character has a numeric value that is not a nonnegative integer;
-1 if the character has no numeric value.
And here is the link.
Use the Instr function
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
will return 15 in pos
If not found it will return 0
If you need to find the comma with an excel formula you can use the =FIND(",";A1)
function.
Notice that if you want to use Instr
to find the position of a string case-insensitive use the third parameter of Instr and give it the const vbTextCompare
(or just 1 for die-hards).
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
will give you a value of 14.
Note that you have to specify the start position in this case as stated in the specification I linked: The start argument is required if compare is specified.
To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to "www.example.com/PAGE_NAME_HERE"
, but suddenly a third party application (or something else) sends the user to "www.supposedlymaliciouswebsite.com/PAGE_HERE"
, then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings.
You can use this and it should be working --> You must use toList
before making the new list using select:
db.Products
.where(x=>x.CategoryID == categoryID).ToList()
.select(x=>new Product { Name = p.Name}).ToList();
You need to set android:exported="true"
in your AndroidManifest.xml
file where you declare this Activity
:
<activity
android:name="com.example.lib.MainActivity"
android:label="LibMain"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" >
</action>
</intent-filter>
</activity>
For Windows, try:
NBTSTAT -A 10.100.3.104
or
ping -a 10.100.3.104
For Linux, try:
nmblookup -A 10.100.3.104
They are almost same.
If you started a project requiring the #include "stdafx.h"
line, put it first.
I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.
The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:
public static byte[] downloadFile(URL url)
{
try {
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), baos);
return baos.toByteArray();
}
catch (IOException e)
{
// Log error and return null, some default or throw a runtime exception
}
}
You have:
foreach (var category in Model.Categories)
and then
@foreach (var product in Model)
Based on that view and model it seems that Model
is of type Product
if yes then the second foreach
is not valid. Actually the first one could be the one that is invalid if you return a collection of Product
.
UPDATE:
You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?
I'm surprised your code compiles when you said you are returning a model of Product
type. Here's how you can do it:
@foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in category.Products)
{
<li>
put the rest of your code
</li>
}
</ul>
</div>
}
That suggest that instead of returning a Product
, you return a collection of Category
with Products. Something like this in EF:
// I am typing it here directly
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
Perfectly working method to convert File URI into String filePath
Maybe like this:
list('abcdefgh') # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design
Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
If a dedicated script seems like too much overhead, you can spawn separate processes explicitly with sh -c
. For example:
CMD sh -c 'mini_httpd -C /my/config -D &' \
&& ./content_computing_loop
This will do:
▢
It is ?
(known as a "WHITE SQUARE WITH ROUNDED CORNERS" on fileformat.info)
Or
◻
as ?
(known as a "WHITE MEDIUM SQUARE" on the same website)
Two with shadow:
❏
❑
as ? and ? . The difference between them is the shadows' shape. You can see it if you zoom in or if you print it out. (They are known as "LOWER RIGHT DROP-SHADOWED WHITE SQUARE" and "LOWER RIGHT SHADOWED WHITE SQUARE", respectively).
You can also use
☐
which is ?
(known as a "BALLOT BOX").
A sample is at http://jsfiddle.net/S2QCt/267/
(a note: on the Mac, ▢
is quite nice, because it is bigger and somewhat more elegant than ☐
On Windows, ☐
looks more standard, while ▢
is somewhat small.)
if you have bash, you can use extended globbing
shopt -s extglob
shopt -s nullglob
shopt -s nocaseglob
for file in +([0-9])_+([a-z])_+([a-z0-9]).jpg
do
IFS="_"
set -- $file
echo "This is your captured output : $2"
done
or
ls +([0-9])_+([a-z])_+([a-z0-9]).jpg | while read file
do
IFS="_"
set -- $file
echo "This is your captured output : $2"
done
Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.
The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g"
, containing way too many slashes.
Since sed
can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:
replacement="/my/path"
sed --expression "s@pattern@$replacement@"
Note that this is not bullet proof: if the replacement string later contains @
it will break for the same reason, and any backslash sequences like \1
will still be interpreted according to sed
rules. Using |
as a delimiter is also a nice option as it is similar in readability to /
.
decimal pay = 1.994444M;
Math.Round(pay , 2);
You're targeting the wrong item with that jQuery selector. The name
of your search bar is searchBar
, not the id
. What you want to use is $('#main_search').val('hi')
.
There are several scenarios to consider. First of all, you need to check the type of your object. You can simply call GetType() for this. If the type does not implement IDynamicMetaObjectProvider, then you can use reflection same as for any other object. Something like:
var propertyInfo = test.GetType().GetProperties();
However, for IDynamicMetaObjectProvider implementations, the simple reflection doesn't work. Basically, you need to know more about this object. If it is ExpandoObject (which is one of the IDynamicMetaObjectProvider implementations), you can use the answer provided by itowlson. ExpandoObject stores its properties in a dictionary and you can simply cast your dynamic object to a dictionary.
If it's DynamicObject (another IDynamicMetaObjectProvider implementation), then you need to use whatever methods this DynamicObject exposes. DynamicObject isn't required to actually "store" its list of properties anywhere. For example, it might do something like this (I'm reusing an example from my blog post):
public class SampleObject : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = binder.Name;
return true;
}
}
In this case, whenever you try to access a property (with any given name), the object simply returns the name of the property as a string.
dynamic obj = new SampleObject();
Console.WriteLine(obj.SampleProperty);
//Prints "SampleProperty".
So, you don't have anything to reflect over - this object doesn't have any properties, and at the same time all valid property names will work.
I'd say for IDynamicMetaObjectProvider implementations, you need to filter on known implementations where you can get a list of properties, such as ExpandoObject, and ignore (or throw an exception) for the rest.
There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time.
Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies.
unbrew () {
local formula
for formula in "$@"; do
brew deps "$formula" |
xargs brew uninstall --ignore-dependencies --force
brew uninstall --force "$formula"
done
brew missing | cut -f2 -d: | sort -u | xargs brew install
}
It was tested on Homebrew 1.7.4.
This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim).
simplexml_load_file()
interprets an XML file (either a file on your disk or a URL) into an object. What you have in $feed
is a string.
You have two options:
Use file_get_contents()
to get the XML feed as a string, and use e simplexml_load_string()
:
$feed = file_get_contents('...');
$items = simplexml_load_string($feed);
Load the XML feed directly using simplexml_load_file()
:
$items = simplexml_load_file('...');
By default know there is not a great way. Awhile back I got frustrated with this and wrote a little utility class that helped out a bit and made the syntax a bit cleaner. Essentially it turns the code into
TypeSwitcher.Do(clause[0],
TypeSwitch.Case<int>(x => ...), // x is an int
TypeSwitch.Case<decimal>(d => ...), // d is a decimal
TypeSwitch.Case<string>(s => ...)); // s is a string
Full blog post and details on the implementation are available here
To get dynamic tagging to work with ajax, here's what I did.
Select2 version 3.5
This is easy in version 3.5 because it offers the createSearchChoice
hook. It even works for multiple select, as long as multiple: true
and tags: true
are set.
HTML
<input type="hidden" name="locations" value="Whistler, BC" />
JS
$('input[name="locations"]').select2({
tags: true,
multiple: true,
createSearchChoice: function(term, data) {
if (!data.length)
return { id: term, text: term };
},
ajax: {
url: '/api/v1.1/locations',
dataType: 'json'
}
});
The idea here is to use select2's createSearchChoice
hook which passes you both the term
that the user entered and the ajax response (as data
). If ajax returns an empty list, then tell select2 to offer the user-entered term
as an option.
Demo: https://johnny.netlify.com/select2-examples/version3
Select2 version 4.X
Version 4.X doesn't have a createSearchChoice
hook anymore, but here's how I did the same thing.
HTML
<select name="locations" multiple>
<option value="Whistler, BC" selected>Whistler, BC</option>
</select>
JS
$('select[name="locations"]').select2({
ajax: {
url: '/api/v1.1/locations',
dataType: 'json',
data: function(params) {
this.data('term', params.term);
return params;
},
processResults: function(data) {
if (data.length)
return {
results: data
};
else
return {
results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
};
}
}
});
The ideas is to stash the term that the user typed into jQuery's data store inside select2's data
hook. Then in select2's processResults
hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.
Your student.h file only forward declares a struct named "Student", it does not define one. This is sufficient if you only refer to it through reference or pointer. However, as soon as you try to use it (including creating one) you will need the full definition of the structure.
In short, move your struct Student { ... }; into the .h file and use the .cpp file for implementation of member functions (which it has none so you don't need a .cpp file).