I'm one of the developers who helped create Sass.
The difference is UI. Underneath the textual exterior they are identical. This is why sass and scss files can import each other. Actually, Sass has four syntax parsers: scss, sass, CSS, and less. All of these convert a different syntax into an Abstract Syntax Tree which is further processed into CSS output or even onto one of the other formats via the sass-convert tool.
Use the syntax you like the best, both are fully supported and you can change between them later if you change your mind.
SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)
Never returns any records unless eotm_dyn
is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn
like
SELECT * from employees
WHERE NOT EXISTS (
SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)
assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.
<form method="post" action="addMember.php" enctype="multipart/form-data">
<p>
Please Enter the Band Members Name.
</p>
<p>
Band Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Band Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
</p>
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
</form>
save it as addMember.php
<?php
//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];
// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
in the above code one little bug ,i fixed that bug.
This simplistic version also works.
public void UploadMultipart(byte[] file, string filename, string contentType, string url)
{
var webClient = new WebClient();
string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
var fileData = webClient.Encoding.GetString(file);
var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, filename, contentType, fileData);
var nfile = webClient.Encoding.GetBytes(package);
byte[] resp = webClient.UploadData(url, "POST", nfile);
}
Add any extra required headers if needed.
It's easy to create this yourself
In your layout include the following ProgressBar
with a specific drawable (note you should get the width from dimensions instead). The max value is important here:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="500"
android:progress="0"
android:progressDrawable="@drawable/circular" />
Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius
instead of innerRadiusRatio
) and thickness values.
circular (Pre Lollipop OR API Level < 21)
<shape
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
circular ( >= Lollipop OR API Level >= 21)
<shape
android:useLevel="true"
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
useLevel is "false" by default in API Level 21 (Lollipop) .
Start Animation
Next in your code use an ObjectAnimator
to animate the progress field of the ProgessBar
of your layout.
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
Stop Animation
progressBar.clearAnimation();
P.S. unlike examples above, it give smooth animation.
For anyone looking for a solution on a modern stack:
import jsonp from 'jsonp';
import queryString from 'query-string';
// formData being an object with your form data like:
// { EMAIL: '[email protected]' }
jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
console.log(err);
console.log(data);
});
<asp:RadioButtonList ID="rblRequestType">
<asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
<asp:ListItem Value="Value2">Value2</asp:ListItem>
</asp:RadioButtonList>
You can set checked like this.
var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");
radio0.checked = true;
radio1.checked = true;
As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC
, you may end up with something like this:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
Or, if you prefer to use getConnection(url, "sa", "s3cr3t")
:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
EDIT: Regarding your Connection refused
error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.
Integer.valueOf()
returns an Integer object, while Integer.parseInt()
returns an int
primitive.
Without using find
:
du -a $directory | awk '{print $2}' | grep '\.in$'
As there is nothing in this question (but its age) that requires a solution in Windows.Forms
, here is a way to do this in WPF
in code-behind.
TextBlock tb = new TextBlock();
tb.Inlines.Add(new Run("Background indicates packet repeat status:"));
tb.Inlines.Add(new LineBreak());
tb.Inlines.Add(new LineBreak());
Run r = new Run("White");
r.Background = Brushes.White;
r.ToolTip = "This word has a White background";
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Identical Packet received at this time."));
tb.Inlines.Add(new LineBreak());
r = new Run("SkyBlue");
r.ToolTip = "This word has a SkyBlue background";
r.Background = new SolidColorBrush(Colors.SkyBlue);
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Original Packet received at this time."));
myControl.Content = tb;
I also experienced an issue like this, my workspace was corrupted and didn't do all the important things anymore.
For some reason, I had a corrupt resource on one of my projects. It didn't show up in the package tree, but it did show in the error log in Eclipse as
Error while creating a link for external folder X:\somefolder
After checking every project (because the error didn't point to one), I indeed found this resource in one of the build paths (in Configure Build Path menu it did show an error icon!) and deleted it.
See Eclipse (Kepler) Workspace acting weird (type hierarchy, searching for references not working) for a wider description of my issue if you're experiencing something similar.
Posted this for future developers to reference.
An IEEE double has 53 significant bits (that's the value of DBL_MANT_DIG
in <cfloat>
). That's approximately 15.95 decimal digits (log10(253)); the implementation sets DBL_DIG
to 15, not 16, because it has to round down. So you have nearly an extra decimal digit of precision (beyond what's implied by DBL_DIG==15
) because of that.
The nextafter()
function computes the nearest representable number to a given number; it can be used to show just how precise a given number is.
This program:
#include <cstdio>
#include <cfloat>
#include <cmath>
int main() {
double x = 1.0/7.0;
printf("FLT_RADIX = %d\n", FLT_RADIX);
printf("DBL_DIG = %d\n", DBL_DIG);
printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}
gives me this output on my system:
FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.14285714285714282
0.14285714285714285
0.14285714285714288
(You can replace %.17g
by, say, %.64g
to see more digits, none of which are significant.)
As you can see, the last displayed decimal digit changes by 3 with each consecutive value. The fact that the last displayed digit of 1.0/7.0
(5
) happens to match the mathematical value is largely coincidental; it was a lucky guess. And the correct rounded digit is 6
, not 5
. Replacing 1.0/7.0
by 1.0/3.0
gives this output:
FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.33333333333333326
0.33333333333333331
0.33333333333333337
which shows about 16 decimal digits of precision, as you'd expect.
Both unix2dos and dos2unix is available in windows with gitbash. You can use the following command to perform UNIX(LF) -> DOS(CRLF) conversion. Hence, you will not get the warning.
unix2dos filename
or
dos2unix -D filename
But, don't run this command on any existing CRLF file, then you will get empty newlines every second line.
dos2unix -D filename
will not work with every operating system. Please check this link for compatibility.
If for some reason you need to force the command then use --force
. If it says invalid then use -f
.
You almost never want to use Read Uncommited
since it's not really ACID
compliant. Read Commmited
is a good default starting place. Repeatable Read
is probably only needed in reporting, rollup or aggregation scenarios. Note that many DBs, postgres included don't actually support Repeatable Read, you have to use Serializable
instead. Serializable
is useful for things that you know have to happen completely independently of anything else; think of it like synchronized
in Java. Serializable goes hand in hand with REQUIRES_NEW
propagation.
I use REQUIRES
for all functions that run UPDATE or DELETE queries as well as "service" level functions. For DAO level functions that only run SELECTs, I use SUPPORTS
which will participate in a TX if one is already started (i.e. being called from a service function).
UsedRange represents not only nonempty cells, but also formatted cells without any value. And that's why you should be very vigilant.
<Snippet name="abc">
name is an attribute, not an element. That's why it's failing. Look into using SetAttribute on the <Snippet>
element.
root.SetAttribute("name", "name goes here");
is the code you need with what you have.
Don't forget about tools:context=".YouClassName"
property in ScrollView
.
It is what was causing my application to crash.
In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.
The lesson learned is "always use homogeneous development and deployment databases!"
Just say :
git commit --amend -m "New commit message"
and then
git push --force
This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180
and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.
Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.
You can always use normal functions:
function myPrivateFunction() {
console.log("My property: " + this.prop);
}
class MyClass() {
constructor() {
this.prop = "myProp";
myPrivateFunction.bind(this)();
}
}
new MyClass(); // 'My property: myProp'
@MaxPython The answer above is missing ":"
try:
#do something
except:
# print 'error/exception'
def printError(e): print e
From number to currency string is easy through Number.prototype.toLocaleString. However the reverse seems to be a common problem. The thousands separator and decimal point may not be obtained in the JS standard.
In this particular question the thousands separator is a white space " "
but in many cases it can be a period "."
and decimal point can be a comma ","
. Such as in 1 000 000,00
or 1.000.000,00
. Then this is how i convert it into a proper floating point number.
var price = "1 000.000,99",
value = +price.replace(/(\.|\s)|(\,)/g,(m,p1,p2) => p1 ? "" : ".");
console.log(value);
_x000D_
So the replacer callback takes "1.000.000,00"
and converts it into "1000000.00"
. After that +
in the front of the resulting string coerces it into a number.
This function is actually quite handy. For instance if you replace the p1 = ""
part with p1 = ","
in the callback function, an input of 1.000.000,00
would result 1,000,000.00
All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives
<li ng-repeat="select in Items">
<foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found
It's a great idea to use cURL as suggested by rojoca.
Here is an example. You can monitor text.txt while the script is running in background:
<?php
function doCurl($begin)
{
echo "Do curl<br />\n";
$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = preg_replace('/\?.*/', '', $url);
$url .= '?begin='.$begin;
echo 'URL: '.$url.'<br>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo 'Result: '.$result.'<br>';
curl_close($ch);
}
if (empty($_GET['begin'])) {
doCurl(1);
}
else {
while (ob_get_level())
ob_end_clean();
header('Connection: close');
ignore_user_abort();
ob_start();
echo 'Connection Closed';
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
$begin = $_GET['begin'];
$fp = fopen("text.txt", "w");
fprintf($fp, "begin: %d\n", $begin);
for ($i = 0; $i < 15; $i++) {
sleep(1);
fprintf($fp, "i: %d\n", $i);
}
fclose($fp);
if ($begin < 10)
doCurl($begin + 1);
}
?>
Lambda expression can be passed as a argument.To pass a lambda expression as an argument the type of the parameter (which receives the lambda expression as an argument) must be of functional interface type.
If there is a functional interface -
interface IMyFunc {
boolean test(int num);
}
And there is a filter method which adds the int in the list only if it is greater than 5. Note here that filter method has funtional interface IMyFunc as one of the parameter. In that case lambda expression can be passed as an argument for the method parameter.
public class LambdaDemo {
public static List<Integer> filter(IMyFunc testNum, List<Integer> listItems) {
List<Integer> result = new ArrayList<Integer>();
for(Integer item: listItems) {
if(testNum.test(item)) {
result.add(item);
}
}
return result;
}
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(4);
myList.add(6);
myList.add(7);
// calling filter method with a lambda expression
// as one of the param
Collection<Integer> values = filter(n -> n > 5, myList);
System.out.println("Filtered values " + values);
}
}
you can slide up and down any view or layout by using bellow code in android app
boolean isClicked=false;
LinearLayout mLayoutTab = (LinearLayout)findViewById(R.id.linearlayout);
if(isClicked){
isClicked = false;
mLayoutTab.animate()
.translationYBy(120)
.translationY(0)
.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
}else{
isClicked = true;
mLayoutTab.animate()
.translationYBy(0)
.translationY(120)
.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
}
This is my solution...
/*
this program is looking for CPU,Memory,Procs also u can look glibtop header there was a lot of usefull function have fun..
systeminfo.c
*/
#include <stdio.h>
#include <glibtop.h>
#include <glibtop/cpu.h>
#include <glibtop/mem.h>
#include <glibtop/proclist.h>
int main(){
glibtop_init();
glibtop_cpu cpu;
glibtop_mem memory;
glibtop_proclist proclist;
glibtop_get_cpu (&cpu);
glibtop_get_mem(&memory);
printf("CPU TYPE INFORMATIONS \n\n"
"Cpu Total : %ld \n"
"Cpu User : %ld \n"
"Cpu Nice : %ld \n"
"Cpu Sys : %ld \n"
"Cpu Idle : %ld \n"
"Cpu Frequences : %ld \n",
(unsigned long)cpu.total,
(unsigned long)cpu.user,
(unsigned long)cpu.nice,
(unsigned long)cpu.sys,
(unsigned long)cpu.idle,
(unsigned long)cpu.frequency);
printf("\nMEMORY USING\n\n"
"Memory Total : %ld MB\n"
"Memory Used : %ld MB\n"
"Memory Free : %ld MB\n"
"Memory Buffered : %ld MB\n"
"Memory Cached : %ld MB\n"
"Memory user : %ld MB\n"
"Memory Locked : %ld MB\n",
(unsigned long)memory.total/(1024*1024),
(unsigned long)memory.used/(1024*1024),
(unsigned long)memory.free/(1024*1024),
(unsigned long)memory.shared/(1024*1024),
(unsigned long)memory.buffer/(1024*1024),
(unsigned long)memory.cached/(1024*1024),
(unsigned long)memory.user/(1024*1024),
(unsigned long)memory.locked/(1024*1024));
int which,arg;
glibtop_get_proclist(&proclist,which,arg);
printf("%ld\n%ld\n%ld\n",
(unsigned long)proclist.number,
(unsigned long)proclist.total,
(unsigned long)proclist.size);
return 0;
}
makefile is
CC=gcc
CFLAGS=-Wall -g
CLIBS=-lgtop-2.0 -lgtop_sysdeps-2.0 -lgtop_common-2.0
cpuinfo:cpu.c
$(CC) $(CFLAGS) systeminfo.c -o systeminfo $(CLIBS)
clean:
rm -f systeminfo
In terms of the algorithms themselves I would go with AES, for the simple reason is that it's been accepted by NIST and will be peer reviewed and cryptanalyzed for years. However I would suggest that in practical applications, unless you're storing some file that the government wants to keep secret (in which case the NSA would probably supply you with a better algorithm than both AES and Blowfish), using either of these algorithms won't make too much of a difference. All the security should be in the key, and both of these algorithms are resistant to brute force attacks. Blowfish has only shown to be weak on implementations that don't make use of the full 16 rounds. And while AES is newer, that fact should make you lean more towards BlowFish (if you were only taking age into consideration). Think of it this way, BlowFish has been around since the 90's and nobody (that we know of) has broken it yet....
Here is what I would pose to you... instead of looking at these two algorithms and trying to choose between the algorithm, why don't you look at your key generation scheme. A potential attacker who wants to decrypt your file is not going to sit there and come up with a theoretical set of keys that can be used and then do a brute force attack that can take months. Instead he is going to exploit something else, such as attacking your server hardware, reverse engineering your assembly to see the key, trying to find some config file that has the key in it, or maybe blackmailing your friend to copy a file from your computer. Those are going to be where you are most vulnerable, not the algorithm.
For those using Yarn as their package manager instead of npm:
yarn global add babel-cli
No one has mentioned this yet, and this may not be a common problem, but I had a similar problem with Xcode 5: Make sure you have a default keychain selected in the Mac's Keychain Access. I trying out a fresh install of Mountain Lion and deleted one keychain, which happened to be the default. After setting another keychain as the default (right-click on the keychain and select Make Keychain "Keychain_name" default"), Xcode was able to set up the valid signing identities.
You can use String.Join
. If you have a List<string>
then you can call ToArray
first:
List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());
In .NET 4 you don't need the ToArray
anymore, since there is an overload of String.Join
that takes an IEnumerable<string>
.
Results:
John, Anna, Monica
I'm not aware of any plotting method which takes arrays or lists but you could use annotate()
while iterating over the values in n
.
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]
fig, ax = plt.subplots()
ax.scatter(z, y)
for i, txt in enumerate(n):
ax.annotate(txt, (z[i], y[i]))
There are a lot of formatting options for annotate()
, see the matplotlib website:
getParentFragmentManager().setFragmentResultListener
is the 2020 way of doing this. Your only limitation is to use a bundle to pass the data. Check out the docs for more info and examples.
Some other ways
getActivity()
and cast it to the shared activity between your fragments, then use it as a bridge to pass the data. This solution is highly not recommended because of the cupelling it requires between the activity and the fragments, but it used to be the popular way of doing this back in the KitKat days...FragmentManager
is that it's not limited to Bundles. The downside, however, is that you may run into edge cases bugs where you mess up the activity life cycle and get exceptions like IllegalStateException
when the fragment manager is in the middle of saving state or the activity were destroyed. Also, it does not support cross-processing communication.In your database upload file, add the followin line before any line:
SET NAMES utf8;
And your problem should be solved.
Sometimes this problem happens when you upload/download the fonts using the wrong FTP method. Fonts must be FTP-ed using binary method, not ASCII. (Depending on your mood, it may feel counterintuitive, lol). If you ftp the font files using ASCII method, you can get this error message. If you ftp your files with an 'auto' method, and you get this error message, try ftp forcing the binary method.
Why should you need manipulations with packages.config or .csproj files?
The error explicitly says: Use NuGet Package Restore to download them.
Use it accordingly this instruction: https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore-troubleshooting:
Quick solution for Visual Studio users
1.Select the Tools > NuGet Package Manager > Package Manager Settings menu command.
2.Set both options under Package Restore.
3.Select OK.
4.Build your project again.
If you have multiple columns in your dataframe and would like to remove all rows that have outliers in at least one column, the following expression would do that in one shot.
df = pd.DataFrame(np.random.randn(100, 3))
from scipy import stats
df[(np.abs(stats.zscore(df)) < 3).all(axis=1)]
description:
zscore
, df[0]
for example, and remove .all(axis=1)
.df[(np.abs(stats.zscore(df[0])) < 3)]
follow some steps below:
open cygwin setup again
choose catagory on view tab
fill "make" in search tab
expand devel
find "make: a GNU version of the 'make' ultility", click to install
Done!
Here is why the original expression didn't work.
From man bash:
Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.
So, brace expansion is something done early as a purely textual macro operation, before parameter expansion.
Shells are highly optimized hybrids between macro processors and more formal programming languages. In order to optimize the typical use cases, the language is made rather more complex and some limitations are accepted.
Recommendation
I would suggest sticking with Posix1 features. This means using for i in <list>; do
, if the list is already known, otherwise, use while
or seq
, as in:
#!/bin/sh
limit=4
i=1; while [ $i -le $limit ]; do
echo $i
i=$(($i + 1))
done
# Or -----------------------
for i in $(seq 1 $limit); do
echo $i
done
Use repr:
a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'
Note you do not get \s
for a space. I hope that was a typo...?
But if you really do want \s
for spaces, you could do this:
print(repr(a).replace(' ',r'\s'))
The following should do what you want.
@keyframes marquee {
from { text-indent: 100% }
to { text-indent: -100% }
}
Nope, you have to open a browser atleast once to create your username
on GitHub, once created, you can leverage GitHub API to create repositories from command line, following below command:
curl -u 'github-username' https://api.github.com/user/repos -d '{"name":"repo-name"}'
For example:
curl -u 'arpitaggarwal' https://api.github.com/user/repos -d '{"name":"command-line-repo"}'
By adb shell input keyevent
, either an event_code
or a string
will be sent to the device.
usage: input [text|keyevent]
input text <string>
input keyevent <event_code>
Some possible values for event_code
are:
0 --> "KEYCODE_UNKNOWN"
1 --> "KEYCODE_MENU"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "TAG_LAST_KEYCODE"
The sendevent
utility sends touch or keyboard events, as well as other events for simulating the hardware events. Refer to this article for details: Android, low level shell click on screen.
Here is a solution without relying on any server-side control, just like OP has described in the question.
Client side HTML code:
<form action="upload.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="UploadedFile" />
</form>
Page_Load method of upload.aspx :
if(Request.Files["UploadedFile"] != null)
{
HttpPostedFile MyFile = Request.Files["UploadedFile"];
//Setting location to upload files
string TargetLocation = Server.MapPath("~/Files/");
try
{
if (MyFile.ContentLength > 0)
{
//Determining file name. You can format it as you wish.
string FileName = MyFile.FileName;
//Determining file size.
int FileSize = MyFile.ContentLength;
//Creating a byte array corresponding to file size.
byte[] FileByteArray = new byte[FileSize];
//Posted file is being pushed into byte array.
MyFile.InputStream.Read(FileByteArray, 0, FileSize);
//Uploading properly formatted file to server.
MyFile.SaveAs(TargetLocation + FileName);
}
}
catch(Exception BlueScreen)
{
//Handle errors
}
}
One more way of convenient placement of Environment.NewLine in format string. The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine
Usage
" X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
gives:
X=1
Y=2
X+Y=3
Code
///<summary>
/// Use "string".FormatIt(...) instead of string.Format("string, ...)
/// Use {nl} in text to insert Environment.NewLine
///</summary>
///<exception cref="ArgumentNullException">If format is null</exception>
[StringFormatMethod("format")]
public static string FormatIt(this string format, params object[] args)
{
if (format == null) throw new ArgumentNullException("format");
return string.Format(format.Replace("{nl}", Environment.NewLine), args);
}
Note
If you want ReSharper to highlight your parameters, add attribute to the method above
[StringFormatMethod("format")]
This implementation is obviously less efficient than just String.Format
Maybe one, who interested in this question would be interested in the next question too: Named string formatting in C#
Sometimes web browsers seems to be more forgiving if you use the Unicode string ­
rather than the ­
entity.
util.format does this.
It will be part of v0.5.3 and can be used like this:
var uri = util.format('http%s://%s%s',
(useSSL?'s':''), apiBase, path||'/');
gem install pg -- --with-pg-config=/usr/pgsql-9.1/bin/pg_config
you can add the following code : the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
In simple words,
applicationContext.xml
defines the beans that are shared among all the servlets. If your application have more than one servlet, then defining the common resources in the applicationContext.xml
would make more sense.
spring-servlet.xml
defines the beans that are related only to that servlet. Here it is the dispatcher servlet. So, your Spring MVC controllers must be defined in this file.
There is nothing wrong in defining all the beans in the spring-servlet.xml
if you are running only one servlet in your web application.
With recent version of Pandas, you can do
df.N.hist(by=df.Letter)
Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.
Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).
http://connect.microsoft.com/PowerShell/feedback/details/376207/
They suggest using --%
as a way to force PowerShell to stop trying to interpret the text to the right.
For example:
MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj
A new byte array will automatically be initialized with all zeroes. You don't have to do anything.
The more general approach to initializing with other values, is to use the Arrays
class.
import java.util.Arrays;
byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );
You may find the HitchHiker's Guide to Packaging helpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the setup.py
file. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.
My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.
If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF
trick:
DECLARE @CodeNameString varchar(100)
SELECT
@CodeNameString = STUFF( (SELECT ',' + CodeName
FROM dbo.AccountCodes
ORDER BY Sort
FOR XML PATH('')),
1, 1, '')
The FOR XML PATH('')
basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3
etc.) and the STUFF
puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.
UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <
, >
or &
, then my current solution will in fact encode those into <
, >
, and &
.
If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.
In case you were looking for an older version of .NET then use:
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result As New List(Of Integer)
For i As Integer = 0 To arr.Length
If arr(i).Contains("ra") Then result.Add(i)
Next
End Sub
End Module
Create enviroment variable in your .bashrc
export RUNSERVER_PORT=8010
Create alias
alias runserver='django-admin runserver $RUNSERVER_PORT'
Im using zsh and virtualenvs wrapper. I put export in projects postactivate script and asign port for every project.
workon someproject
runserver
Errors and exceptions in PowerShell are structured objects. The error message you see printed on the console is actually a formatted message with information from several elements of the error/exception object. You can (re-)construct it yourself like this:
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId
$formatstring -f $fields
If you just want the error message displayed in your catch
block you can simply echo the current object variable (which holds the error at that point):
try {
...
} catch {
$_
}
If you need colored output use Write-Host
with a formatted string as described above:
try {
...
} catch {
...
Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
}
With that said, usually you don't want to just display the error message as-is in an exception handler (otherwise the -ErrorAction Stop
would be pointless). The structured error/exception objects provide you with additional information that you can use for better error control. For instance you have $_.Exception.HResult
with the actual error number. $_.ScriptStackTrace
and $_.Exception.StackTrace
, so you can display stacktraces when debugging. $_.Exception.InnerException
gives you access to nested exceptions that often contain additional information about the error (top level PowerShell errors can be somewhat generic). You can unroll these nested exceptions with something like this:
$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
$e = $e.InnerException
$msg += "`n" + $e.Message
}
$msg
In your case the information you want to extract seems to be in $_.ErrorDetails.Message
. It's not quite clear to me if you have an object or a JSON string there, but you should be able to get information about the types and values of the members of $_.ErrorDetails
by running
$_.ErrorDetails | Get-Member
$_.ErrorDetails | Format-List *
If $_.ErrorDetails.Message
is an object you should be able to obtain the message string like this:
$_.ErrorDetails.Message.message
otherwise you need to convert the JSON string to an object first:
$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message
Depending what kind of error you're handling, exceptions of particular types might also include more specific information about the problem at hand. In your case for instance you have a WebException
which in addition to the error message ($_.Exception.Message
) contains the actual response from the server:
PS C:\> $e.Exception | Get-Member TypeName: System.Net.WebException Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj), bool _Exception.E... GetBaseException Method System.Exception GetBaseException(), System.Excep... GetHashCode Method int GetHashCode(), int _Exception.GetHashCode() GetObjectData Method void GetObjectData(System.Runtime.Serialization.S... GetType Method type GetType(), type _Exception.GetType() ToString Method string ToString(), string _Exception.ToString() Data Property System.Collections.IDictionary Data {get;} HelpLink Property string HelpLink {get;set;} HResult Property int HResult {get;} InnerException Property System.Exception InnerException {get;} Message Property string Message {get;} Response Property System.Net.WebResponse Response {get;} Source Property string Source {get;set;} StackTrace Property string StackTrace {get;} Status Property System.Net.WebExceptionStatus Status {get;} TargetSite Property System.Reflection.MethodBase TargetSite {get;}
which provides you with information like this:
PS C:\> $e.Exception.Response IsMutuallyAuthenticated : False Cookies : {} Headers : {Keep-Alive, Connection, Content-Length, Content-T...} SupportsHeaders : True ContentLength : 198 ContentEncoding : ContentType : text/html; charset=iso-8859-1 CharacterSet : iso-8859-1 Server : Apache/2.4.10 LastModified : 17.07.2016 14:39:29 StatusCode : NotFound StatusDescription : Not Found ProtocolVersion : 1.1 ResponseUri : http://www.example.com/ Method : POST IsFromCache : False
Since not all exceptions have the exact same set of properties you may want to use specific handlers for particular exceptions:
try {
...
} catch [System.ArgumentException] {
# handle argument exceptions
} catch [System.Net.WebException] {
# handle web exceptions
} catch {
# handle all other exceptions
}
If you have operations that need to be done regardless of whether an error occured or not (cleanup tasks like closing a socket or a database connection) you can put them in a finally
block after the exception handling:
try {
...
} catch {
...
} finally {
# cleanup operations go here
}
Your printf
needs a format string:
printf("%d\n", x);
This reference page gives details on how to use printf
and related functions.
FYI: I also noticed I can mess up a perfectly working spring boot app and prevent it from serving contents from the static folder, if I add a bad rest controller like so
@RestController
public class BadController {
@RequestMapping(method= RequestMethod.POST)
public String someMethod(@RequestParam(value="date", required=false)String dateString, Model model){
return "foo";
}
}
In this example, after adding the bad controller to the project, when the browser asks for a file available in static folder, the error response is '405 Method Not Allowed'.
Notice paths are not mapped in the bad controller example.
You can easily write the method to do that :
public static String toCamelCase(final String init) {
if (init == null)
return null;
final StringBuilder ret = new StringBuilder(init.length());
for (final String word : init.split(" ")) {
if (!word.isEmpty()) {
ret.append(Character.toUpperCase(word.charAt(0)));
ret.append(word.substring(1).toLowerCase());
}
if (!(ret.length() == init.length()))
ret.append(" ");
}
return ret.toString();
}
Install the favicon middleware and then do:
var favicon = require('serve-favicon');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
Or better, using the path
module:
app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
(note that this solution will work in express 3 apps as well)
According to the API, .favicon
accepts a location parameter:
app.use(express.favicon("public/images/favicon.ico"));
Most of the time, you might want this (as vsync suggested):
app.use(express.favicon(__dirname + '/public/images/favicon.ico'));
Or better yet, use the path
module (as Druska suggested):
app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico')));
According to the package description:
ETag
based on the contents of the icon, rather than file system properties.Content-Type
.System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath");
int count = dir.GetFiles().Length;
You can use this.
Webclient client = new Webclient();
string content = client.DownloadString(url);
Pass the URL of page who you want to get. You can parse the result using htmlagilitypack.
function getStringReminder(str, substr, occ) {
let index = str.indexOf(substr);
let preindex = '';
let i = 1;
while (index !== -1) {
preIndex = index;
if (occ == i) {
break;
}
index = str.indexOf(substr, index + 1)
i++;
}
return preIndex;
}
console.log(getStringReminder('bcdefgbcdbcd', 'bcd', 3));
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
if you're intereased only in bash the "for(( ... ))" solution presented above is the best, but if you want something POSIX SH compliant that will work on all unices you'll have to use "expr" and "while", and that's because "(())" or "seq" or "i=i+1" are not that portable among various shells
alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");
or %0D%0A in a url
The apps UI only works for panels.
The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.
Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.
Alternatively you can also draw the button somewhere else and insert it as an image.
More info: https://developers.google.com/apps-script/guides/menus
I want to chime in here even though this question has already been answered correctly by @pscl in case anyone else runs into the same issue I did. Out of the 4 methods give I chose to use the es6 syntax with arrow functions due to it's conciseness and lack of dependence on external libraries:
Using Array.prototype.filter with ES6 Arrow Functions
removeItem(index) {
this.setState((prevState) => ({
data: prevState.data.filter((_, i) => i != index)
}));
}
As you can see I made a slight modification to ignore the type of index (!==
to !=
) because in my case I was retrieving the index from a string field.
Another helpful point if you're seeing weird behavior when removing an element on the client side is to NEVER use the index of an array as the key for the element:
// bad
{content.map((content, index) =>
<p key={index}>{content.Content}</p>
)}
When React diffs with the virtual DOM on a change, it will look at the keys to determine what has changed. So if you're using indices and there is one less in the array, it will remove the last one. Instead, use the id's of the content as keys, like this.
// good
{content.map(content =>
<p key={content.id}>{content.Content}</p>
)}
The above is an excerpt from this answer from a related post.
Happy Coding Everyone!
This should work for everyone, any screen resolutions:
.modal-body {
max-height: calc(100vh - 143px);
overflow-y: auto; }
First, count your modal header and footer height, in my case I have H4
heading so I have them on 141px
, already counted default modal margin in 20px(top+bottom)
.
So that subtract 141px
is the max-height
for my modal height, for the better result there are both border top and bottom by 1px
, for this, 143px
will work perfectly.
In some case of styling you may like to use overflow-y: auto;
instead of overflow-y: scroll;
, try it.
Try it, and you get the best result in both computer or mobile devices.
If you have a heading larger than H4
, recount it see how much px
you would like to subtract.
If you don't know what I am telling, just change the number of 143px
, see what is the best result for your case.
Last, I'd suggest have it an inline CSS.
Probably good for small results, works in all versions of TSQL:
SELECT
*
FROM
(SELECT TOP (N) *
FROM
(SELECT TOP (M + N - 1)
FROM
Table
ORDER BY
MyColumn) qasc
ORDER BY
MyColumn DESC) qdesc
ORDER BY
MyColumn
The reason why Neil's suggestion results in a fullscreen DatePicker
is the choice of parent theme:
<!-- Theme.AppCompat.Light is not a dialog theme -->
<style name="DialogTheme" parent="**Theme.AppCompat.Light**">
<item name="colorAccent">@color/blue_500</item>
</style>
Moreover, if you go this route, you have to specify the theme while creating the DatePickerDialog
:
// R.style.DialogTheme
new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
This, in my opinion, is not good. One should try to keep the styling out of java and inside styles.xml/themes.xml.
I do agree that Neil's suggestion, with a bit of change (changing the parent theme to say, Theme.Material.Light.Dialog
) will get you the desired result. But, here's the other way:
On first inspection, we come across datePickerStyle
which defines things such as: headerBackground
(what you are trying to change), dayOfWeekBackground
, and a few other text-colors and text-styles.
Overriding this attribute in your app's theme will not work. DatePickerDialog
uses a separate theme assignable by the attribute datePickerDialogTheme
. So, for our changes to take affect, we must override datePickerStyle
inside an overriden datePickerDialogTheme
.
Here we go:
Override datePickerDialogTheme
inside your app's base theme:
<style name="AppBaseTheme" parent="android:Theme.Material.Light">
....
<item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>
Define MyDatePickerDialogTheme
. The choice of parent theme will depend on what your app's base theme is: it could be either Theme.Material.Dialog
or Theme.Material.Light.Dialog
:
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>
We have overridden datePickerStyle
with the style MyDatePickerStyle
. The choice of parent will once again depend on what your app's base theme is: either Widget.Material.DatePicker
or Widget.Material.Light.DatePicker
. Define it as per your requirements:
<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">@color/chosen_header_bg_color</item>
</style>
Currently, we are only overriding headerBackground
which by default is set to ?attr/colorAccent
(this is also why Neil suggestion works in changing the background). But there's quite a lot of customization possible:
dayOfWeekBackground
dayOfWeekTextAppearance
headerMonthTextAppearance
headerDayOfMonthTextAppearance
headerYearTextAppearance
headerSelectedTextColor
yearListItemTextAppearance
yearListSelectorColor
calendarTextColor
calendarSelectedTextColor
If you don't want this much control (customization), you don't need to override datePickerStyle
. colorAccent
controls most of the DatePicker's
colors. So, overriding just colorAccent
inside MyDatePickerDialogTheme
should work:
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:colorAccent">@color/date_picker_accent</item>
<!-- No need to override 'datePickerStyle' -->
<!-- <item name="android:datePickerStyle">@style/MyDatePickerStyle</item> -->
</style>
Overriding colorAccent
gives you the added benefit of changing OK
& CANCEL
text colors as well. Not bad.
This way you don't have to provide any styling information to DatePickerDialog's
constructor. Everything has been wired properly:
DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
}, 2015, 5, 22);
dpd.show();
I just wanted to add one last option to what most people and articles mention. As mR_fr0g has stated, it's important to handle the interrupt correctly either by:
Propagating the InterruptException
Restore Interrupt state on Thread
Or additionally:
There is nothing wrong with handling the interrupt in a custom way depending on your circumstances. As an interrupt is a request for termination, as opposed to a forceful command, it is perfectly valid to complete additional work to allow the application to handle the request gracefully. For example, if a Thread is Sleeping, waiting on IO or a hardware response, when it receives the Interrupt, then it is perfectly valid to gracefully close any connections before terminating the thread.
I highly recommend understanding the topic, but this article is a good source of information: http://www.ibm.com/developerworks/java/library/j-jtp05236/
What is the line which gives exception ??
The reason for this is because the element to which you have referred is removed from the DOM structure
I was facing the same problem while working with IEDriver. The reason was because javascript loaded the element one more time after i have referred so my date reference pointed to an unexisting object even if it was right their on UI. I used the following workaround.
try {
WebElement date = driver.findElement(By.linkText(Utility.getSheetData(path, 7, 1, 2)));
date.click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
WebElement date = driver.findElement(By.linkText(Utility.getSheetData(path, 7, 1, 2)));
date.click();
}
See if the same can help you !
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
Jquery One-liners:
ES6 + jQuery:
$('#select').append([...Array(100).keys()].map((i,j) => `< option >${i}</option >`))
Lodash + jQuery:
$('#select').append(_.range(100).map(function(i,j){ return $('<option>',{text:i})}))
The model fields contained by _meta are listed in multiple locations as lists of the respective field objects. It may be easier to work with them as a dictionary where the keys are the field names.
In my opinion, this is most irredundant and expressive way to collect and organize the model field objects:
def get_model_fields(model):
fields = {}
options = model._meta
for field in sorted(options.concrete_fields + options.many_to_many + options.virtual_fields):
fields[field.name] = field
return fields
(See This example usage in django.forms.models.fields_for_model.)
Http 415 Media Unsupported
is responded back only when the content type header you are providing is not supported by the application.
With POSTMAN, the Content-type
header you are sending is Content type 'multipart/form-data
not application/json
. While in the ajax code you are setting it correctly to application/json
. Pass the correct Content-type header in POSTMAN and it will work.
I should like to take a step back and a modern look at this 10 years old question. The classes mentioned, Date
and XMLGregorianCalendar
, are old now. I challenge the use of them and offer alternatives.
Date
was always poorly designed and is more than 20 years old. This is simple: don’t use it.XMLGregorianCalendar
is old too and has an old-fashioned design. As I understand it, it was used for producing dates and times in XML format for XML documents. Like 2009-05-07T19:05:45.678+02:00
or 2009-05-07T17:05:45.678Z
. These formats agree well enough with ISO 8601 that the classes of java.time, the modern Java date and time API, can produce them, which we prefer.For many (most?) purposes the modern replacement for a Date
will be an Instant
. An Instant
is a point in time (just as a Date
is).
Instant yourInstant = // ...
System.out.println(yourInstant);
An example output from this snippet:
2009-05-07T17:05:45.678Z
It’s the same as the latter of my example XMLGregorianCalendar
strings above. As most of you know, it comes from Instant.toString
being implicitly called by System.out.println
. With java.time, in many cases we don’t need the conversions that in the old days we made between Date
, Calendar
, XMLGregorianCalendar
and other classes (in some cases we do need conversions, though, I am showing you a couple in the next section).
Neither a Date
nor in Instant
has got a time zone nor a UTC offset. The previously accepted and still highest voted answer by Ben Noland uses the JVMs current default time zone for selecting the offset of the XMLGregorianCalendar
. To include an offset in a modern object we use an OffsetDateTime
. For example:
ZoneId zone = ZoneId.of("America/Asuncion");
OffsetDateTime dateTime = yourInstant.atZone(zone).toOffsetDateTime();
System.out.println(dateTime);
2009-05-07T13:05:45.678-04:00
Again this conforms with XML format. If you want to use the current JVM time zone setting again, set zone
to ZoneId.systemDefault()
.
There are more ways to convert Instant
to XMLGregorianCalendar
. I will present a couple, each with its pros and cons. First, just as an XMLGregorianCalendar
produces a string like 2009-05-07T17:05:45.678Z
, it can also be built from such a string:
String dateTimeString = yourInstant.toString();
XMLGregorianCalendar date2
= DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTimeString);
System.out.println(date2);
2009-05-07T17:05:45.678Z
Pro: it’s short and I don’t think it gives any surprises. Con: To me it feels like a waste formatting the instant into a string and parsing it back.
ZonedDateTime dateTime = yourInstant.atZone(zone);
GregorianCalendar c = GregorianCalendar.from(dateTime);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
System.out.println(date2);
2009-05-07T13:05:45.678-04:00
Pro: It’s the official conversion. Controlling the offset comes naturally. Con: It goes through more steps and is therefore longer.
If you got an old-fashioned Date
object from a legacy API that you cannot afford to change just now, convert it to Instant
:
Instant i = yourDate.toInstant();
System.out.println(i);
Output is the same as before:
2009-05-07T17:05:45.678Z
If you want to control the offset, convert further to an OffsetDateTime
in the same way as above.
If you’ve got an old-fashioned Date
and absolutely need an old-fashioned XMLGregorianCalendar
, just use the answer by Ben Noland.
Although the question specifically describes installing 2.6, I would like to add some importants points to the excellent answers above in case someone comes across this. For the record, my case was that I was trying to install 2.7 on an ubuntu 10.04 box.
First, my motivation towards the methods described in all the answers here is that installing Python from deadsnake's ppa's has been a total failure. So building a local Python is the way to go.
Having tried so, I thought relying to the default installation of pip (with sudo apt-get install pip
) would be adequate. This unfortunately is wrong. It turned out that I was getting all shorts of nasty issues and eventually not being able to create a virtualenv.
Therefore, I highly recommend to install pip locally with wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py && python get-pip.py --user
. This related question gave me this hint.
Now if this doesn't work, make sure that libssl-dev
for Ubuntu or openssl-dev
for CentOS is installed. Install them with apt-get
or yum
and then re-build Python (no need to remove anything if already installed, do so on top). get-pip
complains about that, you can check so by running import ssl
on a py shell.
Last, don't forget to declare .local/bin
and local python to path, check with which pip
and which python
.
My suggestion would be to use RestSharp. You can make calls to REST services and have them cast into POCO objects with very little boilerplate code to actually have to parse through the response. This will not solve your particular error, but it answers your overall question of how to make calls to REST services. Having to change your code to use it should pay off in the ease of use and robustness moving forward. That is just my two cents though.
Example:
namespace RestSharpThingy
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using RestSharp;
public static class Program
{
public static void Main()
{
Uri baseUrl = new Uri("https://httpbin.org/");
IRestClient client = new RestClient(baseUrl);
IRestRequest request = new RestRequest("get", Method.GET) { Credentials = new NetworkCredential("testUser", "P455w0rd") };
request.AddHeader("Authorization", "Bearer qaPmk9Vw8o7r7UOiX-3b-8Z_6r3w0Iu2pecwJ3x7CngjPp2fN3c61Q_5VU3y0rc-vPpkTKuaOI2eRs3bMyA5ucKKzY1thMFoM0wjnReEYeMGyq3JfZ-OIko1if3NmIj79ZSpNotLL2734ts2jGBjw8-uUgKet7jQAaq-qf5aIDwzUo0bnGosEj_UkFxiJKXPPlF2L4iNJSlBqRYrhw08RK1SzB4tf18Airb80WVy1Kewx2NGq5zCC-SCzvJW-mlOtjIDBAQ5intqaRkwRaSyjJ_MagxJF_CLc4BNUYC3hC2ejQDoTE6HYMWMcg0mbyWghMFpOw3gqyfAGjr6LPJcIly__aJ5__iyt-BTkOnMpDAZLTjzx4qDHMPWeND-TlzKWXjVb5yMv5Q6Jg6UmETWbuxyTdvGTJFzanUg1HWzPr7gSs6GLEv9VDTMiC8a5sNcGyLcHBIJo8mErrZrIssHvbT8ZUPWtyJaujKvdgazqsrad9CO3iRsZWQJ3lpvdQwucCsyjoRVoj_mXYhz3JK3wfOjLff16Gy1NLbj4gmOhBBRb8rJnUXnP7rBHs00FAk59BIpKLIPIyMgYBApDCut8V55AgXtGs4MgFFiJKbuaKxq8cdMYEVBTzDJ-S1IR5d6eiTGusD5aFlUkAs9NV_nFw");
request.AddParameter("clientId", 123);
IRestResponse<RootObject> response = client.Execute<RootObject>(request);
if (response.IsSuccessful)
{
response.Data.Write();
}
else
{
Console.WriteLine(response.ErrorMessage);
}
Console.WriteLine();
string path = Assembly.GetExecutingAssembly().Location;
string name = Path.GetFileName(path);
request = new RestRequest("post", Method.POST);
request.AddFile(name, File.ReadAllBytes(path), name, "application/octet-stream");
response = client.Execute<RootObject>(request);
if (response.IsSuccessful)
{
response.Data.Write();
}
else
{
Console.WriteLine(response.ErrorMessage);
}
Console.ReadLine();
}
private static void Write(this RootObject rootObject)
{
Console.WriteLine("clientId: " + rootObject.args.clientId);
Console.WriteLine("Accept: " + rootObject.headers.Accept);
Console.WriteLine("AcceptEncoding: " + rootObject.headers.AcceptEncoding);
Console.WriteLine("AcceptLanguage: " + rootObject.headers.AcceptLanguage);
Console.WriteLine("Authorization: " + rootObject.headers.Authorization);
Console.WriteLine("Connection: " + rootObject.headers.Connection);
Console.WriteLine("Dnt: " + rootObject.headers.Dnt);
Console.WriteLine("Host: " + rootObject.headers.Host);
Console.WriteLine("Origin: " + rootObject.headers.Origin);
Console.WriteLine("Referer: " + rootObject.headers.Referer);
Console.WriteLine("UserAgent: " + rootObject.headers.UserAgent);
Console.WriteLine("origin: " + rootObject.origin);
Console.WriteLine("url: " + rootObject.url);
Console.WriteLine("data: " + rootObject.data);
Console.WriteLine("files: ");
foreach (KeyValuePair<string, string> kvp in rootObject.files ?? Enumerable.Empty<KeyValuePair<string, string>>())
{
Console.WriteLine("\t" + kvp.Key + ": " + kvp.Value);
}
}
}
public class Args
{
public string clientId { get; set; }
}
public class Headers
{
public string Accept { get; set; }
public string AcceptEncoding { get; set; }
public string AcceptLanguage { get; set; }
public string Authorization { get; set; }
public string Connection { get; set; }
public string Dnt { get; set; }
public string Host { get; set; }
public string Origin { get; set; }
public string Referer { get; set; }
public string UserAgent { get; set; }
}
public class RootObject
{
public Args args { get; set; }
public Headers headers { get; set; }
public string origin { get; set; }
public string url { get; set; }
public string data { get; set; }
public Dictionary<string, string> files { get; set; }
}
}
" the user is the one who select max no and min no ?" What do you mean by this line ?
You can use java function int random = Random.nextInt(n)
. This returns a random int in range[0, n-1]).
and you can set it in your textview using the setText()
method
There is a PPA with up-to-date versions of Ruby 2.x for Ubuntu 12.04+:
$ sudo apt-add-repository ppa:brightbox/ruby-ng
$ sudo apt-get update
$ sudo apt-get install ruby2.4
$ ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux-gnu]
The problem here is that you cannot define the background color using a color selector, you need a drawable selector. So, the necessary changes would look like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@drawable/selected_state" />
</selector>
You would also need to move that resource to the drawable
directory where it would make more sense since it's not a color selector per se.
Then you would have to create the res/drawable/selected_state.xml
file like this:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/semitransparent_white" />
</shape>
and finally, you would use it like this:
android:background="@drawable/selector"
Note: the reason why the OP was getting an image resource drawn is probably because he tried to just reference his resource that was still in the color directory but using @drawable
so he ended up with an ID collision, selecting the wrong resource.
Hope this can still help someone even if the OP probably has, I hope, solved his problem by now.
You can delete the latest gradle-.-all folder from the below path Windows: C:\Users\your-username.gradle\wrapper\dists
If you use Mac, you are in luck. One can change the keymap for Intellij as Mac OS X, then you can use option+C.
Hope you dont mind Xml.Linq and .net3.5+
XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);
Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.
They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.
Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools
There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?
If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.
On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).
Small And Better One
var i = 0;
$("#container > option").each(function(){
if($(this).val().length > i) {
i = $(this).val().length;
console.log(i);
console.log($(this).val());
}
});
Those are some very nice, but lengthy answers.
To sum up my experiences:
For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:
// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;
// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);
This triggers the visual cue fading in and out.
Why not just:
names, counts = zip(*D.items())
plt.bar(names, counts)
It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.
You can use following code to insert an image through script.
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Above example has been copied from this link. Check noogui's reply for details.
In case you need to insert image from Google Drive, please check this link for current updates.
if your python version is 3.5
, do a pip install mysqlclient
, other things didn't work for me
Here's a pure CSS solution. No need for jQuery. It won't show a tooltip, instead it'll just expand the content to its full length on mouseover.
Works great if you have content that gets replaced. Then you don't have to run a jQuery function every time.
.might-overflow {
text-overflow: ellipsis;
overflow : hidden;
white-space: nowrap;
}
.might-overflow:hover {
text-overflow: clip;
white-space: normal;
word-break: break-all;
}
At some point in time the object changed from ionic
to an uppercase Ionic
.
As of July 2017 you need to put Ionic.version
into your console to get the version number.
If you don't want the Drop list
to show up like a popup. You can customize it this way just like me (it will show up as if on the same flat, see image below):
After expand:
Please follow the steps below:
First, create a dart file named drop_list_model.dart
:
import 'package:flutter/material.dart';
class DropListModel {
DropListModel(this.listOptionItems);
final List<OptionItem> listOptionItems;
}
class OptionItem {
final String id;
final String title;
OptionItem({@required this.id, @required this.title});
}
Next, create file file select_drop_list.dart
:
import 'package:flutter/material.dart';
import 'package:time_keeping/model/drop_list_model.dart';
import 'package:time_keeping/widgets/src/core_internal.dart';
class SelectDropList extends StatefulWidget {
final OptionItem itemSelected;
final DropListModel dropListModel;
final Function(OptionItem optionItem) onOptionSelected;
SelectDropList(this.itemSelected, this.dropListModel, this.onOptionSelected);
@override
_SelectDropListState createState() => _SelectDropListState(itemSelected, dropListModel);
}
class _SelectDropListState extends State<SelectDropList> with SingleTickerProviderStateMixin {
OptionItem optionItemSelected;
final DropListModel dropListModel;
AnimationController expandController;
Animation<double> animation;
bool isShow = false;
_SelectDropListState(this.optionItemSelected, this.dropListModel);
@override
void initState() {
super.initState();
expandController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 350)
);
animation = CurvedAnimation(
parent: expandController,
curve: Curves.fastOutSlowIn,
);
_runExpandCheck();
}
void _runExpandCheck() {
if(isShow) {
expandController.forward();
} else {
expandController.reverse();
}
}
@override
void dispose() {
expandController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 17),
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 10,
color: Colors.black26,
offset: Offset(0, 2))
],
),
child: new Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(Icons.card_travel, color: Color(0xFF307DF1),),
SizedBox(width: 10,),
Expanded(
child: GestureDetector(
onTap: () {
this.isShow = !this.isShow;
_runExpandCheck();
setState(() {
});
},
child: Text(optionItemSelected.title, style: TextStyle(
color: Color(0xFF307DF1),
fontSize: 16),),
)
),
Align(
alignment: Alignment(1, 0),
child: Icon(
isShow ? Icons.arrow_drop_down : Icons.arrow_right,
color: Color(0xFF307DF1),
size: 15,
),
),
],
),
),
SizeTransition(
axisAlignment: 1.0,
sizeFactor: animation,
child: Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.only(bottom: 10),
decoration: new BoxDecoration(
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 4,
color: Colors.black26,
offset: Offset(0, 4))
],
),
child: _buildDropListOptions(dropListModel.listOptionItems, context)
)
),
// Divider(color: Colors.grey.shade300, height: 1,)
],
),
);
}
Column _buildDropListOptions(List<OptionItem> items, BuildContext context) {
return Column(
children: items.map((item) => _buildSubMenu(item, context)).toList(),
);
}
Widget _buildSubMenu(OptionItem item, BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 26.0, top: 5, bottom: 5),
child: GestureDetector(
child: Row(
children: <Widget>[
Expanded(
flex: 1,
child: Container(
padding: const EdgeInsets.only(top: 20),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey[200], width: 1)),
),
child: Text(item.title,
style: TextStyle(
color: Color(0xFF307DF1),
fontWeight: FontWeight.w400,
fontSize: 14),
maxLines: 3,
textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis),
),
),
],
),
onTap: () {
this.optionItemSelected = item;
isShow = false;
expandController.reverse();
widget.onOptionSelected(item);
},
),
);
}
}
Initialize value:
DropListModel dropListModel = DropListModel([OptionItem(id: "1", title: "Option 1"), OptionItem(id: "2", title: "Option 2")]);
OptionItem optionItemSelected = OptionItem(id: null, title: "Ch?n quy?n truy c?p");
Finally use it:
SelectDropList(
this.optionItemSelected,
this.dropListModel,
(optionItem){
optionItemSelected = optionItem;
setState(() {
});
},
)
Instead of using
if(data !== null && data !== '' && data!==undefined) {
// do something
}
You can use below simple code
if(Boolean(value)){
// do something
}
Create a repository folder under your project. Let's take
${project.basedir}/src/main/resources/repo
Then, install your custom jar to this repo:
mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]
Lastly, add the following repo and dependency definitions to the projects pom.xml:
<repositories>
<repository>
<id>project-repo</id>
<url>file://${project.basedir}/src/main/resources/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>[GROUP]</groupId>
<artifactId>[ARTIFACT]</artifactId>
<version>[VERS]</version>
</dependency>
</dependencies>
One additional comment regarding Vineet Reynolds answer.
I found out that I had to set -XX:+UseParallelGC
in eclipse.ini
I setup the virtual machine (vm) arguments as follows
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
that solved the issue.
Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then
string currentURL = HttpContext.Current.Request.Url.Host;
will return www.someshopping.com
Note the difference between a local debugging environment and a production environment
Here's a hack that just got me out of trouble with this one.
So a similar scenario to the OP - I've got a nested Angular component that needs data passed down to it, but the input points to an array, and as mentioned above, Angular doesn't see a change as it does not examine the contents of the array.
So to fix it I convert the array to a string for Angular to detect a change, and then in the nested component I split(',') the string back to an array and its happy days again.
==
will still test object equality. It is easy to be fooled, however:
Integer a = 10;
Integer b = 10;
System.out.println(a == b); //prints true
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c == d); //prints false
Your examples with inequalities will work since they are not defined on Objects. However, with the ==
comparison, object equality will still be checked. In this case, when you initialize the objects from a boxed primitive, the same object is used (for both a and b). This is an okay optimization since the primitive box classes are immutable.
This is how I did it with a large (50 GB) file:
I tried 2 different ways: the first, reading the file into memory and using Regex Replace or String Replace. Then I appended the entire string to a temporary file.
The first method works well for a few Regex replacements, but Regex.Replace or String.Replace could cause out of memory error if you do many replaces in a large file.
The second is by reading the temp file line by line and manually building each line using StringBuilder and appending each processed line to the result file. This method was pretty fast.
static void ProcessLargeFile()
{
if (File.Exists(outFileName)) File.Delete(outFileName);
string text = File.ReadAllText(inputFileName, Encoding.UTF8);
// EX 1 This opens entire file in memory and uses Replace and Regex Replace --> might cause out of memory error
text = text.Replace("</text>", "");
text = Regex.Replace(text, @"\<ref.*?\</ref\>", "");
File.WriteAllText(outFileName, text);
// EX 2 This reads file line by line
if (File.Exists(outFileName)) File.Delete(outFileName);
using (var sw = new StreamWriter(outFileName))
using (var fs = File.OpenRead(inFileName))
using (var sr = new StreamReader(fs, Encoding.UTF8)) //use UTF8 encoding or whatever encoding your file uses
{
string line, newLine;
while ((line = sr.ReadLine()) != null)
{
//note: call your own replace function or use String.Replace here
newLine = Util.ReplaceDoubleBrackets(line);
sw.WriteLine(newLine);
}
}
}
public static string ReplaceDoubleBrackets(string str)
{
//note: this replaces the first occurrence of a word delimited by [[ ]]
//replace [[ with your own delimiter
if (str.IndexOf("[[") < 0)
return str;
StringBuilder sb = new StringBuilder();
//this part gets the string to replace, put this in a loop if more than one occurrence per line.
int posStart = str.IndexOf("[[");
int posEnd = str.IndexOf("]]");
int length = posEnd - posStart;
// ... code to replace with newstr
sb.Append(newstr);
return sb.ToString();
}
You can use the open pragma.
For eg. below sets STDOUT, STDIN & STDERR to use UTF-8....
use open qw/:std :utf8/;
Leave off the quotes
$cmd &
$othercmd &
eg:
nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash
cmd="ls -la"
$cmd &
nicholas@nick-win7 /tmp
$ ./test
nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root 0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx 1 nicholas None 35 2010-09-10 20:44 test
-rwxr-xr-x 1 nicholas None 41 2010-09-10 20:43 test~
Depending on your version ou cannot do it directly, but you could do something hacky like
select top 25 *
from (
select top 75 *
from table
order by field asc
) a
order by field desc
where 'field' is the key.
Let's say you generate a bunch of views that are similar. You could set an OnClickListener
for each view individually:
button1.setOnClickListener(new OnClickListener ... );
button2.setOnClickListener(new OnClickListener ... );
...
Then you have to create a unique onClick
method for each view even if they do the similar things, like:
public void onClick(View v) {
doAction(1); // 1 for button1, 2 for button2, etc.
}
This is because onClick
has only one parameter, a View
, and it has to get other information from instance variables or final local variables in enclosing scopes. What we really want is to get information from the views themselves.
Enter getTag
/setTag
:
button1.setTag(1);
button2.setTag(2);
Now we can use the same OnClickListener for every button:
listener = new OnClickListener() {
@Override
public void onClick(View v) {
doAction(v.getTag());
}
};
It's basically a way for views to have memories.
When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:
def add(a,b):
return a + b
you would call the function like this:
add(3,5)
which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:
answer = add(4,7)
Which would set the variable answer equal to 11 in this case.
The element that you posted looks like it's just copy-pasted from the Google Maps embed feature.
If you'd like to drop markers for the locations that you have, you'll need to write some JavaScript to do so. I'm learning how to do this as well.
Check out the following: https://developers.google.com/maps/documentation/javascript/overlays
It has several examples and code samples that can be easily re-used and adapted to fit your current problem.
Two Answers
1. Answer to the asked question.
2. A simple change equals a better way!
Answer 1 - Pass the Vars Array to the __construct() in a class, you could also leave the construct empty and pass the Arrays through your functions instead.
<?php
// Create an Array with all needed Sub Arrays Example:
// Example Sub Array 1
$content_arrays["modals"]= array();
// Example Sub Array 2
$content_arrays["js_custom"] = array();
// Create a Class
class Array_Pushing_Example_1 {
// Public to access outside of class
public $content_arrays;
// Needed in the class only
private $push_value_1;
private $push_value_2;
private $push_value_3;
private $push_value_4;
private $values;
private $external_values;
// Primary Contents Array as Parameter in __construct
public function __construct($content_arrays){
// Declare it
$this->content_arrays = $content_arrays;
}
// Push Values from in the Array using Public Function
public function array_push_1(){
// Values
$this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
$this->push_values_2 = array("a","b","c");
// Loop Values and Push Values to Sub Array
foreach($this->push_values_1 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_2 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
// GET Push Values External to the Class with Public Function
public function array_push_2($external_values){
$this->push_values_3 = $external_values["values_1"];
$this->push_values_4 = $external_values["values_2"];
// Loop Values and Push Values to Sub Array
foreach($this->push_values_3 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_4 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
}
// Start the Class with the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_1($content_arrays);
// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();
// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);
// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";
echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){
echo $modals;
echo "<br>";
}
echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){
echo $js_custom;
echo "<br>";
}
echo "<br>";
?>
Answer 2 - A simple change however would put it inline with modern standards. Just declare your Arrays in the Class.
<?php
// Create a Class
class Array_Pushing_Example_2 {
// Public to access outside of class
public $content_arrays;
// Needed in the class only
private $push_value_1;
private $push_value_2;
private $push_value_3;
private $push_value_4;
private $values;
private $external_values;
// Declare Contents Array and Sub Arrays in __construct
public function __construct(){
// Declare them
$this->content_arrays["modals"] = array();
$this->content_arrays["js_custom"] = array();
}
// Push Values from in the Array using Public Function
public function array_push_1(){
// Values
$this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
$this->push_values_2 = array("a","b","c");
// Loop Values and Push Values to Sub Array
foreach($this->push_values_1 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_2 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
// GET Push Values External to the Class with Public Function
public function array_push_2($external_values){
$this->push_values_3 = $external_values["values_1"];
$this->push_values_4 = $external_values["values_2"];
// Loop Values and Push Values to Sub Array
foreach($this->push_values_3 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_4 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
}
// Start the Class without the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_2();
// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();
// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);
// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";
echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){
echo $modals;
echo "<br>";
}
echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){
echo $js_custom;
echo "<br>";
}
echo "<br>";
?>
Both options output the same information and allow a function to push and retrieve information from an Array and sub Arrays to any place in the code(Given that the data has been pushed first). The second option gives more control over how the data is used and protected. They can be used as is just modify to your needs but if they were used to extend a Controller they could share their values among any of the Classes the Controller is using. Neither method requires the use of a Global(s).
Output:
Array Custom Content Results
Modals - Count: 5
a
b
c
FOO
foo
JS Custom - Count: 9
1
2B or not 2B
3
42
5
car
house
bike
glass
An other approach using borders and no CSS3 properties :
div, div:after{_x000D_
border-width: 80px 0 80px 80px;_x000D_
border-color: transparent transparent transparent #000;_x000D_
border-style:solid;_x000D_
position:relative;_x000D_
}_x000D_
div:after{_x000D_
content:'';_x000D_
position:absolute;_x000D_
left:-115px; top:-80px;_x000D_
border-left-color:#fff;_x000D_
}
_x000D_
<div></div>
_x000D_
Here is a solution to the literal question of how to print a message to the browser's error console, not the debugger console. (There might be good reasons to bypass the debugger.)
As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don't want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):
var startTime = (new Date()).getTime();
function logError(msg)
{
var milliseconds = (new Date()).getTime() - startTime;
window.setTimeout(function () {
throw( new Error(milliseconds + ': ' + msg, "") );
});
}
logError('testing');
I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages.
The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way.
It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can't find a way to do that.
Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can't help you there.
If this is a simple Java project, You essentially create a new project and give the location of the existing code. The project wizard will tell you that it will use existing sources.
Also, Eclipse 3.3.2 is ancient history, you guys should really upgrade. This is like using Visual Studio 5.
In XML there can be only one root element - you have two - heading
and song
.
If you restructure to something like:
<?xml version="1.0" encoding="UTF-8"?>
<song>
<heading>
The Twelve Days of Christmas
</heading>
....
</song>
The error about well-formed XML on the root level should disappear (though there may be other issues).
Using reset($array) and end($array)
<?php
$arrays = [1,2,3,4,5];
$first = reset($arrays);
$last = end($arrays);
foreach( $arrays as $array )
{
if ( $first == $array )
{
echo "<li>{$array} first</li>";
}
else if ( $last == $array )
{
echo "<li>{$array} last</li>";
}
else
{
echo "<li>{$array}</li>";
}
}
The usual API for this is DirectShow.
You can use P/Invoke to import the C++ APIs, but I think there are already a few projects out there that have done this.
http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/
http://www.codeproject.com/KB/directx/DirXVidStrm.aspx
To get the streaming part, you probably want to use DirectShow to apply a compression codec to reduce lag, then you can get a Stream and transmit it. You could consider using multicast to reduce network load.
Auth::id()
, likePost::create([ 'body' => request('body'), 'title' => request('title'), 'user_id' => Auth::id()]);
also remember to include Auth facade at top of your controller which is App\Http\Controllers\Auth
Update as an alternative to the excellent answer from 2010:
You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups
Example:
PS C:\WINDOWS\system32> Get-LocalGroupMember -name users
ObjectClass Name PrincipalSource
----------- ---- ---------------
User DESKTOP-R05QDNL\someUser1 Local
User DESKTOP-R05QDNL\someUser2 MicrosoftAccount
Group NT AUTHORITY\INTERACTIVE Unknown
You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.
In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:
$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"
New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description
It's actually a sensible question. Here's the answer from Excel 2010 help:
"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."
So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:
Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")
There is already a correct answer from Adam, but you have another option to refactor your code:
if (Age.GetValueOrDefault() == 0)
{
// it's null or 0
}
No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.
In other words, your code only works by accident, and probably not in all browsers.
Is this what you're trying to do?
<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>
./eclipse -clean -refresh
as mentioned in comment by sulai Dec 20 '12 at 12:46, that worked for me.
However, on the Mac OS X, I had to figure out how to get to ./eclipse
Here's the solution:
cd Eclipse.app/Contents/MacOS/
Thank you Andrew's comment for this post: https://stackoverflow.com/a/1783448/2162226
I had this issue in VS 2015. The following solved it for me:
Find "webpages:Version" in the appsettings and update it to version 3.0.0.0. My web.config had
<add key="webpages:Version" value="2.0.0.0" />
and I updated it to
<add key="webpages:Version" value="3.0.0.0" />
This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.
Add a reference to Microsoft.VisualBasic
Create a class called WindowsFormsApplication
public class WindowsFormsApplication : WindowsFormsApplicationBase
{
/// <summary>
/// Runs the specified mainForm in this application context.
/// </summary>
/// <param name="mainForm">Form that is run.</param>
public virtual void Run(Form mainForm)
{
// set up the main form.
this.MainForm = mainForm;
// Example code
((Form1)mainForm).FileName = this.CommandLineArgs[0];
// then, run the the main form.
this.Run(this.CommandLineArgs);
}
/// <summary>
/// Runs this.MainForm in this application context. Converts the command
/// line arguments correctly for the base this.Run method.
/// </summary>
/// <param name="commandLineArgs">Command line collection.</param>
private void Run(ReadOnlyCollection<string> commandLineArgs)
{
// convert the Collection<string> to string[], so that it can be used
// in the Run method.
ArrayList list = new ArrayList(commandLineArgs);
string[] commandLine = (string[])list.ToArray(typeof(string));
this.Run(commandLine);
}
}
Modify your Main() routine to look like this
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var application = new WindowsFormsApplication();
application.Run(new Form1());
}
}
This method offers some additional usefull features (like SplashScreen support and some usefull events)
public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
public event ShutdownEventHandler Shutdown;
public event StartupEventHandler Startup;
public event StartupNextInstanceEventHandler StartupNextInstance;
public event UnhandledExceptionEventHandler UnhandledException;
As of Python 3.4, the hashlib
module in the standard library contains key derivation functions which are "designed for secure password hashing".
So use one of those, like hashlib.pbkdf2_hmac
, with a salt generated using os.urandom
:
from typing import Tuple
import os
import hashlib
import hmac
def hash_new_password(password: str) -> Tuple[bytes, bytes]:
"""
Hash the provided password with a randomly-generated salt and return the
salt and hash to store in the database.
"""
salt = os.urandom(16)
pw_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
return salt, pw_hash
def is_correct_password(salt: bytes, pw_hash: bytes, password: str) -> bool:
"""
Given a previously-stored salt and hash, and a password provided by a user
trying to log in, check whether the password is correct.
"""
return hmac.compare_digest(
pw_hash,
hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
)
# Example usage:
salt, pw_hash = hash_new_password('correct horse battery staple')
assert is_correct_password(salt, pw_hash, 'correct horse battery staple')
assert not is_correct_password(salt, pw_hash, 'Tr0ub4dor&3')
assert not is_correct_password(salt, pw_hash, 'rosebud')
Note that:
os.urandom
always uses a cryptographically secure source of randomnesshmac.compare_digest
, used in is_correct_password
, is basically just the ==
operator for strings but without the ability to short-circuit, which makes it immune to timing attacks. That probably doesn't really provide any extra security value, but it doesn't hurt, either, so I've gone ahead and used it.For theory on what makes a good password hash and a list of other functions appropriate for hashing passwords with, see https://security.stackexchange.com/q/211/29805.
Try this:
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
JS Code
function search(ele) {
if(event.key === 'Enter') {
alert(ele.value);
}
}
I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.
All you will have to do is
class BatchCollection(dict):
def __init__(self, *args, **kwargs):
dict.__init__(*args, **kwargs)
OR
class BatchCollection(dict):
def __init__(self, inpt={}):
super(BatchCollection, self).__init__(inpt)
A sample usage for my personal use
### EXAMPLE
class BatchCollection(dict):
def __init__(self, inpt={}):
dict.__init__(*args, **kwargs)
def __setitem__(self, key, item):
if (isinstance(key, tuple) and len(key) == 2
and isinstance(item, collections.Iterable)):
# self.__dict__[key] = item
super(BatchCollection, self).__setitem__(key, item)
else:
raise Exception(
"Valid key should be a tuple (database_name, table_name) "
"and value should be iterable")
Note: tested only in python3
As always, the Jakarta Commons have at least part of the answer :
This can be used to check most whether a given String is a number. You still have to choose what to do in case your String isnt a number ...
Here is a method I use to get the last xx of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
I guess this has been already answered. However, I think that you can still mix both options in a syntactically better way by doing:
switch (value)
{
case 1: case 2: case 3:
// Do Something
break;
case 4: case 5: case 6:
// Do Something
break;
default:
// Do Something
break;
}
Bear in mind that I speak ASFAC++B. :) I've put the most important differentiating factor first.
Garbage Collection
Garbage Collection (GC) is the single most important factor in differentiating between these languages.
While C and C++ can be used with GC, it is a bolted-on afterthought and cannot be made to work as well (the best known is here) - it has to be "conservative" which means that it cannot collect all unused memory.
C# is designed from the ground up to work on a GC platform, with standard libraries also designed that way. It makes an absolutely fundamental difference to developer productivity that has to be experienced to be believed.
There is a belief widespread among C/C++ users that GC equates with "bad performance". But this is out-of-date folklore (even the Boehm collector on C/C++ performs much better than most people expect it to). The typical fear is of "long pauses" where the program stops so the GC can do some work. But in reality these long pauses happen with non-GC programs, because they run on top of a virtual memory system, which occasionally interrupts to move data between physical memory and disk.
There is also widespread belief that GC can be replaced with shared_ptr, but it can't; the irony is that in a multi-threaded program, shared_ptr
is slower than a GC-based system.
There are environments that are so frugal that GC isn't practical - but these are increasingly rare. Cell phones typically have GC. The CLR's GC that C# typically runs on appears to be state-of-the-art.
Since adopting C# about 18 months ago I've gone through several phases of pure performance tuning with a profiler, and the GC is so efficient that it is practically invisible during the operation of the program.
GC is not a panacea, it doesn't solve all programming problems, it only really cleans up memory allocation, if you're allocating very large memory blocks then you will still need to take some care, and it is still possible to have what amounts to a memory leak in a sufficiently complex program - and yet, the effect of GC on productivity makes it a pretty close approximation to a panacea!
Undefined Behaviour
C++ is founded on the notion of undefined behaviour. That is, the language specification defines the outcome of certain narrowly defined usages of language features, and describes all other usages as causing undefined behaviour, meaning in principle that the operation could have any outcome at all (in practice this means hard-to-diagnose bugs involving apparently non-deterministic corruption of data).
Almost everything about C++ touches on undefined behaviour. Even very nice forthcoming features like lambda expressions can easily be used as convenient way to corrupt the stack (capture a local by reference, allow the lambda instance to outlive the local).
C# is founded on the principle that all possible operations should have defined behaviour. The worst that can happen is an exception is thrown. This completely changes the experience of software construction.
(There's unsafe mode, which has pointers and therefore undefined behaviour, but that is strongly discouraged for general use - think of it as analogous to embedded assembly language.)
Complexity
In terms of complexity, C++ has to be singled out, especially if we consider the very-soon-to-be standardized new version. C++ does absolutely everything it can to make itself effective, short of assuming GC, and as a result it has an awesome learning curve. The language designers excuse much of this by saying "Those features are only for library authors, not ordinary users" - but to be truly effective in any language, you need to build your code as reusable libraries. So you can't escape.
On the positive side, C++ is so complex, it's like a playground for nerds! I can assure you that you would have a lot of fun learning how it all fits together. But I can't seriously recommend it as a basis for productive new work (oh, the wasted years...) on mainstream platforms.
C keeps the language simple (simple in the sense of "the compiler is easy to write"), but this makes the coding techniques more arcane.
Note that not all new language features equate with added complexity. Some language features are described as "syntactic sugar", because they are shorthand that the compiler expands for you. This is a good way to think of a great deal of the enhancements to C# over recent years. The language standard even specifies some features by giving the translation to longhand, e.g. using
statement expands into try
/finally
.
At one point, it was possible to think of C++ templates in the same way. But they've since become so powerful that they are now form the basis of a whole separate dimension of the language, with its own enthusiastic user communities and idioms.
Libraries
The strangest thing about C and C++ is that they don't have a standard interchangeable form of pre-compiled library. Integrating someone else's code into your project is always a little fiddly, with obscure decisions to be made about how you'll be linking to it.
Also, the standard library is extremely basic - C++ has a complete set of data structures and a way of representing strings (std::string
), but that's still minimal. Is there a standard way of finding a list of files in a directory? Amazingly, no! Is there standard library support for parsing or generating XML? No. What about accessing databases? Be serious! Writing a web site back-end? Are you crazy? etc.
So you have to go hunting further afield. For XML, try Xerces. But does it use std::string
to represent strings? Of course not!
And do all these third-party libraries have their own bizarre customs for naming classes and functions? You betcha!
The situation in C# couldn't be more different; the fundamentals were in place from the start, so everything inter-operates beautifully (and because the fundamentals are supplied by the CLR, there is cross-language support).
It's not all perfect; generics should have been in place from the start but wasn't, which does leave a visible scar on some older libraries; but it is usually trivial to fix this externally. Also a number of popular libraries are ported from Java, which isn't as good a fit as it first appears.
Closures (Anonymous Methods with Local Variable Capture)
Java and C are practically the last remaining mainstream languages to lack closures, and libraries can be designed and used much more neatly with them than without (this is one reason why ported Java libraries sometimes seem clunky to a C# user).
The amusing thing about C++ is that its standard library was designed as if closures were available in the language (container types, <algorithm>
, <functional>
). Then ten years went by, and now they're finally being added! They will have a huge impact (although, as noted above, they leak underfined behaviour).
C# and JavaScript are the most widely used languages in which closures are "idiomatically established". (The major difference between those languages being that C# is statically typed while JavaScript is dynamically typed).
Platform Support
I've put this last only because it doesn't appear to differentiate these languages as much as you might think. All these languages can run on multiple OSes and machine architectures. C is the most widely-supported, then C++, and finally C# (although C# can be used on most major platforms thanks to an open source implementation called Mono).
My experience of porting C++ programs between Windows and various Unix flavours was unpleasant. I've never tried porting anything very complex in C# to Mono, so I can't comment on that.
I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)
echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service
Output:
1
----------
1
Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.
Here is a nice plugin for jQuery that submits forms via ajax:
http://malsup.com/jquery/form/
its as simple as:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert('form was submitted');
});
});
</script>
It uses the forms action for the post location. Not that you can't achieve this with your own code but this plugin has worked very nicely for me!
From the command line, it's simply:
printf "compute sha1" | openssl sha1
You can invoke the library like this:
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
int main()
{
unsigned char ibuf[] = "compute sha1";
unsigned char obuf[20];
SHA1(ibuf, strlen(ibuf), obuf);
int i;
for (i = 0; i < 20; i++) {
printf("%02x ", obuf[i]);
}
printf("\n");
return 0;
}
I had an xaml file with the following definition
<Window x:Class="mm2.Views"
.etc..
/>
mm2.Views
was the name of a namespace in my app.
To fix it, I correctly renamed the xaml object:
<Window x:Class="mm2.Views.RecordedTracks"
.etc..
/>
[NOTE: I am not deleting my answer on purpose, so people see how not to do it]
If you use:
me@over_there:~$ dpkg --status nvidia-current | grep Version | cut -f 1 -d '-' | sed 's/[^.,0-9]//g'
260.19.06
you will get the version of the nVIDIA driver package installed through your distribution's packaging mechanism. But this may not be the version that is actually running as part of your kernel right now.
Add this to an htaccess file (and see edit notes added below):
<IfModule mod_php5.c>
php_value post_max_size 200M
php_value upload_max_filesize 200M
php_value memory_limit 300M
php_value max_execution_time 259200
php_value max_input_time 259200
php_value session.gc_maxlifetime 1200
</IfModule>
Additional resources and information:
2021 EDIT:
As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:
<IfModule
is loaded.mod_php5.c
in the first line. If you are using PHP 7, you would replace that with mod_php7.c
.php.ini
config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.Using this answer which provides the code to use Dom4j to do pretty-printing, change the line that sets the output format from: createPrettyPrint()
to: createCompactFormat()
public String unPrettyPrint(final String xml){
if (StringUtils.isBlank(xml)) {
throw new RuntimeException("xml was null or blank in unPrettyPrint()");
}
final StringWriter sw;
try {
final OutputFormat format = OutputFormat.createCompactFormat();
final org.dom4j.Document document = DocumentHelper.parseText(xml);
sw = new StringWriter();
final XMLWriter writer = new XMLWriter(sw, format);
writer.write(document);
}
catch (Exception e) {
throw new RuntimeException("Error un-pretty printing xml:\n" + xml, e);
}
return sw.toString();
}
What you may actually want to use is an Iterable
that can return a fresh Iterator
multiple times by calling iterator()
.
//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
Iterator<Type> it = ible.iterator(); //Gets an iterator
while (it.hasNext()) {
it.next();
}
it = ible.iterator(); //Gets a NEW iterator, also from the beginning
while (it.hasNext()) {
it.next();
}
}
You must define what the iterator()
method does just once beforehand:
void main() {
LinkedList<String> list; //This could be any type of object that has an iterator
//Define an Iterable that knows how to retrieve a fresh iterator
Iterable<Type> ible = new Iterable<Type>() {
@Override
public Iterator<Type> iterator() {
return list.listIterator(); //Define how to get a fresh iterator from any object
}
};
//Now with a single instance of an Iterable,
func(ible); //you can iterate through it multiple times.
}
If you do something like this:
cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";
size will be taken from "some large text".Length
This can be problematic when it's an output parameter, you get back no more characters then you put as input.
",".join(l)
will not work for all cases. I'd suggest using the csv module with StringIO
import StringIO
import csv
l = ['list','of','["""crazy"quotes"and\'',123,'other things']
line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'
/* 1 */ Foo* foo1 = new Foo ();
Creates an object of type Foo
in dynamic memory. foo1
points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo
was a POD-type, this would perform value-initialization (it doesn't apply here).
/* 2 */ Foo* foo2 = new Foo;
Identical to before, because Foo
is not a POD type.
/* 3 */ Foo foo3;
Creates a Foo
object called foo3
in automatic storage.
/* 4 */ Foo foo4 = Foo::Foo();
Uses copy-initialization to create a Foo
object called foo4
in automatic storage.
/* 5 */ Bar* bar1 = new Bar ( *new Foo() );
Uses Bar
's conversion constructor to create an object of type Bar
in dynamic storage. bar1
is a pointer to it.
/* 6 */ Bar* bar2 = new Bar ( *new Foo );
Same as before.
/* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
This is just invalid syntax. You can't declare a variable there.
/* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );
Would work and work by the same principle to 5 and 6 if bar3
wasn't declared on in 7.
5 & 6 contain memory leaks.
Syntax like new Bar ( Foo::Foo() );
is not usual. It's usually new Bar ( (Foo()) );
- extra parenthesis account for most-vexing parse. (corrected)
You can use this snippet :-D
using System;
using System.Reflection;
public static class EnumUtils
{
public static T GetDefaultValue<T>()
where T : struct, Enum
{
return (T)GetDefaultValue(typeof(T));
}
public static object GetDefaultValue(Type enumType)
{
var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
if (attribute != null)
return attribute.Value;
var innerType = enumType.GetEnumUnderlyingType();
var zero = Activator.CreateInstance(innerType);
if (enumType.IsEnumDefined(zero))
return zero;
var values = enumType.GetEnumValues();
return values.GetValue(0);
}
}
Example:
using System;
public enum Enum1
{
Foo,
Bar,
Baz,
Quux
}
public enum Enum2
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 0
}
public enum Enum3
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
public static class Program
{
public static void Main()
{
var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
Console.WriteLine(defaultValue1); // Foo
var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
Console.WriteLine(defaultValue2); // Quux
var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
Console.WriteLine(defaultValue3); // Foo
var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
Console.WriteLine(defaultValue4); // Bar
}
}
I know this is very old thread running, but still EF has not fixed this. For people using auto-generated DbContext
can use the following code to set the timeout manually.
public partial class SampleContext : DbContext
{
public SampleContext()
: base("name=SampleContext")
{
this.SetCommandTimeOut(180);
}
public void SetCommandTimeOut(int Timeout)
{
var objectContext = (this as IObjectContextAdapter).ObjectContext;
objectContext.CommandTimeout = Timeout;
}
The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):
Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.
For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.
These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '
), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "
), or (iv) unquoted — with the following restrictions:
... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.
# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
iptables -A FORWARD -p all -d $ip -j REJECT
done
I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).
I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.
[Desktop Entry]
Name=No name
Encoding=UTF-8
Version=1.0
Exec=vncconfig -nowin
X-GNOME-Autostart-enabled=true
Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.
Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.
I think the secret guru register is the expression = register. It can be used for creative mappings.
:inoremap \d The current date <c-r>=system("date")<cr>
You can use it in conjunction with your system as above or get responses from custom VimL functions etc.
or just ad hoc stuff like
<c-r>=35+7<cr>
Try using @Html.DropDownList
instead:
<td>Account: </td>
<td>@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>
@Html.DropDownListFor
expects a lambda as its first argument, not a string
for the ID as you specify.
Other than that, without knowing what getUserAccounts()
consists of, suffice to say it needs to return some sort of collection (IEnumerable
for example) that has at least 1 object in it. If it returns null
the property in the ViewBag won't have anything.
In your project settings.py file,set ALLOWED_HOSTS like this :
ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']
and then restart your apache. in ubuntu:
/etc/init.d/apache2 restart
I know this is a little bit late but i think there is a more elegant way of doing this with PHP 5.3+
by using the DateTime class :
$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window
and document
both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.
So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.
Data table to List
#region "getobject filled object with property reconized"
public List<T> ConvertTo<T>(DataTable datatable) where T : new()
{
List<T> Temp = new List<T>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
columnsNames.Add(DataColumn.ColumnName);
Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
return Temp;
}
catch
{
return Temp;
}
}
public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties;
Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch
{
return obj;
}
}
#endregion
IEnumerable collection To Datatable
#region "New DataTable"
public DataTable ToDataTable<T>(IEnumerable<T> collection)
{
DataTable newDataTable = new DataTable();
Type impliedType = typeof(T);
PropertyInfo[] _propInfo = impliedType.GetProperties();
foreach (PropertyInfo pi in _propInfo)
newDataTable.Columns.Add(pi.Name, pi.PropertyType);
foreach (T item in collection)
{
DataRow newDataRow = newDataTable.NewRow();
newDataRow.BeginEdit();
foreach (PropertyInfo pi in _propInfo)
newDataRow[pi.Name] = pi.GetValue(item, null);
newDataRow.EndEdit();
newDataTable.Rows.Add(newDataRow);
}
return newDataTable;
}
You almost never have to write your own loops in C++. Here, you can use std::find.
const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
std::cout << "Found.\n"
}
else
{
std::cout << "Not found.\n";
}
std::end
requires C++11. Without it, you can find the number of elements in the array with:
const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);
...and the end with:
int* end = myArray + numElements;
Have you tried this
long c = users.stream().filter((user) -> user.getId() == 1).count();
if(c > 1){
throw new IllegalStateException();
}
long count()
Returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:
return mapToLong(e -> 1L).sum();
This is a terminal operation.
Source: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
How about alias gcc99= gcc -std=c99
?
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) {
return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);
// assuming the current url is `/team/33/user/11` and the route points to `user/11`
// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});
// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});
// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts:
constructor(private route: ActivatedRoute, private router: Router) {}
// Example call
onNavigateClick() {
// Navigates to a parent component
this.router.navigate([..], { relativeTo: this.route })
}
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"
// if the string parameter is passed it will be wrapped into an array
routerLink="../.."
You can also download MySql workbench (31Mo) which includes mysql.exe
and mysqldump.exe
.
I successfully tested this when i had to run Perl scripts using DBD:MySql
module to run SQL statements against a distant MySql db.
$(window).on('load', function () {
alert('Alert after page load');
}
});
Here is what I would do.
Also I would use a template function to make the construction of select2nd easier.
#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include <string>
/*
* A class to extract the second part of a pair
*/
template<typename T>
struct select2nd
{
typename T::second_type operator()(T const& value) const
{return value.second;}
};
/*
* A utility template function to make the use of select2nd easy.
* Pass a map and it automatically creates a select2nd that utilizes the
* value type. This works nicely as the template functions can deduce the
* template parameters based on the function parameters.
*/
template<typename T>
select2nd<typename T::value_type> make_select2nd(T const& m)
{
return select2nd<typename T::value_type>();
}
int main()
{
std::map<int,std::string> m;
std::vector<std::string> v;
/*
* Please note: You must use std::back_inserter()
* As transform assumes the second range is as large as the first.
* Alternatively you could pre-populate the vector.
*
* Use make_select2nd() to make the function look nice.
* Alternatively you could use:
* select2nd<std::map<int,std::string>::value_type>()
*/
std::transform(m.begin(),m.end(),
std::back_inserter(v),
make_select2nd(m)
);
}
Newest version of C# - C# 7.1 allows to create async console app. To enable C# 7.1 in project, you have to upgrade your VS to at least 15.3, and change C# version to C# 7.1
or C# latest minor version
. To do this, go to Project properties -> Build -> Advanced -> Language version.
After this, following code will work:
internal class Program
{
public static async Task Main(string[] args)
{
(...)
}
DO Not Use EventEmitter for your service communication.
You should use one of the Observable types. I personally like BehaviorSubject.
Simple example:
You can pass initial state, here I passing null
let subject = new BehaviorSubject(null);
When you want to update the subject
subject.next(myObject)
Observe from any service or component and act when it gets new updates.
subject.subscribe(this.YOURMETHOD);
You are wrong about LocalDateTime
: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):
A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.
The difference between the two is that Instant
represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant
objects created at the same moment in two different places of the Earth will have exactly the same value.
Rather than changing the connection string, you can use the IsValidDateTime
property of the MySqlDateTime
object to help you determine if you can cast the object as a DateTime
.
I had a scenario where I was trying to load data from an "UpdateTime" column that was only explicitly set when there was an update to the row (as opposed to the InsertedTime which was always set). For this case, I used the MySqlDataReader.GetMySqlDateTime
method like so:
using (MySqlDataReader reader = await MySqlHelper.ExecuteReaderAsync(...))
{
if (await reader.ReadAsync())
{
DateTime? updateTime = reader.GetMySqlDateTime("UpdateTime").IsValidDateTime ? (DateTime?)reader["UpdateTime"] : null;
}
}
Assuming a C-style array a
of size N
, with elements of a type implicitly convertible from 0
, the following sets all the elements to values constructed from 0
.
std::fill(a, a+N, 0);
Note that this is not the same as "emptying" or "clearing".
Edit: Following james Kanze's suggestion, in C++11 you could use the more idiomatic alternative
std::fill( std::begin( a ), std::end( a ), 0 );
In the absence of C++11, you could roll out your own solution along these lines:
template <typename T, std::size_t N> T* end_(T(&arr)[N]) { return arr + N; }
template <typename T, std::size_t N> T* begin_(T(&arr)[N]) { return arr; }
std::fill( begin_( a ), end_( a ), 0 );
Bro, moment.js is awesome for this: The diff method is what you want: http://momentjs.com/docs/#/displaying/difference/
The below function return array of years from the year to the current year.
const getYears = (from = 2017) => {_x000D_
const diff = moment(new Date()).diff(new Date(`01/01/${from}`), 'years') ;_x000D_
return [...Array(diff >= 0 ? diff + 1 : 0).keys()].map((num) => {_x000D_
return from + num;_x000D_
});_x000D_
}_x000D_
_x000D_
console.log(getYears(2016));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:
String endpointUrl = ...;
QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
"EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
"EchoServicePort");
/** Create a service and add at least one port to it. **/
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);
/** Create a Dispatch instance from a service.**/
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,
SOAPMessage.class, Service.Mode.MESSAGE);
/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
// Create a message. This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();
// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();
// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
"http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();
/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);
/** Process the response. **/
I tried to install scikit-image but got the following error when I tried to install the .whl file even though my installed version of python was 2.7 32-bit. scikit_image-0.12.3-cp27-cp27m-win32.whl is not a supported wheel on this platform.
However I also got this message before the error message:
You are using pip version 7.1.0, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
I then ran the command python -m pip install --upgrade pip
and then pip install scikit_image-0.12.3-cp27-cp27m-win32.whl
worked fine. I hope this can help someone!
In bootstrap 4 use "autoHide : true"
$('#datepicker1').datepicker({
autoHide: true,
format: 'mm-yyyy',
endDate: new Date()
});
I'm not sure why the simplest way has been ignored/omitted in the answers above:
SELECT FORMAT(GetDate(),'yyyy-MM-dd');--= 2020-01-02
SELECT FORMAT(GetDate(),'dd MMM yyyy HH:mm:ss');-- = 02 Jan 2020 08:08:08
I prefer the second one because whichever language you speak, you will understand what date it is!
Also SQL Server always 'understands' it when you send that to your save procedure, regardless of which regional formats are set in the computers - I always use full year (yyyy), month name (MMM) and 24 hour format (capital HH) for hour in my programming.
Check out Regular Expressions.
If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.
I've found that Valamas' and Lepu's answers above are the most straightforward answers that deal with images of unknown size, or of known size that you'd rather not hard-code into your CSS. I just have a few small tweaks: remove irrelevant styles, size it to 200px to match the question, and add max-height/max-width to handle images that may be too large.
div.image-thumbnail
{
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
max-height: 200px;
max-width: 200px;
}
None of the current answers show the InputStream
being closed (this will leak a file descriptor), and/or don't deal with .getResourceAsStream()
returning null when the resource is not found (this will lead to a NullPointerException
with the confusing message, "inStream parameter is null"
). You need something like the following:
String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
if (inputStream == null) {
throw new FileNotFoundException(propertiesFilename);
}
prop.load(inputStream);
} catch (IOException e) {
throw new RuntimeException(
"Could not read " + propertiesFilename + " resource file: " + e);
}
Try with enabling the sub-thread as daemon-thread.
Recommended:
from threading import Thread
t = Thread(target=<your-method>)
t.daemon = True # This thread dies when main thread (only non-daemon thread) exits.
t.start()
Inline:
t = Thread(target=<your-method>, daemon=True).start()
Old API:
t.setDaemon(True)
t.start()
When your main thread terminates ("i.e. when I press Ctrl+C"), other threads will also be killed by the instructions above.
The named ones are all raster graphics, but beside that don't forget the more and more important vectorgraphics. There are compressed and uncompressed types (in a more or less way), but they're all lossless. Most important are:
Okey,Other people's view are very clear, but I would like to do some added, as follow:
Cursor tempCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
//do Time-consuming Operations
Cursor.Current = tempCursor;
It appears that the functionality previously present in the react-cookie
npm package has been moved to universal-cookie
. The relevant example from the universal-cookie repository now is:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman
The first push should be a:
git push -u origin branchname
That would make sure:
origin
',simple
'Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.
In JQuery I don't think that click() accepts two functions for toggling. You should use the toggle() function for that: http://docs.jquery.com/Events/toggle
How about using the wsdl /server
or wsdl /serverinterface
switches?
As far as I understand the wsdl.exe command line properties, that's what you're looking for.
- ADVANCED -
/server
Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy
classes.
On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!
Marc
UPDATE:
When I use wsdl /server
on a WSDL file, I get this file created:
[WebService(Namespace="http://.......")]
public abstract partial class OneCrmServiceType : System.Web.Services.WebService
{
/// <remarks/>
[WebMethod]
public abstract void OrderCreated(......);
}
This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.
You can always add the "yourservice.asmx" manually - it doesn't really contain much:
<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs"
Class="YourServiceNamespace.YourServiceClass" %>
clone() was designed with several mistakes (see this question), so it's best to avoid it.
From Effective Java 2nd Edition, Item 11: Override clone judiciously
Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.
This book also describes the many advantages copy constructors have over Cloneable/clone.
All standard collections have copy constructors. Use them.
List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);
Disclaimer: I don't do much C#
You are trying to modify the DictionaryEntry object which is stored in the HashTable. The Hashtable only stores one object -- your instance of DictionaryEntry. Changing the Key or the Value is enough to change the HashTable and cause the enumerator to become invalid.
You can do it outside of the loop:
if(hashtable.Contains(key))
{
hashtable[key] = value;
}
by first creating a list of all the keys of the values you wish to change and iterate through that list instead.
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
If using a SASS version (eg: thomas-mcdonald's one), then you may want to be slightly more dynamic (honor existing variables) and create all badge contexts using the same technique as used for labels:
// Colors
// Contextual variations of badges
// Bootstrap 3.0 removed contexts for badges, we re-introduce them, based on what is done for labels
.badge-default {
@include label-variant($label-default-bg);
}
.badge-primary {
@include label-variant($label-primary-bg);
}
.badge-success {
@include label-variant($label-success-bg);
}
.badge-info {
@include label-variant($label-info-bg);
}
.badge-warning {
@include label-variant($label-warning-bg);
}
.badge-danger {
@include label-variant($label-danger-bg);
}
The LESS equivalent should be straightforward.
Simply call getUrl() on URLConnection instance after calling getInputStream():
URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();
If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:
HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );
Remove the panel background
<item name="android:windowBackground">@color/transparent_color</item>
<color name="transparent_color">#00000000</color>
This is Mystyle:
<style name="ThemeDialogCustom">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowBackground">@color/transparent_color</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:colorBackgroundCacheHint">@null</item>
</style>
Which i have added to the constructor.
Add textColor :
<item name="android:textColor">#ff0000</item>
In my case, I had to add using System.Data.Entity;
Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.