I know it's a bit late but, Microsoft has made their Xaml.Behaviors open source and it's now much easier to use interactivity with just one namespace.
Then use it like this,
<Button Width="150" Style="{DynamicResource MaterialDesignRaisedDarkButton}">
<behaviours:Interaction.Triggers>
<behaviours:EventTrigger EventName="Click">
<behaviours:InvokeCommandAction Command="{Binding OpenCommand}" PassEventArgsToCommand="True"/>
</behaviours:EventTrigger>
</behaviours:Interaction.Triggers>
Open
</Button>
PassEventArgsToCommand="True" should be set as True and the RelayCommand that you implement can take RoutedEventArgs or objects as template. If you are using object as the parameter type just cast it to the appropriate event type.
The command will look something like this,
OpenCommand = new RelayCommand<object>(OnOpenClicked, (o) => { return true; });
The command method will look something like this,
private void OnOpenClicked(object parameter)
{
Logger.Info(parameter?.GetType().Name);
}
The 'parameter' will be the Routed event object.
And the log incase you are curious,
2020-12-15 11:40:36.3600|INFO|MyApplication.ViewModels.MainWindowViewModel|RoutedEventArgs
As you can see the TypeName logged is RoutedEventArgs
RelayCommand impelmentation can be found here.
PS : You can bind to any event of any control. Like Closing event of Window and you will get the corresponding events.
//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));
Manage multiple java version in MAC using jenv
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew install jenv
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
brew tap homebrew/cask-versions
brew search java
brew install cask java6
jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Note:- if you get error like “”ln: /Users//.jenv/versions/oracle64-1.8.0.231: No such file or directory, then run following:-
mkdir -p /Users//.jenv/versions/oracle64-1.8.0.231
jenv rehash
jenv versions
jenv global oracle64-1.8.0.231
jenv local oracle64-1.6.0.65
jenv exec bash
echo $JAVA_HOME
Try this to convert string to uri
String mystring="Hello"
Uri myUri = Uri.parse(mystring);
Uri to String
Uri uri;
String uri_to_string;
uri_to_string= uri.toString();
Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!
for (int i = 0; i < 3; i++) {
LinearLayout linearDummy = new LinearLayout(getActivity());
linearDummy.setOrientation(LinearLayout.VERTICAL);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();
} else {
linearDummy.setId(View.generateViewId());
}
fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();
xNumberLinear.addView(linearDummy);
}
Try to go to App_Data folder property and add ASPNET user with read and write privileges
Ref:
How to assign correct permissions to App_Data folder of WebMail Pro ASP.NET
Permissions on APP_DATA Folder
ASP/ASP.NET Best way to handle write permissions?
If it does not solve your problem then check whether your XML files are not open by another thread using these configuration files.. and provide some more details if still persists.
There's no notion of "this class must have these functions" (that is, no interfaces per se), because:
Instead, JavaScript uses what's called duck typing. (If it walks like a duck, and quacks like a duck, as far as JS cares, it's a duck.) If your object has quack(), walk(), and fly() methods, code can use it wherever it expects an object that can walk, quack, and fly, without requiring the implementation of some "Duckable" interface. The interface is exactly the set of functions that the code uses (and the return values from those functions), and with duck typing, you get that for free.
Now, that's not to say your code won't fail halfway through, if you try to call some_dog.quack()
; you'll get a TypeError. Frankly, if you're telling dogs to quack, you have slightly bigger problems; duck typing works best when you keep all your ducks in a row, so to speak, and aren't letting dogs and ducks mingle together unless you're treating them as generic animals. In other words, even though the interface is fluid, it's still there; it's often an error to pass a dog to code that expects it to quack and fly in the first place.
But if you're sure you're doing the right thing, you can work around the quacking-dog problem by testing for the existence of a particular method before trying to use it. Something like
if (typeof(someObject.quack) == "function")
{
// This thing can quack
}
So you can check for all the methods you can use before you use them. The syntax is kind of ugly, though. There's a slightly prettier way:
Object.prototype.can = function(methodName)
{
return ((typeof this[methodName]) == "function");
};
if (someObject.can("quack"))
{
someObject.quack();
}
This is standard JavaScript, so it should work in any JS interpreter worth using. It has the added benefit of reading like English.
For modern browsers (that is, pretty much any browser other than IE 6-8), there's even a way to keep the property from showing up in for...in
:
Object.defineProperty(Object.prototype, 'can', {
enumerable: false,
value: function(method) {
return (typeof this[method] === 'function');
}
}
The problem is that IE7 objects don't have .defineProperty
at all, and in IE8, it allegedly only works on host objects (that is, DOM elements and such). If compatibility is an issue, you can't use .defineProperty
. (I won't even mention IE6, because it's rather irrelevant anymore outside of China.)
Another issue is that some coding styles like to assume that everyone writes bad code, and prohibit modifying Object.prototype
in case someone wants to blindly use for...in
. If you care about that, or are using (IMO broken) code that does, try a slightly different version:
function can(obj, methodName)
{
return ((typeof obj[methodName]) == "function");
}
if (can(someObject, "quack"))
{
someObject.quack();
}
Use the CLIM function (equivalent to CAXIS function in MATLAB):
plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4) # identical to caxis([-4,4]) in MATLAB
plt.show()
It depends a bit on context. Cardinality means the number of something but it gets used in a variety of contexts.
PERSON
table, for example, GENDER
is likely to be a very low cardinality column (there are probably only two values in GENDER
) while PERSON_ID
is likely to be a very high cardinality column (every row will have a different value).There are probably other situations where people talk about cardinality using a different context and mean something else.
Updating the ~/.profile
or ~/.bash_profile
does not work sometimes. I just deleted JDK 6 and source
d .bash_profile
.
Try running this:
sudo rm -rd jdk1.6.0_* #it may not let you delete without sudo
Then, modify/add your JAVA_HOME and PATH variables.
source ~/.bash_profile #assuming you've updated $JAVA_HOME and $PATH
brew install ffmpeg
will install what you need and all the dependencies if you are on a Mac.
Section 6.5.8.6 of the C standard says:
Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.
ReSharper does a great job of finding unused code.
In the VS IDE, you can right click on the definition and choose 'Find All References', although this only works at the solution level.
Or, using your EOF markers, you need to quote the initial marker so expansion won't be done:
#-----v---v------
cat <<'EOF' >> brightup.sh
#!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
curr=$((curr+406));
echo $curr > /sys/class/backlight/intel_backlight/brightness;
fi
EOF
IHTH
You can call more of 1 function filters in the same ng-repeat filter
<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
Quite easy... You're doing it wrong, because by that event the control is not there:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
}
}
That is, it will only be valid for a DataRow
(the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS")
will only find the control that you want.
npm install -d --save
worked for me. -d
flag command force npm to install your dependencies and --save
will save the all updated dependencies in your package.json
Submit
is null
because it is not part of activity_main.xml
When you call findViewById
inside an Activity
, it is going to look for a View
inside your Activity's layout.
try this instead :
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Another thing : you use
android:layout_below="@+id/LoginTitle"
but what you want is probably
android:layout_below="@id/LoginTitle"
See this question about the difference between @id
and @+id
.
Try:
pwd=`pwd`
or
pwd=$(pwd)
Notice no spaces after the equals sign.
Also as Mr. Weiss points out; you don't assign to $pwd
, you assign to pwd
.
From w3 schools:
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<img src="/pathtoimage" class="tooltiptext">
</div>
Sounds like about what you want
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it.
<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>
You can pass the JSON string output by json_encode to a JavaScript variable as follows:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:
<?php
echo json_encode($ar, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
Associative Array Example:
<?php
$book = array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan",
"edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan",
"edition": 6
}; */
alert(book.title);
</script>
Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format.
You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title'].
here you can find more information and details.
Define Methods like this and you will get the help you need.
/// <summary>
/// Adds two numbers and returns the result
/// </summary>
/// <param name="first">first number to add</param>
/// <param name="second">second number to </param>
/// <returns></returns>
private int Add(int first, int second)
{
return first + second;
}
Sometimes you need to use double brackets, otherwise you get an error like too many arguments
if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
then
fi
Gradle can work with the 18.0.+ notation, it however now depends on the new support repository which is now bundled with the SDK.
Open the SDK manager and immediately under Extras the first option is "Android Support Repository" and install it
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('your View Name');
Depending on your browser, you may access to your local files. But this may not work for all the users of your app.
To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Once your file is loaded, you can retrieve the data using:
var jsonData = JSON.parse(theTextContentOfMyFile);
To get the smallest or largest item in a list, use the built-in min and max functions:
lo = min(L)
hi = max(L)
As with sort, you can pass in a "key" argument that is used to map the list items before they are compared:
lo = min(L, key=int)
hi = max(L, key=int)
http://effbot.org/zone/python-list.htm
Looks like you could use the max function if you map it correctly for strings and use that as the comparison. I would recommend just finding the max once though of course, not for each element in the list.
-- The way to go these days --
Use SipHash. For your own protection.
-- Old and Dangerous --
unsigned int RSHash(const std::string& str)
{
unsigned int b = 378551;
unsigned int a = 63689;
unsigned int hash = 0;
for(std::size_t i = 0; i < str.length(); i++)
{
hash = hash * a + str[i];
a = a * b;
}
return (hash & 0x7FFFFFFF);
}
unsigned int JSHash(const std::string& str)
{
unsigned int hash = 1315423911;
for(std::size_t i = 0; i < str.length(); i++)
{
hash ^= ((hash << 5) + str[i] + (hash >> 2));
}
return (hash & 0x7FFFFFFF);
}
Ask google for "general purpose hash function"
Easiest way would probably be with jQuery, as follows:
$(document).ready(function(){
$("#_1234").attr("checked","checked");
})
This adds a new attribute "checked" (which in HTML does not need a value). Just remember to include the jQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.
Also, related question
Have you looked at angular-ui bootstrap? There's a Dialog (ui.bootstrap.dialog) directive that works quite well. You can close the dialog during the call back the angular way (per the example):
$scope.close = function(result){
dialog.close(result);
};
Update:
The directive has since been renamed Modal.
I often have this problem with sequences (as opposed to discrete values). If I have a sequence of ints, and I want to SUM them, when the list is empty I'll receive the error "InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.".
I find I can solve this by casting the sequence to a nullable type. SUM and the other aggregate operators don't throw this error if a sequence of nullable types is empty.
So for example something like this
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => x.AnIntegerValue);
becomes
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => (int?) x.AnIntegerValue);
The second one will return 0 when no rows match the where clause. (the first one throws an exception when no rows match).
I faced similar issue, with RelativeLayout as the root element for each row in the recyclerview.
To solve the issue, find the xml file that holds each row and make sure that the root element's height is wrap_content
NOT match_parent
.
For me it turned out that I had a @JsonManagedReferece
in one entity without a @JsonBackReference
in the other referenced entity. This caused the marshaller to throw an error.
NoneType
is the type for the None
object, which is an object that indicates no value. None
is the return value of functions that "don't return anything". It is also a common default return value for functions that search for something and may or may not find it; for example, it's returned by re.search
when the regex doesn't match, or dict.get
when the key has no entry in the dict. You cannot add None
to strings or other objects.
One of your variables is None
, not a string. Maybe you forgot to return
in one of your functions, or maybe the user didn't provide a command-line option and optparse
gave you None
for that option's value. When you try to add None
to a string, you get that exception:
send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)
One of group
or SNMPGROUPCMD
or V3PRIVCMD
has None
as its value.
In your code:
var obj = {
myProp: string;
};
You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):
var string = 'A string';
var obj = {
property: string
};
However, what you want is that the object literal is typed. This can be achieved in various ways:
Interface:
interface myObj {
property: string;
}
var obj: myObj = { property: "My string" };
Type alias:
type myObjType = {
property: string
};
var obj: myObjType = { property: "My string" };
Object type literal:
var obj: { property: string; } = { property: "Mystring" };
ENABLEDELAYEDEXPANSION
is a parameter passed to the SETLOCAL
command (look at setlocal /?
)
Its effect lives for the duration of the script, or an ENDLOCAL
:
When the end of a batch script is reached, an implied
ENDLOCAL
is executed for any outstandingSETLOCAL
commands issued by that batch script.
In particular, this means that if you use SETLOCAL ENABLEDELAYEDEXPANSION
in a script, any environment variable changes are lost at the end of it unless you take special measures.
CSS support has binding to javascript, as a side note.
if (CSS.supports("( -moz-user-select:unset )")) {_x000D_
console.log("FIREFOX!!!")_x000D_
}
_x000D_
https://developer.mozilla.org/en-US/docs/Web/CSS/Mozilla_Extensions
Just doing like @Kjartan.
Steps are as follows:
Right click your C# project name in Visual Studio's "Solution Explorer";
Then, select "add -> Reference -> COM -> Type Libraries " in order;
Find the "Microsoft Office 16.0 Object Library", and add it to reference (Note: the version number may vary with the OFFICE you have installed);
After doing this, you will see "Microsoft.Office.Interop.Word" under the "Reference" item in your project.
NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode()
method. You can use it to control how rounding or truncation is applied during formatting.
Truncate String
public static string TruncateText(string strText, int intLength)
{
if (!(string.IsNullOrEmpty(strText)))
{
// split the text.
var words = strText.Split(' ');
// calculate the number of words
// based on the provided characters length
// use an average of 7.6 chars per word.
int wordLength = Convert.ToInt32(Math.Ceiling(intLength / 7.6));
// if the text is shorter than the length,
// display the text without changing it.
if (words.Length <= wordLength)
return strText.Trim();
// put together a shorter text
// based on the number of words
return string.Join(" ", words.Take(wordLength)) + " ...".Trim();
}
else
{
return "";
}
}
Try to check the limits of your SQL database. Maybe you'r exceeding the field limit for this row.
Specific Solution to the example problem:-
Try [A-Z]*123$
will match 123
, AAA123
, ASDFRRF123
. In case you need at least a character before 123
use [A-Z]+123$
.
General Solution to the question (How to match "any character" in the regular expression):
[\w|\W]{min_char_to_match,}
.[\S]{min_char_to_match,}
.import inspect
def func(a,b,c=5):
pass
inspect.getargspec(func) # inspect.signature(func) in Python 3
(['a', 'b', 'c'], None, None, (5,))
Simply running
sc.getConf().getAll()
should give you a list with all settings.
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
Pretty simple on a per database level
Use DatabaseName
Select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'ColName'
Normally, you want maximum compatibility with EditText
's normal behaviour.
So you should not use android:focusable="false"
as, yes, the view will just not be focusable anymore which looks bad. The background drawable will not show its "pressed" state anymore, for example.
What you should do instead is the following:
myEditText.setInputType(InputType.TYPE_NULL);
myEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// showMyDialog();
}
});
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// showMyDialog();
}
}
});
By setting the input type to TYPE_NULL
, you prevent the software keyboard from popping up.
By setting the OnClickListener
and OnFocusChangeListener
, you make sure that your dialog will always open when the user clicks into the EditText
field, both when it gains focus (first click) and on subsequent clicks.
Just setting android:inputType="none"
or setInputType(InputType.TYPE_NULL)
is not always enough. For some devices, you should set android:editable="false"
in XML as well, although it is deprecated. If it does not work anymore, it will just be ignored (as all XML attributes that are not supported).
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
in some cases where pywin32 is not the direct reference and other libraries require pywin32-ctypes to be installed; causes the "ImportError: No module named win32com" when application bundled with pyinstaller.
running following command solves on python 3.7 - pyinstaller 3.6
pip install pywin32==227
You could just comment the maven dependency for a while:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
</dependencies>
It worked fine for me
Disabling it from
application.properties
is deprecated for Spring Boot 2.0
i just place one image in " d drive-->Data-->IMG". The image name is x.jpg
:
And on c# code type
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));
(please put double slash in between path)
this.Background = myBrush;
finally i got the background..
Joseph:
spinner.setOnItemSelectedListener(this)
should be below
Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1);
on onCreate
This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)
Sub Create_new_file()
Application.DisplayAlerts = False
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String
Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook
For Each sh In wb.Worksheets
pname = sh.Name
If sh.Visible = True Then
sh.Copy After:=wbNew.Sheets(Sheets.Count)
wbNew.Sheets(Sheets.Count).Cells.ClearContents
wbNew.Sheets(Sheets.Count).Cells.ClearFormats
wb.Sheets(sh.Name).Activate
Range(sh.PageSetup.PrintArea).Select
Selection.Copy
wbNew.Sheets(pname).Activate
Range("A1").Select
With Selection
.PasteSpecial (xlValues)
.PasteSpecial (xlFormats)
.PasteSpecial (xlPasteColumnWidths)
End With
ActiveSheet.Name = pname
End If
Next
wbNew.Sheets("Hoja1").Delete
Application.DisplayAlerts = True
End Sub
What you put inside the </dependencies>
tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.
However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>
. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement>
tag.
You can also use the </dependencyManagement>
to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).
static value may exists into a function and can be used in different forms and can have different value in the program. Also during program after increment of decrement their value may change but const in constant during the whole program.
The maximum length until "it gets sluggish" is totally dependent on your target machine and your actual code, so you'll need to test on that (those) platform(s) to see what is acceptable.
However, the maximum length of an array according to the ECMA-262 5th Edition specification is bound by an unsigned 32-bit integer due to the ToUint32 abstract operation, so the longest possible array could have 232-1 = 4,294,967,295 = 4.29 billion elements.
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
Putty doesn't use openssh key files - there is a utility in putty suite to convert them.
edit: it is called puttygen
Your struct can have methods and properties... why not try
public struct MyStruct {
public string s;
public int length { return s.Length; }
}
Correction @Guffa's answer shows that it is possible... more info here: http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx
Create a Jenkins Job that runs on Master:
java -jar "%JENKINS_HOME%/war/WEB-INF/jenkins-cli.jar" -s "%JENKINS_URL%" safe-restart
Answering to the very first post of this topic...
Symptom : Some app don't install, saying there is no space and in reallity there is plenty of space free on both internal and external storage !!! Solution: disable external installation by default.
Setting external install by defaut with this:
adb shell pm set-install-location 2
Makes install impossible on many apps that can't install externally (such as adblock + or so)
Then the solution is
adb shell pm set-install-location 0
Or
adb shell pm set-install-location 1
0: auto (if one is full - or irrelevant !!! - it select the other)
1: internal
2: external
df.to_html()
has a columns parameter.
Just pass the columns into the to_html()
method.
df.to_html(columns=['A','B','C','D','E','F','G'])
If you would like to remove by a list of IDs this works great.
db.CollectionName.remove({
"_id": {
$in: [
ObjectId("0930292929292929292929"),
ObjectId("0920292929292929292929")
]
}
})
If you've upgraded from Bootstrap 2.3.2 to Bootstrap 3 then you'll need to remove the 'hide' class from any of your modal divs.;
If the values came from another table, you might want to use
UPDATE table1 t1
SET (col1, col2) = (
SELECT col3, col4
FROM table2 t2
WHERE t1.col8=t2.col9
)
Example:
UPDATE table1
SET (col1, col2, col3) =(
(SELECT MIN (ship_charge), MAX (ship_charge) FROM orders),
'07/01/2007'
)
WHERE col4 = 1001;
If possible, avoid hard resets. Hard resets are one of the very few destructive operations in git. Luckily, you can undo a cherry-pick without resets and avoid anything destructive.
Note the hash of the cherry-pick you want to undo, say it is ${bad_cherrypick}
. Do a git revert ${bad_cherrypick}
. Now the contents of your working tree are as they were before your bad cherry-pick.
Repeat your git cherry-pick ${wanted_commit}
, and when you're happy with the new cherry-pick, do a git rebase -i ${bad_cherrypick}~1
. During the rebase, delete both ${bad_cherrypick}
and its corresponding revert.
The branch you are working on will only have the good cherry-pick. No resets needed!
Well given the choice, I'd be using objects. I'd create an object for each record where each object has a children
collection and store them all in an assoc array (/hashtable) where the Id is the key. And blitz through the collection once, adding the children to the relevant children fields. Simple.
But because you're being no fun by restricting use of some good OOP, I'd probably iterate based on:
function PrintLine(int pID, int level)
foreach record where ParentID == pID
print level*tabs + record-data
PrintLine(record.ID, level + 1)
PrintLine(0, 0)
Edit: this is similar to a couple of other entries, but I think it's slightly cleaner. One thing I'll add: this is extremely SQL-intensive. It's nasty. If you have the choice, go the OOP route.
Easy and simple way to quit from the application
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
i got some problems with dynamic refresh of my listview.
Call notifyDataSetChanged() on your Adapter.
Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.
notifyDataSetChanged() did not work properly in my case[ I called the notifyDataSetChanged from another class]. Just in the case i edited the ListView in the running Activity (Thread). That video thanks to Christopher gave the final hint.
In my second class i used
Runnable run = new Runnable(){
public void run(){
contactsActivity.update();
}
};
contactsActivity.runOnUiThread(run);
to acces the update() from my Activity. This update includes
myAdapter.notifyDataSetChanged();
to tell the Adapter to refresh the view. Worked fine as far as I can say.
Another solution is to do the division within a python command. For example:
$ numerator=90
$ denominator=7
$ python -c "print (round(${numerator}.0 / ${denominator}.0))"
Seems less archaic to me than using awk.
rsubmit;
options missing=0;
ods listing close;
ods csv file='\\FILE_PATH_and_Name_of_report.csv';
proc sql;
SELECT *
FROM `YOUR_FINAL_TABLE_NAME';
quit;
ods csv close;
endrsubmit;
You can use normal CSS selectors to select an element by name using jquery. Like this:
Button Code
<button type="button" name="mybutton">Click Me!</button>
Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});
The preflight is being triggered by your Content-Type of application/json
. The simplest way to prevent this is to set the Content-Type to be text/plain
in your case. application/x-www-form-urlencoded
& multipart/form-data
Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.
If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.
Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:
VSCommands didn't work for me and caused a problem when I installed Visual Studio 2010 aside of Visual Studio 2012.
After some experimentations I found the trick:
Go to HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers
and add an entry with the name "C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe"
and the value "RUNASADMIN"
.
This should solve your issue. I've also blogged about that.
Try this:
Update TableB Set
Code = Coalesce(
(Select Max(Value)
From TableA
Where Id = b.Id), 123)
From TableB b
You could have multiple Python versions on your macOS.
You may check that by command
, type
or which
command, like:
which -a python python2 python2.7 python3 python3.6
Or type python
in Terminal and hit Tab few times for auto completion, which is equivalent to:
compgen -c python
By default python
/pip
commands points to the first binary found in PATH
environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin
which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local
(such as /usr/local/bin
) are provided by external packages.
It is generally advised, that when working with multiple versions, for Python 2 you may use python2
/pip2
command, respectively for Python 3 you can use python3
/pip3
, but it depends on your configuration which commands are available.
It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python
formula has been upgraded to Python 3.x and a python@2
formula will be added for installing Python 2.7. Before, python
formula was pointing to Python 2.
For instance, if you've installed different version via Homebrew, try the following command:
brew list python python3
or:
brew list | grep ^python
it'll show you all Python files installed with the package.
Alternatively you may use apropos
or locate python
command to locate more Python related files.
To check any environment variables related to Python, run:
env | grep ^PYTHON
To address your issues:
Error: No such keg: /usr/local/Cellar/python
Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3
).
The locate database (
/var/db/locate.database
) does not exist.
Follow the advice and run:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
After the database is rebuild, you can use locate
command.
Learn about CORS, try crossorigin.me
is work fine
Example: https://crossorigin.me/https://fr.s.us/js/jquery-ui.css
Not show a message error and continue page white, u need see error is try
http://cors.io/?u=https://fr.s.us/js/jquery-ui.css
enjoin us ;-)
I had the same problem on Mac OS(Mojave) and solved the problem as mentioned on this link - Openssl issue.
If you do not have Homebrew or don't know what is Homebrew:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Or if you already have Homebrew installed:
brew update && brew upgrade
brew uninstall --ignore-dependencies openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
Update:
Keep in mind, that I had to use --ignore-dependencies
flag, because other packages installed that depend on OpenSSL.
Additional if the problem is caused after using pyenv, you can fix it by using:
brew reinstall python
Well, first you should parse the JSON string, so that you can easily access it's members:
var arr = $.parseJSON(str);
Use the map
method to extract the values:
arr = $.map(arr, function(o){ return o.y; });
Then you can use the array in the max
method:
var highest = Math.max.apply(this,arr);
Or as a one-liner:
var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
I could not get the above example to work with blobs and I wanted to know what exactly is in upload.php. So here you go:
(tested only in Chrome 28.0.1500.95)
// javascript function that uploads a blob to upload.php
function uploadBlob(){
// create a blob here for testing
var blob = new Blob(["i am a blob"]);
//var blob = yourAudioBlobCapturedFromWebAudioAPI;// for example
var reader = new FileReader();
// this function is triggered once a call to readAsDataURL returns
reader.onload = function(event){
var fd = new FormData();
fd.append('fname', 'test.txt');
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// print the output from the upload.php script
console.log(data);
});
};
// trigger the read from the reader...
reader.readAsDataURL(blob);
}
The contents of upload.php:
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
echo ($decodedData);
$filename = "test.txt";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
I recently migrated my MongoDB to DynamoDB, and wrote 3 blogs to share some experience and data about performance, cost.
Migrate from MongoDB to AWS DynamoDB + SimpleDB
For zooming your map two level then just add this small code of line
map.setZoom(map.getZoom() + 2);
You can delete localStorage items one by one using Firebug (a useful web development extension) or Firefox's developer console.
You can enter these commands into the console:
localStorage; // click arrow to view object's properties
localStorage.removeItem("foo");
localStorage.clear(); // remove all of localStorage's properties
Firefox now has a built in storage inspector, which you may need to manually enable. See rahilwazir's answer below.
Add this to your viewcontroller. Works like a charm. Just adjust the values.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);
}
@objc func keyboardWillShow(sender: NSNotification) {
self.view.frame.origin.y -= 150
}
@objc func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y += 150
}
So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:
r" |(?<![0-9])[.,](?![0-9])"
The event must be cancelable
. Adding an if
statement solves this issue.
if (e.cancelable) {
e.preventDefault();
}
In your code you should put it here:
if (this.isSwipe(swipeThreshold) && e.cancelable) {
e.preventDefault();
e.stopPropagation();
swiping = true;
}
To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset()
syntax. E.g. for the data-frame
df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)
to remove just the a
column you could do
Data <- subset( Data, select = -a )
and to remove the b
and d
columns you could do
Data <- subset( Data, select = -c(d, b ) )
You can remove all columns between d
and b
with:
Data <- subset( Data, select = -c( d : b )
As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset
documentation:
Warning:
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.
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
I created class for work with shapes hope you enjoy
public class Geomethry {
public static boolean intersectionCircleAndRectangle(int circleX, int circleY, int circleR, int rectangleX, int rectangleY, int rectangleWidth, int rectangleHeight){
boolean result = false;
float rectHalfWidth = rectangleWidth/2.0f;
float rectHalfHeight = rectangleHeight/2.0f;
float rectCenterX = rectangleX + rectHalfWidth;
float rectCenterY = rectangleY + rectHalfHeight;
float deltax = Math.abs(rectCenterX - circleX);
float deltay = Math.abs(rectCenterY - circleY);
float lengthHypotenuseSqure = deltax*deltax + deltay*deltay;
do{
// check that distance between the centerse is more than the distance between the circumcircle of rectangle and circle
if(lengthHypotenuseSqure > ((rectHalfWidth+circleR)*(rectHalfWidth+circleR) + (rectHalfHeight+circleR)*(rectHalfHeight+circleR))){
//System.out.println("distance between the centerse is more than the distance between the circumcircle of rectangle and circle");
break;
}
// check that distance between the centerse is less than the distance between the inscribed circle
float rectMinHalfSide = Math.min(rectHalfWidth, rectHalfHeight);
if(lengthHypotenuseSqure < ((rectMinHalfSide+circleR)*(rectMinHalfSide+circleR))){
//System.out.println("distance between the centerse is less than the distance between the inscribed circle");
result=true;
break;
}
// check that the squares relate to angles
if((deltax > (rectHalfWidth+circleR)*0.9) && (deltay > (rectHalfHeight+circleR)*0.9)){
//System.out.println("squares relate to angles");
result=true;
}
}while(false);
return result;
}
public static boolean intersectionRectangleAndRectangle(int rectangleX, int rectangleY, int rectangleWidth, int rectangleHeight, int rectangleX2, int rectangleY2, int rectangleWidth2, int rectangleHeight2){
boolean result = false;
float rectHalfWidth = rectangleWidth/2.0f;
float rectHalfHeight = rectangleHeight/2.0f;
float rectHalfWidth2 = rectangleWidth2/2.0f;
float rectHalfHeight2 = rectangleHeight2/2.0f;
float deltax = Math.abs((rectangleX + rectHalfWidth) - (rectangleX2 + rectHalfWidth2));
float deltay = Math.abs((rectangleY + rectHalfHeight) - (rectangleY2 + rectHalfHeight2));
float lengthHypotenuseSqure = deltax*deltax + deltay*deltay;
do{
// check that distance between the centerse is more than the distance between the circumcircle
if(lengthHypotenuseSqure > ((rectHalfWidth+rectHalfWidth2)*(rectHalfWidth+rectHalfWidth2) + (rectHalfHeight+rectHalfHeight2)*(rectHalfHeight+rectHalfHeight2))){
//System.out.println("distance between the centerse is more than the distance between the circumcircle");
break;
}
// check that distance between the centerse is less than the distance between the inscribed circle
float rectMinHalfSide = Math.min(rectHalfWidth, rectHalfHeight);
float rectMinHalfSide2 = Math.min(rectHalfWidth2, rectHalfHeight2);
if(lengthHypotenuseSqure < ((rectMinHalfSide+rectMinHalfSide2)*(rectMinHalfSide+rectMinHalfSide2))){
//System.out.println("distance between the centerse is less than the distance between the inscribed circle");
result=true;
break;
}
// check that the squares relate to angles
if((deltax > (rectHalfWidth+rectHalfWidth2)*0.9) && (deltay > (rectHalfHeight+rectHalfHeight2)*0.9)){
//System.out.println("squares relate to angles");
result=true;
}
}while(false);
return result;
}
}
var type={
format:"DD, d MM, yy"
};
$('.classname').datepicker(type.format);
Those types are there so that you can create arrays of the primitives, and not the boxed types. Since String isn't a primitive in Java, you can just use Array<String>
in Kotlin as the equivalent of a Java String[]
.
from manual:
: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.
As this returns always zero therefore is is similar to be used as true
Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?
Use the std::vector
class from the standard library.
git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.
git checkout <local_branch>
git merge <master>
If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing
Use the keyword next
. If you do not want to continue to the next item, use break
.
When next
is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:
f.each do |line| # Iterate over the lines in file f
next if line[0,1] == "#" # If this line is a comment, go to the next
puts eval(line)
end
When used in a block, break
transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:
f.each do |line| # Iterate over the lines in file f
break if line == "quit\n" # If this break statement is executed...
puts eval(line)
end
puts "Good bye" # ...then control is transferred here
And finally, the usage of return
in a block:
return
always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):
def find(array, target)
array.each_with_index do |element,index|
return index if (element == target) # return from find
end
nil # If we didn't find the element, return nil
end
You can have a debug.cmd that calls yourscript.cmd
yourscript.cmd > logall.txt
you schedule debug.cmd instead of yourscript.cmd
specifically I want to overload
Boolean.Parse
to allow an int argument.
Would an extension for int work?
public static bool ToBoolean(this int source){
// do it
// return it
}
Then you can call it like this:
int x = 1;
bool y = x.ToBoolean();
Late edit: there is an official plugin for Chart.js 2.7.0+
to do this: https://github.com/chartjs/chartjs-plugin-datalabels
Original answer:
You can loop through the points / bars onAnimationComplete and display the values
Preview
HTML
<canvas id="myChart1" height="300" width="500"></canvas>
<canvas id="myChart2" height="300" width="500"></canvas>
Script
var chartData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [
{
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data: [60, 80, 81, 56, 55, 40]
}
]
};
var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.points.forEach(function (points) {
ctx.fillText(points.value, points.x, points.y - 10);
});
})
}
});
var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillText(bar.value, bar.x, bar.y - 5);
});
})
}
});
Fiddle - http://jsfiddle.net/uh9vw0ao/
start cmd.exe
opens a separate window
start file.cmd
opens the batch file and executes it in another command prompt
You can use a bind function to use a pseudo multi-statement lambda. Then you can use a wrapper class for a Flag to enable assignment.
bind = lambda x, f=(lambda y: y): f(x)
class Flag(object):
def __init__(self, value):
self.value = value
def set(self, value):
self.value = value
return value
input = [Object(name=""), Object(name="fake_name"), Object(name="")]
flag = Flag(True)
output = filter(
lambda o: (
bind(flag.value, lambda orig_flag_value:
bind(flag.set(flag.value and bool(o.name)), lambda _:
bind(orig_flag_value or bool(o.name))))),
input)
Using balexandre's info:
SELECT usesysid, usename FROM pg_stat_activity;
In case someone is still looking for the answer, this worked for me:
=COUNTIF(A2:A51, "*" & B1 & "*")
B1
containing the iPad
string.
I want to more fully address the issue of scroll duration, which, should you choose any earlier answer, will in fact will vary dramatically (and unacceptably) according to the amount of scrolling necessary to reach the target position from the current position .
To obtain a uniform scroll duration the velocity (pixels per millisecond) must account for the size of each individual item - and when the items are of non-standard dimension then a whole new level of complexity is added.
This may be why the RecyclerView developers deployed the too-hard basket for this vital aspect of smooth scrolling.
Assuming that you want a semi-uniform scroll duration, and that your list contains semi-uniform items then you will need something like this.
/** Smoothly scroll to specified position allowing for interval specification. <br>
* Note crude deceleration towards end of scroll
* @param rv Your RecyclerView
* @param toPos Position to scroll to
* @param duration Approximate desired duration of scroll (ms)
* @throws IllegalArgumentException */
private static void smoothScroll(RecyclerView rv, int toPos, int duration) throws IllegalArgumentException {
int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000; // See androidx.recyclerview.widget.LinearSmoothScroller
int itemHeight = rv.getChildAt(0).getHeight(); // Height of first visible view! NB: ViewGroup method!
itemHeight = itemHeight + 33; // Example pixel Adjustment for decoration?
int fvPos = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
int i = Math.abs((fvPos - toPos) * itemHeight);
if (i == 0) { i = (int) Math.abs(rv.getChildAt(0).getY()); }
final int totalPix = i; // Best guess: Total number of pixels to scroll
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(rv.getContext()) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
@Override protected int calculateTimeForScrolling(int dx) {
int ms = (int) ( duration * dx / (float)totalPix );
// Now double the interval for the last fling.
if (dx < TARGET_SEEK_SCROLL_DISTANCE_PX ) { ms = ms*2; } // Crude deceleration!
//lg(format("For dx=%d we allot %dms", dx, ms));
return ms;
}
};
//lg(format("Total pixels from = %d to %d = %d [ itemHeight=%dpix ]", fvPos, toPos, totalPix, itemHeight));
smoothScroller.setTargetPosition(toPos);
rv.getLayoutManager().startSmoothScroll(smoothScroller);
}
PS: I curse the day I began indiscriminately converting ListView to RecyclerView.
You are declaring a local variable, not a class variable. To set an instance variable (attribute), use
class Example(object):
def the_example(self):
self.itsProblem = "problem" # <-- remember the 'self.'
theExample = Example()
theExample.the_example()
print(theExample.itsProblem)
To set a class variable (a.k.a. static member), use
class Example(object):
def the_example(self):
Example.itsProblem = "problem"
# or, type(self).itsProblem = "problem"
# depending what you want to do when the class is derived.
In Ruby and Perl 6 this has been called "splat", and I think most people from those communities will figure out what you mean if you call it that.
The Python tutorial uses the phrase "unpacking argument lists", which is long and descriptive.
It is also referred to as iterable unpacking, or in the case of **
,
dictionary unpacking.
for me this worked
RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
There are generally 2 levels of buffering-
1. Kernel buffer Cache (makes read/write faster)
2. Buffering in I/O library (reduces no. of system calls)
Let's take example of fprintf and write()
.
When you call fprintf()
, it doesn't wirte directly to the file. It first goes to stdio buffer in the program's memory. From there it is written to the kernel buffer cache by using write system call. So one way to skip I/O buffer is directly using write(). Other ways are by using setbuff(stream,NULL)
. This sets the buffering mode to no buffering and data is directly written to kernel buffer.
To forcefully make the data to be shifted to kernel buffer, we can use "\n", which in case of default buffering mode of 'line buffering', will flush I/O buffer.
Or we can use fflush(FILE *stream)
.
Now we are in kernel buffer. Kernel(/OS) wants to minimise disk access time and hence it reads/writes only blocks of disk. So when a read()
is issued, which is a system call and can be invoked directly or through fscanf()
, kernel reads the disk block from disk and stores it in a buffer. After that data is copied from here to user space.
Similarly that fprintf()
data recieved from I/O buffer is written to the disk by the kernel. This makes read() write() faster.
Now to force the kernel to initiate a write()
, after which data transfer is controlled by hardware controllers, there are also some ways. We can use O_SYNC
or similar flags during write calls. Or we could use other functions like fsync(),fdatasync(),sync()
to make the kernel initiate writes as soon as data is available in the kernel buffer.
The variable name you're looking for is ansible_ssh_private_key_file
.
You should set it at 'vars' level:
in the inventory file:
myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
in the host_vars
:
# hosts_vars/myHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
# hosts_vars/myOtherHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
in a group_vars
file if you use the same key for a group of hosts
in the vars
section of your play:
- hosts: myHost
remote_user: ubuntu
vars_files:
- vars.yml
vars:
ansible_ssh_private_key_file: "{{ key1 }}"
tasks:
- name: Echo a hello message
command: echo hello
To detect the type of gesture tap one can implement something inline with this: ( here projectText is an EditText )
projectText.setOnTouchListener(new View.OnTouchListener() {
private GestureDetector gestureDetector = new GestureDetector(activity, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
projectText.setInputType(InputType.TYPE_CLASS_TEXT);
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
return super.onDoubleTap(e);
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
projectText.setInputType(InputType.TYPE_NULL); // disable soft input
final int itemPosition = getLayoutPosition();
if(!projects.get(itemPosition).getProjectId().equals("-1"))
listener.selectedClick(projects.get(itemPosition));
return super.onSingleTapUp(e);
}
});
@Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
return false; //true stops propagation of the event
}
});
This question specifically mentions a single column, so the currently accepted answer works. However, it doesn't generalize to multiple columns. For those interested in a general solution, use the following:
df.replace({False: 0, True: 1}, inplace=True)
This works for a DataFrame that contains columns of many different types, regardless of how many are boolean.
Don't want to create a drawable resource?
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:minHeight="128dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:background="@android:color/white">
<TextView ... />
</FrameLayout>
</FrameLayout>
An array that contains a property that equals to
yourArray.contains(where: {$0.propertyToCheck == value })
Returns boolean.
I know this is quite an old question -
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Let's say, you want to extract the first 2 rows and first 3 columns
A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
[4, 5, 6]]
Understanding the syntax
A_NEW = A[start_index_row : stop_index_row,
start_index_column : stop_index_column)]
If one wants row 2 and column 2 and 3
A_NEW = A[1:2, 1:3]
Reference the numpy indexing and slicing article - Indexing & Slicing
Here is a solution that does not require a SQL context, but maintains the metadata of a DataFrame.
a = sc.parallelize([['a', 'foo'], ['b', 'hem'], ['c', 'haw']]).toDF(['a_id', 'extra'])
b = sc.parallelize([['p1', 'a'], ['p2', 'b'], ['p3', 'c']]).toDF(["other", "b_id"])
c = a.join(b, a.a_id == b.b_id)
Then, c.show()
yields:
+----+-----+-----+----+
|a_id|extra|other|b_id|
+----+-----+-----+----+
| a| foo| p1| a|
| b| hem| p2| b|
| c| haw| p3| c|
+----+-----+-----+----+
I found a way that works if I use JavaScript combined with TypeScript.
logging.d.ts:
declare var log: log4javascript.Logger;
log-declaration.js:
log = null;
initalize-app.ts
import './log-declaration.js';
// Call stuff to actually setup log.
// Similar to this:
log = functionToSetupLog();
This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.
NOTE: I think this only works because I have the allowJs
TypeScript option set to true.
If someone posts an pure TypeScript solution, I will accept that.
Just for completeness, the || and && are the conditional version of the | and & operators.
A reference to the ECMA C# Language specification is here.
From the specification:
3 The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.
In the |
version both sides are evaluated.
The conditional version short circuits evaluation and so allows for code like:
if (x == null || x.Value == 5)
// Do something
Or (no pun intended) using your example:
if (title == "User greeting" || title == "User name")
// {do stuff}
C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.
if you know for sure the element is unique (such as your case with the ID):
myDiv.parentElement.querySelectorAll("#myDiv > .foo");
For a more "global" solution: (use a matchesSelector shim)
function getDirectChildren(elm, sel){
var ret = [], i = 0, l = elm.childNodes.length;
for (var i; i < l; ++i){
if (elm.childNodes[i].matchesSelector(sel)){
ret.push(elm.childNodes[i]);
}
}
return ret;
}
where elm
is your parent element, and sel
is your selector. Could totally be used as a prototype as well.
I just developed my own profiler inspired from pypref_time:
https://github.com/modaresimr/auto_profiler
By adding a decorator it will show a tree of time-consuming functions
@Profiler(depth=4, on_disable=show)
Install by: pip install auto_profiler
import time # line number 1
import random
from auto_profiler import Profiler, Tree
def f1():
mysleep(.6+random.random())
def mysleep(t):
time.sleep(t)
def fact(i):
f1()
if(i==1):
return 1
return i*fact(i-1)
def show(p):
print('Time [Hits * PerHit] Function name [Called from] [Function Location]\n'+\
'-----------------------------------------------------------------------')
print(Tree(p.root, threshold=0.5))
@Profiler(depth=4, on_disable=show)
def main():
for i in range(5):
f1()
fact(3)
if __name__ == '__main__':
main()
Time [Hits * PerHit] Function name [Called from] [function location]
-----------------------------------------------------------------------
8.974s [1 * 8.974] main [auto-profiler/profiler.py:267] [/test/t2.py:30]
+-- 5.954s [5 * 1.191] f1 [/test/t2.py:34] [/test/t2.py:14]
¦ +-- 5.954s [5 * 1.191] mysleep [/test/t2.py:15] [/test/t2.py:17]
¦ +-- 5.954s [5 * 1.191] <time.sleep>
|
|
| # The rest is for the example recursive function call fact
+-- 3.020s [1 * 3.020] fact [/test/t2.py:36] [/test/t2.py:20]
+-- 0.849s [1 * 0.849] f1 [/test/t2.py:21] [/test/t2.py:14]
¦ +-- 0.849s [1 * 0.849] mysleep [/test/t2.py:15] [/test/t2.py:17]
¦ +-- 0.849s [1 * 0.849] <time.sleep>
+-- 2.171s [1 * 2.171] fact [/test/t2.py:24] [/test/t2.py:20]
+-- 1.552s [1 * 1.552] f1 [/test/t2.py:21] [/test/t2.py:14]
¦ +-- 1.552s [1 * 1.552] mysleep [/test/t2.py:15] [/test/t2.py:17]
+-- 0.619s [1 * 0.619] fact [/test/t2.py:24] [/test/t2.py:20]
+-- 0.619s [1 * 0.619] f1 [/test/t2.py:21] [/test/t2.py:14]
A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE
can be useful. Take a look at this example (PostgreSQL):
CREATE TABLE club
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE band
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE concert
(
key SERIAL PRIMARY KEY,
club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
concert_date DATE
);
In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE
was the key to solve the problem.
Swift 5, Checkbox with animation
Create an outlet of the button
@IBOutlet weak var checkBoxOutlet:UIButton!{
didSet{
checkBoxOutlet.setImage(UIImage(named:"unchecked"), for: .normal)
checkBoxOutlet.setImage(UIImage(named:"checked"), for: .selected)
}
}
Create an extension of UIButton
extension UIButton {
//MARK:- Animate check mark
func checkboxAnimation(closure: @escaping () -> Void){
guard let image = self.imageView else {return}
UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveLinear, animations: {
image.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}) { (success) in
UIView.animate(withDuration: 0.1, delay: 0, options: .curveLinear, animations: {
self.isSelected = !self.isSelected
//to-do
closure()
image.transform = .identity
}, completion: nil)
}
}
}
How to use
@IBAction func checkbox(_ sender: UIButton){
sender.checkboxAnimation {
print("I'm done")
//here you can also track the Checked, UnChecked state with sender.isSelected
print(sender.isSelected)
}
}
Check my Example for Checkbox and Radio button https://github.com/rashidlatif55/CheckBoxAndRadioButton
PowerShell has really wacky return semantics - at least when viewed from a more traditional programming perspective. There are two main ideas to wrap your head around:
Thus, the following two script blocks will do effectively the exact same thing:
$a = "Hello, World"
return $a
$a = "Hello, World"
$a
return
The $a variable in the second example is left as output on the pipeline and, as mentioned, all output is returned. In fact, in the second example you could omit the return entirely and you would get the same behavior (the return would be implied as the function naturally completes and exits).
Without more of your function definition I can't say why you are getting a PSMethod object. My guess is that you probably have something a few lines up that is not being captured and is being placed on the output pipeline.
It is also worth noting that you probably don't need those semicolons - unless you are nesting multiple expressions on a single line.
You can read more about the return semantics on the about_Return page on TechNet, or by invoking the help return
command from PowerShell itself.
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from http://pypi.python.org/pypi/automodinit/.
Usage is like this:
automodinit
package into your setup.py
dependencies.__all__ = ["I will get rewritten"] # Don't modify the line above, or this line! import automodinit automodinit.automodinit(__name__, __file__, globals()) del automodinit # Anything else you want can go after here, it won't get modified.
That's it! From now on importing a module will set __all__ to a list of .py[co] files in the module and will also import each of those files as though you had typed:
for x in __all__: import x
Therefore the effect of "from M import *" matches exactly "import M".
automodinit
is happy running from inside ZIP archives and is therefore ZIP safe.
Niall
If you are already using an OutputStream
to write to the socket, then DataOutputStream might be a good fit. Here is an example:
// Assumes you are currently working with a SocketOutputStream.
SocketOutputStream outputStream = ...
long longValue = ...
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeLong(longValue);
dataOutputStream.flush();
There are similar methods for short
, int
, float
, etc. You can then use DataInputStream on the receiving side.
Two things you can do, return an object
somethingAsync()
.then( afterSomething )
.then( afterSomethingElse );
function processAsync (amazingData) {
//processSomething
return {
amazingData: amazingData,
processedData: processedData
};
}
function afterSomething( amazingData ) {
return processAsync( amazingData );
}
function afterSomethingElse( dataObj ) {
let amazingData = dataObj.amazingData,
processedData = dataObj.proccessedData;
}
Use the scope!
var amazingData;
somethingAsync()
.then( afterSomething )
.then( afterSomethingElse )
function afterSomething( returnedAmazingData ) {
amazingData = returnedAmazingData;
return processAsync( amazingData );
}
function afterSomethingElse( processedData ) {
//use amazingData here
}
I had the very same problem recently with Android Studio 1.3. The only working solution was to remove the .gradle and .idea folders and re-import the project into Android Studio.
You can also use shift()
.
var streetaddress = addy.split(',').shift();
According to MDN Web Docs:
The
shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
This still loops through the cartesian product of the two lists, but it does it one line:
>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False
This also have the advantage that any
short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings
in linesX
. If you want to find multiple occurrences you could do something like this:
>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]
If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.
There are many reasons, but perhaps the most important one is that those functions encourage insecure programming practices because they do not support prepared statements. Prepared statements help prevent SQL injection attacks.
When using mysql_*
functions, you have to remember to run user-supplied parameters through mysql_real_escape_string()
. If you forget in just one place or if you happen to escape only part of the input, your database may be subject to attack.
Using prepared statements in PDO
or mysqli
will make it so that these sorts of programming errors are more difficult to make.
Default c++ mechanism for file IO is called streams.
Streams can be of three flavors: input, output and inputoutput.
Input streams act like sources of data. To read data from an input stream you use >>
operator:
istream >> my_variable; //This code will read a value from stream into your variable.
Operator >>
acts different for different types. If in the example above my_variable
was an int, then a number will be read from the strem, if my_variable
was a string, then a word would be read, etc.
You can read more then one value from the stream by writing istream >> a >> b >> c;
where a, b and c would be your variables.
Output streams act like sink to which you can write your data. To write your data to a stream, use <<
operator.
ostream << my_variable; //This code will write a value from your variable into stream.
As with input streams, you can write several values to the stream by writing something like this:
ostream << a << b << c;
Obviously inputoutput streams can act as both.
In your code sample you use cout
and cin
stream objects.
cout
stands for console-output and cin for console-input
. Those are predefined streams for interacting with default console.
To interact with files, you need to use ifstream
and ofstream
types.
Similar to cin
and cout
, ifstream
stands for input-file-stream
and ofstream
stands for output-file-stream
.
Your code might look like this:
#include <iostream>
#include <fstream>
using namespace std;
int start()
{
cout << "Welcome...";
// do fancy stuff
return 0;
}
int main ()
{
string usreq, usr, yn, usrenter;
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ifstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt");
iusrfile >> usr;
cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
For further reading you might want to look at c++ I/O reference
In My case two mysqld processes were running.. killed the optional processs by using pkill -9 mysqld
According to Opera the CSS3 standard does not define the use of border-radius
on TDs. My experience is that Firefox and Chrome support it but Opera does not (don't know about IE). The workaround is to wrap the td content in a div and then apply the border-radius
to the div.
Another issue is that you're reading with scanf("%f", &input);
only. If the user types something that can't be interpreted as a C floating-point number, like "pi", the scanf()
call will not assign anything to input
, and won't progress from there. This means it would attempt to keep reading "pi", and failing.
Given the change to while(!feof(stdin))
which other posters are correctly recommending, if you typed "pi" in there would be an endless loop of printing out the former value of input
and printing the prompt, but the program would never process any new input.
scanf()
returns the number of assignments to input variables it made. If it made no assignment, that means it didn't find a floating-point number, and you should read through more input with something like char string[100];scanf("%99s", string);
. This will remove the next string from the input stream (up to 99 characters, anyway - the extra char
is for the null terminator on the string).
You know, this is reminding me of all the reasons I hate scanf()
, and why I use fgets()
instead and then maybe parse it using sscanf()
.
It varies for different systems (depends on RAM). The easiest way to find out is
import six
six.MAXSIZE
9223372036854775807
This gives the max size of list
and dict
too ,as per the documentation
The name
is present inside the data
. You need to parse a JSON hierarchically to be able to fetch the data properly.
JSONObject jObject = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.
Note: This example uses the org.json.JSONObject
class and not org.json.simple.JSONObject
.
As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject
, I'm adding my comment details in the answer.
Try to use the
org.json.JSONObject
instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.
Sample from the link provided:
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
You could maybe disable and re-enable constraints:
http://sqlforums.windowsitpro.com/web/forum/messageview.aspx?catid=60&threadid=48410&enterthread=y
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
You may want to remove the space to the second String:
separated[1] = separated[1].trim();
If you want to split the string with a special character like dot(.) you should use escape character \ before the dot
Example:
String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"
There are other ways to do it. For instance, you can use the StringTokenizer
class (from java.util
):
StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
Extending the Quote idea for Objective-C:
#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]
NSString *sql = NSStringMultiline(
SELECT name, age
FROM users
WHERE loggedin = true
);
You can activate JVM's debugging capability when starting up the java
command with a special option:
java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar
Starting up jar.jar
like that on the command line will:
server=y
) listening on port 8000 (address=8000
)Listening for transport dt_socket at address: 8000
to stdout
andsuspend=y
) until some debugger connects. The debugger acts as the client in this scenario.Common options for selecting a debugger are:
jar.jar
should begin executing.jdb -connect com.sun.jdi.SocketAttach:port=8000
Putting the other answers all together, here's a command line that will work:
env vblank_mode=0 __GL_SYNC_TO_VBLANK=0 glxgears
This has the advantages of working for both Mesa and NVidia drivers, and not requiring any changes to configuration files.
The code works for me. (after adding missing except
clause / import
statements)
Did you put \
in the original code?
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
+ stock + '/chartdata;type=quote;range=5d/csv'
If you omit it, it could be a cause of the exception:
>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
BTW, string(e)
should be str(e)
.
there are a number of NSDate
helpers on the web, I tend to use:
https://github.com/billymeltdown/nsdate-helper/
Readme extract below:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
This produces the following kinds of output:
‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)
I have now been able to get Keyboard input in Swift by using the following:
In my main.swift file I declared a variable i and assigned to it the function GetInt() which I defined in Objective C. Through a so called Bridging Header where I declared the function prototype for GetInt I could link to main.swift. Here are the files:
main.swift:
var i: CInt = GetInt()
println("Your input is \(i) ");
Bridging Header:
#include "obj.m"
int GetInt();
obj.m:
#import <Foundation/Foundation.h>
#import <stdio.h>
#import <stdlib.h>
int GetInt()
{
int i;
scanf("%i", &i);
return i;
}
In obj.m it is possible to include the c standard output and input, stdio.h, as well as the c standard library stdlib.h which enables you to program in C in Objective-C, which means there is no need for including a real swift file like user.c or something like that.
Hope I could help,
Edit: It is not possible to get String input through C because here I am using the CInt -> the integer type of C and not of Swift. There is no equivalent Swift type for the C char*. Therefore String is not convertible to string. But there are fairly enough solutions around here to get String input.
Raul
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps
https://nominatim.openstreetmap.org/search?q=Mumbai&format=json
Here is the API documentation for reference.
Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.
The best solution, for me, is to wrap input [type="file"] in a wrapper, and add some jquery code:
$(function(){_x000D_
function readURL(input){_x000D_
if (input.files && input.files[0]){_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onload = function (e){_x000D_
$('#uploadImage').attr('src', e.target.result);_x000D_
}_x000D_
reader.readAsDataURL(input.files[0]);_x000D_
}_x000D_
}_x000D_
$("#image").change(function(){_x000D_
readURL(this);_x000D_
});_x000D_
});
_x000D_
#image{_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
opacity: 0;_x000D_
width: 75px;_x000D_
height: 35px;_x000D_
}_x000D_
#uploadImage{_x000D_
position: relative;_x000D_
top: 30px;_x000D_
left: 70px;_x000D_
}_x000D_
.button{_x000D_
position: relative;_x000D_
width: 75px;_x000D_
height: 35px;_x000D_
border: 1px solid #000;_x000D_
border-radius: 5px;_x000D_
font-size: 1.5em;_x000D_
text-align: center;_x000D_
line-height: 34px;_x000D_
}
_x000D_
<form action="#" method="post" id="form" >_x000D_
<div class="button">_x000D_
Upload<input type="file" id="image" />_x000D_
</div>_x000D_
<img id="uploadImage" src="#" alt="your image" width="350" height="300" />_x000D_
</form>
_x000D_
This was resolved by installing the latest NuGet Package Manager:
https://visualstudiogallery.msdn.microsoft.com/4ec1526c-4a8c-4a84-b702-b21a8f5293ca
Don't forget to restart Visual Studio.
You have to write a specific media query for this, from your question, below 768px, the navbar will collapse, so apply it above 768px and below 1000px, just like that:
@media (min-width: 768px) and (max-width: 1000px) {
.collapse {
display: none !important;
}
}
This will hide the navbar collapse until the default occurrence of the bootstrap unit. As the collapse class flips the inner assets inside navbar collapse will be automatically hidden, like wise you have to set your css as you desired design.
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}
You can use a replace regular expression.
s/[;,\t\r ]|[\n]{2}/\n/g
s/
at the beginning means a search[
and ]
are the characters to search for (in any order)/
delimits the search-for text and the replace textIn English, this reads:
"Search for ;
or ,
or \t
or \r
or (space) or exactly two sequential
\n
and replace it with \n
"
In C#, you could do the following: (after importing System.Text.RegularExpressions
)
Regex pattern = new Regex("[;,\t\r ]|[\n]{2}");
pattern.Replace(myString, "\n");
That can be done by using some/every methods of Array and RegEx.
To check whether ALL of words from list(array) are present in the string:
const multiSearchAnd = (text, searchWords) => (
searchWords.every((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
To check whether ANY of words from list(array) are present in the string:
const multiSearchOr = (text, searchWords) => (
searchWords.some((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false
The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.
Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.
This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.
See also here:
The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.
In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.
1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2
The pattern \d
might not be supported by your sed
. Try [0-9]
or [[:digit:]]
instead.
To only print the actual match (not the entire matching line), use a substitution.
sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'
In the following Java solution we take advantage over the fact that Strings are immutable in order to avoid cloning the result-set upon every iteration.
The input will be a String, say "abc", and the output will be all the possible permutations:
abc
acb
bac
bca
cba
cab
public static void permute(String s) {
permute(s, 0);
}
private static void permute(String str, int left){
if(left == str.length()-1) {
System.out.println(str);
} else {
for(int i = left; i < str.length(); i++) {
String s = swap(str, left, i);
permute(s, left+1);
}
}
}
private static String swap(String s, int left, int right) {
if (left == right)
return s;
String result = s.substring(0, left);
result += s.substring(right, right+1);
result += s.substring(left+1, right);
result += s.substring(left, left+1);
result += s.substring(right+1);
return result;
}
Same approach can be applied to arrays (instead of a string):
public static void main(String[] args) {
int[] abc = {1,2,3};
permute(abc, 0);
}
public static void permute(int[] arr, int index) {
if (index == arr.length) {
System.out.println(Arrays.toString(arr));
} else {
for (int i = index; i < arr.length; i++) {
int[] permutation = arr.clone();
permutation[index] = arr[i];
permutation[i] = arr[index];
permute(permutation, index + 1);
}
}
}
What they both have in common is that they both use a partition to differentiate between the sorted part of the array and the unsorted.
The difference is, that with selection sort you are guaranteed that sorted part of the array won't change when adding elements to the sorted partition.
The reason being, because selection searches for the minimum of the unsorted set and adds it right after the last element of the sorted set, thereby increasing the sorted set by 1.
Insertion on the other hand, only just cares about the next element that is encountered, which is the first element in the unsorted part of the array. It will take this element and simply fit it into its proper place in the sorted set.
Insertion sort will typically always be a better candidate for arrays that are only partially sorted because you are wasting operations to find the minimum.
Conclusion:
Selection sort incrementally adds an element to the end by finding the minimum element in the unsorted section.
Insertion sort propagates the first element found in the unsorted section into anywhere in the sorted section.
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
Semantically, you use <p>
tags to indicate paragraphs. <span>
is used to apply CSS style and/or class(es) to an arbitrary section of text and inline elements.
If all you want is the number of lines (and not the number of lines and the stupid file name coming back):
wc -l < /filepath/filename.ext
As previously mentioned these also work (but are inferior for other reasons):
awk 'END{print NR}' file # not on all unixes
sed -n '$=' file # (GNU sed) also not on all unixes
grep -c ".*" file # overkill and probably also slower
The icons you are seeing on desktop is not a icon file. They are either executable files .exe or shortcuts of any application .lnk. So can only set icon which have .ico extension.
Go to Project Menu -> Your_Project_Name Properties -> Application TAB -> Resources -> Icon
browse for your Icon, remember it must have .ico extension
You can make your icon in Visual Studio
Go to Project Menu -> Add New Item -> Icon File
Above methods didn´t work for me. This did:
Dim arrayIsNothing As Boolean
On Error Resume Next
arrayIsNothing = IsNumeric(UBound(YOUR_ARRAY)) And False
If Err.Number <> 0 Then arrayIsNothing = True
Err.Clear
On Error GoTo 0
'Now you can test:
if arrayIsNothing then ...
You can try editing /etc/php5/fpm/php.ini:
; Old Limit
; memory_limit = 512M
; New Limit
memory_limit = 2048M
You may need to restart nginx
:
sudo systemctl restart nginx
You may also have an infinite loop somewhere. Can you post the code you're calling?
One method is:
tar -cf my_archive.tar $( find -name "*.php" -or -name "*.html" )
There are some caveats with this method however:
A workaround to these could be to output the contents of the find command into a file, and then use the "-T, --files-from FILE" option to tar.
You could also use countplot
from seaborn
. This package builds on pandas
to create a high level plotting interface. It gives you good styling and correct axis labels for free.
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
sns.countplot(df['colour'], color='gray')
It also supports coloring the bars in the right color with a little trick
sns.countplot(df['colour'],
palette={color: color for color in df['colour'].unique()})
I did a little more googling and came across this page
The command doesn't seem to make sense but I tried it anyway:
In the file /usr/share/phpmyadmin/libraries/dbi/mysqli.dbi.lib.php at the end of function PMA_DBI_connect()
just before the return
statement I added:
mysqli_query($link, "SET SESSION CHARACTER_SET_RESULTS =latin1;");
mysqli_query($link, "SET SESSION CHARACTER_SET_CLIENT =latin1;");
And it works! I now see Japanese characters in phpMyAdmin. WTF? Why does this work?
Here is another simple implementation in Swift3.
func seconds2Timestamp(intSeconds:Int)->String {
let mins:Int = intSeconds/60
let hours:Int = mins/60
let secs:Int = intSeconds%60
let strTimestamp:String = ((hours<10) ? "0" : "") + String(hours) + ":" + ((mins<10) ? "0" : "") + String(mins) + ":" + ((secs<10) ? "0" : "") + String(secs)
return strTimestamp
}
maybe you want to take a look java.util.Stack
class.
it has push, pop methods. and implemented List interface.
for shift/unshift, you can reference @Jon's answer.
however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
This is Function which will convert most of the video formats to number of frames there are in the video. It works on Python3
with OpenCV 3+
import cv2
import time
import os
def video_to_frames(input_loc, output_loc):
"""Function to extract frames from input video file
and save them as separate frames in an output directory.
Args:
input_loc: Input video file.
output_loc: Output directory to save the frames.
Returns:
None
"""
try:
os.mkdir(output_loc)
except OSError:
pass
# Log the time
time_start = time.time()
# Start capturing the feed
cap = cv2.VideoCapture(input_loc)
# Find the number of frames
video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
print ("Number of frames: ", video_length)
count = 0
print ("Converting video..\n")
# Start converting the video
while cap.isOpened():
# Extract the frame
ret, frame = cap.read()
# Write the results back to output location.
cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
count = count + 1
# If there are no more frames left
if (count > (video_length-1)):
# Log the time again
time_end = time.time()
# Release the feed
cap.release()
# Print stats
print ("Done extracting frames.\n%d frames extracted" % count)
print ("It took %d seconds forconversion." % (time_end-time_start))
break
if __name__=="__main__":
input_loc = '/path/to/video/00009.MTS'
output_loc = '/path/to/output/frames/'
video_to_frames(input_loc, output_loc)
It supports .mts
and normal files like .mp4
and .avi
. Tried and Tested on .mts
files. Works like a Charm.
Credit to @Gert Grenander , @Alaa.Kh , and Ross Shanon
Trying to make some order:
it all works - all but the firefox bookmarking function. for some reason the 'window.sidebar.addPanel' is not a function for the debugger, though it is working fine.
The problem is that it takes its values from the calling <a ..>
tag: title as the bookmark name and href as the bookmark address.
so this is my code:
javascript:
$("#bookmarkme").click(function () {
var url = 'http://' + location.host; // i'm in a sub-page and bookmarking the home page
var name = "Snir's Homepage";
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
alert("In order to bookmark go to the homepage and press "
+ (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ?
'Command/Cmd' : 'CTRL') + "+D.")
}
else if (window.sidebar) { // Mozilla Firefox Bookmark
//important for firefox to add bookmarks - remember to check out the checkbox on the popup
$(this).attr('rel', 'sidebar');
//set the appropriate attributes
$(this).attr('href', url);
$(this).attr('title', name);
//add bookmark:
// window.sidebar.addPanel(name, url, '');
// window.sidebar.addPanel(url, name, '');
window.sidebar.addPanel('', '', '');
}
else if (window.external) { // IE Favorite
window.external.addFavorite(url, name);
}
return;
});
html:
<a id="bookmarkme" href="#" title="bookmark this page">Bookmark This Page</a>
In internet explorer there is a different between 'addFavorite':
<a href="javascript:window.external.addFavorite('http://tiny.cc/snir','snir-site')">..</a>
and 'AddFavorite': <span onclick="window.external.AddFavorite(location.href, document.title);">..</span>
.
example here: http://www.yourhtmlsource.com/javascript/addtofavorites.html
Important, in chrome we can't add bookmarks using js (aspnet-i): http://www.codeproject.com/Questions/452899/How-to-add-bookmark-in-Google-Chrome-Opera-and-Saf
also check this out, for example we wanna count t
echo "test" | awk -v RS='t' 'END{print NR-1}'
or in python
python -c 'print "this is for test".count("t")'
or even better, we can make our script dynamic with awk
echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""
in this case output is like this :
e 1
s 1
t 2
You need to install the python-setuptools
package:
apt-get install python-setuptools
on Debian-ish systems
yum install python-setuptools
on Redhat-ish systems
Use sudo
if applicable
Webkit based browsers (like Google Chrome or Safari) has built-in developer tools. In Chrome you can open it Menu->Tools->Developer Tools
. The Network
tab allows you to see all information about every request and response:
In the bottom of the picture you can see that I've filtered request down to XHR
- these are requests made by javascript code.
Tip: log is cleared every time you load a page, at the bottom of the picture, the black dot button will preserve log.
After analyzing requests and responses you can simulate these requests from your web-crawler and extract valuable data. In many cases it will be easier to get your data than parsing HTML, because that data does not contain presentation logic and is formatted to be accessed by javascript code.
Firefox has similar extension, it is called firebug. Some will argue that firebug is even more powerful but I like the simplicity of webkit.
I have a project on GitHub that you can use
https://github.com/BrunoVT1992/ConsoleTable
You can use it like this:
var table = new Table();
table.SetHeaders("Name", "Date", "Number");
for (int i = 0; i <= 10; i++)
{
if (i % 2 == 0)
table.AddRow($"name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), i.ToString());
else
table.AddRow($"long name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), (i * 5000).ToString());
}
Console.WriteLine(table.ToString());
It will give this result:
l = [83, 84, 65, 67, 75]
s = "".join([chr(c) for c in l])
print s
Set the href
attribute with
$(selector).attr('href', 'url_goes_here');
and read it using
$(selector).attr('href');
Where "selector" is any valid jQuery selector for your <a>
element (".myClass" or "#myId" to name the most simple ones).
Hope this helps !
Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.
An example:
eventcreate /ID 1 /L APPLICATION /T INFORMATION /SO MYEVENTSOURCE /D "My first log"
This will create a new event source named MYEVENTSOURCE
under APPLICATION
event log as INFORMATION
event type.
I think this utility is included only from XP onwards.
Windows IT Pro: JSI Tip 5487. Windows XP includes the EventCreate utility for creating custom events.
Type eventcreate /?
in CMD prompt
Microsoft TechNet: Windows Command-Line Reference: Eventcreate
SS64: Windows Command-Line Reference: Eventcreate
Doesn't look like it's possible (yet), even with CSS3 or proprietary -webkit-
or -moz-
CSS properties.
However, I did find this post from last June that used SVG filters on HTML. Not available in any current browser (the demo hinted at a custom WebKit build), but very impressive as a proof of concept.
You can use LINQ for this
var list = new List<int>();
var sum = list.Sum();
and for a List of strings like Roy Dictus said you have to convert
list.Sum(str => Convert.ToInt32(str));
int [][] twoDim = new int [5][5];
int a = (twoDim.length);//5
int b = (twoDim[0].length);//5
for(int i = 0; i < a; i++){ // 1 2 3 4 5
for(int j = 0; j <b; j++) { // 1 2 3 4 5
int x = (i+1)*(j+1);
twoDim[i][j] = x;
if (x<10) {
System.out.print(" " + x + " ");
} else {
System.out.print(x + " ");
}
}//end of for J
System.out.println();
}//end of for i
You could just use:
<div id="GridDiv">
// gridview inside...
</div>
<a href="#GridDiv">Scroll to top</a>
.schema TableName
Where TableName is the name of the Table
Your anchor tag should be:
<a id="loginLink" onclick="showHideTable();" href="#">Login</a>
And You javascript function :
function showHideTable()
{
if (document.getElementById("loginTable").style.display == "none" ) {
document.getElementById("loginTable").style.display="";
} else {
document.getElementById("loginTable").style.display="none";
}
@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls
:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit
:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit
:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
To access the root directory from outside the controller you can simply inject %kernel.root_dir%
as an argument in your services configuration.
service_name:
class: Namespace\Bundle\etc
arguments: ['%kernel.root_dir%']
Then you can get the web root in the class constructor:
public function __construct($rootDir)
{
$this->webRoot = realpath($rootDir . '/../web');
}
There's no specific answer. It depends on the platform. It is implementation-defined. It can be 2, 4 or something else.
The idea behind int
was that it was supposed to match the natural "word" size on the given platform: 16 bit on 16-bit platforms, 32 bit on 32-bit platforms, 64 bit on 64-bit platforms, you get the idea. However, for backward compatibility purposes some compilers prefer to stick to 32-bit int
even on 64-bit platforms.
The time of 2-byte int
is long gone though (16-bit platforms?) unless you are using some embedded platform with 16-bit word size. Your textbooks are probably very old.
I had a similar problem: JUnit tests failed in Maven Surefire but passed in Eclipse when I used JUnit library version 4.11.0 from SpringSource Bundle Repository. Particulary:
<dependency>
<groupId>org.junit</groupId>
<artifactId>com.springsource.org.junit</artifactId>
<version>4.11.0</version>
</dependency>
Then I replaced it with following JUnit library version 4.11 and everything works fine.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
For the listed three conditions only, these expressions might work also:
^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$
If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:
123451234
12345 1234
12345 1234
this expression for instance would be a secondary option with less constraints:
^\d{5}([-]|\s*)?(\d{4})?$
jex.im visualizes regular expressions:
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345 1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
IntelliJ IDEA detects errors and warnings in the current file on the fly (unless Power Save Mode is activated in the File
menu).
Errors in other files and in the project view will be shown after Build
| Make
and listed in the Messages tool window.
For Bazel users: Project errors will show on Bazel Problems tool window after running Compile Project
(Ctrl/Cmd+F9)
To navigate between errors use Navigate
| Next Highlighted Error
(F2) / Previous Highlighted Error
(Shift+F2).
Error Stripe Mark color can be changed here: