This command:
iconv -f utf-8 -t utf-8 -c file.txt
will clean up your UTF-8 file, skipping all the invalid characters.
-f is the source format
-t the target format
-c skips any invalid sequence
I know I'm really late to the game, but here goes.
What I did was take the HTTP_HOST server variable ($_SERVER['HTTP_HOST']
) and the number of letters in the domain (so for example.com
it would be 11).
Then I used the substr
function to get the subdomain. I did
$numberOfLettersInSubdomain = strlen($_SERVER['HTTP_HOST'])-12
$subdomain = substr($_SERVER['HTTP_HOST'], $numberOfLettersInSubdomain);
I cut the substring off at 12 instead of 11 because substrings start on 1 for the second parameter. So now if you entered test.example.com, the value of $subdomain
would be test
.
This is better than using explode
because if the subdomain has a .
in it, this will not cut it off.
curl
without any options will perform a GET request. It will simply return the data from the URI specified. Not retrieve the file itself to your local machine.
When you do,
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
You will receive binary data:
|?>?$! <R?HP@T*?Pm?Z??jU???ZP+UAUQ@?
??{X\? K???>0c?yF[i?}4?!?V¸?H_?)nO#?;I??vg^_ ??-Hm$$N0.
???%Y[?L?U3?_^9??P?T?0'u8?l?4 ...
In order to save this, you can use:
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png > image.png
to store that raw image data inside of a file.
An easier way though, is just to use wget
.
$ wget https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
$ ls
.
..
apple-touch-icon-144x144-precomposed.png
If you'll go through these steps:
brew install jmeter
and hit Enterjmeter
and hit Enter againYou won't have to solve any kind of issue. Don't thank
You can convert most of the columns by just calling convert_objects
:
In [36]:
df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date object
WD int64
Manpower float64
2nd object
CTR object
2ndU float64
T1 int64
T2 int64
T3 int64
T4 float64
dtype: object
For column '2nd' and 'CTR' we can call the vectorised str
methods to replace the thousands separator and remove the '%' sign and then astype
to convert:
In [39]:
df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date object
WD int64
Manpower float64
2nd int32
CTR float64
2ndU float64
T1 int64
T2 int64
T3 int64
T4 object
dtype: object
In [40]:
df.head()
Out[40]:
Date WD Manpower 2nd CTR 2ndU T1 T2 T3 T4
0 2013/4/6 6 NaN 2645 5.27 0.29 407 533 454 368
1 2013/4/7 7 NaN 2118 5.89 0.31 257 659 583 369
2 2013/4/13 6 NaN 2470 5.38 0.29 354 531 473 383
3 2013/4/14 7 NaN 2033 6.77 0.37 396 748 681 458
4 2013/4/20 6 NaN 2690 5.38 0.29 361 528 541 381
Or you can do the string handling operations above without the call to astype
and then call convert_objects
to convert everything in one go.
UPDATE
Since version 0.17.0
convert_objects
is deprecated and there isn't a top-level function to do this so you need to do:
df.apply(lambda col:pd.to_numeric(col, errors='coerce'))
See the docs and this related question: pandas: to_numeric for multiple columns
Looks like its looking for VC compilers, so you could try to mention compiler type with -c mingw32
, since you have msys
python setup.py install -c mingw32
I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.
Transparent Actionbar:
values/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>
<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
<item name="android:windowContentOverlay">@null</item>
<item name="windowActionBarOverlay">true</item>
<item name="colorPrimary">@android:color/transparent</item>
</style>
<style name="AppTheme.ActionBar" parent="AppTheme">
<item name="windowActionBarOverlay">false</item>
<item name="colorPrimary">@color/default_yellow</item>
</style>
values-v21/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>
<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
<item name="colorPrimary">@android:color/transparent</item>
</style>
<style name="AppTheme.ActionBar" parent="AppTheme">
<item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
<item name="colorPrimary">@color/default_yellow</item>
</style>
Now you can use these themes in your AndroidManifest.xml
to specify which activities will have a transparent or colored ActionBar
:
<activity
android:name=".MyTransparentActionbarActivity"
android:theme="@style/AppTheme.ActionBar.Transparent"/>
<activity
android:name=".MyColoredActionbarActivity"
android:theme="@style/AppTheme.ActionBar"/>
Note: in API>=21 to get the Actionbar
transparent you need to get the Statusbar
transparent too, otherwise will not respect your colour styles and will stay light-grey.
Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
But you'll notice a funky result:
This happens because when the Statusbar
is transparent the layout will use its height. To prevent this we just need to:
SOLUTION ONE:
Add this line android:fitsSystemWindows="true"
in your layout view container of whatever you want to be placed bellow the Actionbar:
...
<LinearLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
...
SOLUTION TWO:
Add a few lines to our previous method:
protected void setStatusBarTranslucent(boolean makeTranslucent) {
View v = findViewById(R.id.bellow_actionbar);
if (v != null) {
int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
TypedValue tv = new TypedValue();
getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
}
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
Where R.id.bellow_actionbar
will be the layout container view id of whatever we want to be placed bellow the Actionbar
:
...
<LinearLayout
android:id="@+id/bellow_actionbar"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
...
So this is it, it think I'm not forgetting something.
In this example I didn't use a Toolbar
but I think it'll have the same result. This is how I customize my Actionbar
:
@Override
protected void onCreate(Bundle savedInstanceState) {
View vg = getActionBarView();
getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(getContentView());
if (vg != null) {
getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayUseLogoEnabled(false);
}
setStatusBarTranslucent(true);
}
Note: this is an abstract class
that extends ActionBarActivity
Hope it helps!
I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe
eg. 'This is John's place'
Here MYSQL assumes two sentence 'This is John' 's place'
You can put 'This is John''s place'. I think it should work that way.
Another simplest way to connect is through an OdbcConnection using App.config file like this
<appSettings>
<add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True"/>
</appSettings>
MyDB.mdb is my database file and it is present in current primary application folder with main exe file.
if your mdf file has password then use like this
<appSettings>
<add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True;Jet OLEDB:Database Password=Admin$@123"/>
</appSettings>
In Windows nslookup
the command is
ls -d somedomain.com > outfile.txt
which stores the subdomain list in outfile.txt
few domains these days allow this
The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.
Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)
Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.
You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).
Open your info.plist file of your project with any editor of your preference, then add this code at the end of the file before the last
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"
strProcess = "EXCEL.EXE"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Wscript.Sleep(1000) 'Sleep 1 second
'msgbox colProcesses.count 'optional to show the loop works
Loop
Credit to: http://crimsonshift.com/scripting-check-if-process-or-program-is-running-and-start-it/
I am working through the same need and I believe your timeframe is incorrect.
Try these:
You should be using 24 hours as your base. The number after -mtime should be relative to 24 hours. Thus -.5 is the equivalent of 12 hours, because 12 hours is half of 24 hours.
You should definitely avoid using <jsp:...>
tags. They're relics from the past and should always be avoided now.
Use the JSTL.
Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a
public SomeType getQuestionPaperID() {
//...
}
method in your bean.
Once you have that, you can display the value of this property using this code :
<c:out value="${Questions.questionPaperID}" />
or, to specifically target the session scoped attributes (in case of conflicts between scopes) :
<c:out value="${sessionScope.Questions.questionPaperID}" />
Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.
You can use Array#filter
function and additional array for storing sorted values;
var recordsSorted = []
ids.forEach(function(e) {
recordsSorted.push(records.filter(function(o) {
return o.empid === e;
}));
});
console.log(recordsSorted);
Result:
[ [ { empid: 1, fname: 'X', lname: 'Y' } ],
[ { empid: 4, fname: 'C', lname: 'Y' } ],
[ { empid: 5, fname: 'C', lname: 'Y' } ] ]
In my case, the error occured when using a service from an angular module located in an npm package, where the service requires injection of HttpClient
. When installing the npm package, a duplicate node_modules
directory was created inside the package directory due to version conflict handling of npm (engi-sdk-client
is the module containing the service):
Obviously, the dependency to HttpClient
is not resolved correctly, as the locations of HttpClientModule
injected into the service (lives in the duplicate node_modules
directory) and the one injected in app.module
(the correct node_modules
) don't match.
I've also had this error in other setups containing a duplicate node_modules
directory due to a wrong npm install
call.
This defective setup also leads to the described runtime exception No provider for HttpClient!
.
TL;DR; Check for duplicate
node_modules
directories, if none of the other solutions work!
This can help you
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
<form method='post' id='userform' action='thisform.php'> <tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
</td> </tr> </table> <input type='submit' class='buttons'> </form>
<?php
if (isset($_POST['checkboxvar']))
{
print_r($_POST['checkboxvar']);
}
?>
You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.
To echo checked options into your email you would then do this:
echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want
Please keep in mind you should always sanitize your input as needed.
For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays
StringBuilder s = new StringBuilder(token.length());
CharacterIterator it = new StringCharacterIterator(token);
for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
switch (ch) {
case '&':
s.append("&");
break;
case '<':
s.append("<");
break;
case '>':
s.append(">");
break;
default:
s.append(ch);
break;
}
}
token = s.toString();
Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -
NSLog(@"%@",documentsDirectory);
and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file
>>> text=u'abcd'
>>> str(text)
'abcd'
If the string only contains ascii characters.
You can use -i to update the file without using '>' operator. The following command will delete the first line from the file and save it to the file.
sed -i '1d' filename
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
Since, you are able to run Python in PowerShell. You can just do python <scriptName>.py
to run the script. So, for a script named test.py
containing
name = raw_input("Enter your name: ")
print "Hello, " + name
The PowerShell session would be
PS C:\Python27> python test.py
Enter your name: Monty Python
Hello, Monty Python
PS C:\Python27>
It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.
Chrome developer tools has this feature built-in. Bring up the developer tools (pressing F12 is one way), in the Sources tab, the bottom left bar has a set of icons. The "{}" icon is "Pretty print" and does this conversion on demand.
UPDATE: IE9 "F12 developer tools" also has a "Format JavaScript" feature in the Script tab under the Tools icon there. (see Tip #4 in F12 The best kept web debugging secret)
A quick warning, this a pretty wordy answer.
print is tricky sometimes, I had some problems with it when I first started. What you want is a few spaces in between two variables after you print them right? There's many ways to do this, as shown in the above answers.
This is your code:
count = 1
conv = count * 2.54
print count, conv
It's output is this:
1 2.54
If you want spaces in between, you can do it the naive way by sticking a string of spaces in between them. The variables count and conv need to be converted to string types to concatenate(join) them together. This is done with str().
print (str(count) + " " + str(conv))
### Provides an output of:
1 2.54
To do this is the newer, more pythonic way, we use the % sign in conjunction with a letter to denote the kind of value we're using. Here I use underscores instead of spaces to show how many there are. The modulo before the last values just tells python to insert the following values in, in the order we provided.
print ('%i____%s' % (count, conv))
### provides an output of:
1____2.54
I used %i for count because it is a whole number, and %s for conv, because using %i in that instance would provide us with "2" instead of "2.54" Technically, I could've used both %s, but it's all good.
I hope this helps!
-Joseph
P.S. if you want to get complicated with your formatting, you should look at prettyprint for large amounts of text such as dictionaries and tuple lists(imported as pprint) as well as which does automatic tabs, spacing and other cool junk.
Here's some more information about strings in the python docs. http://docs.python.org/library/string.html#module-string
Yes. You may style any HTML element by its tag name, like this:
select {
font-weight: bold;
}
Of course, you can also use a CSS class to style it, like any other element:
<select class="important">
<option>Important Option</option>
<option>Another Important Option</option>
</select>
<style type="text/css">
.important {
font-weight: bold;
}
</style>
I also had the same error , angular 7
<button (click)="Addcity(city.name)" [(ngModel)]="city.name" class="dropdown-item fontstyle"
*ngFor="let city of Cities; let i = index">
{{city.name}}
</button>
I just added ngDefaultControl
<button (click)="Addcity(city.name)" [(ngModel)]="city.name" ngDefaultControl class="dropdown-item fontstyle"
*ngFor="let city of Cities; let i = index">
{{city.name}}
It seems System.gc()
do not work on Art Android 6.0.1 Nexus 5x, So I use Runtime.getRuntime().gc();
instead.
If you are not using SSMS then here is the syntax:
ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)
Delete your existing workspace and then recreate the workspace and add your projects.
You can combine both in the same date function call
date("d-m-Y H:i:s");
Do something like this:
<script>
function changeColor(id)
{
document.getElementById(id).style.color = "#ff0000"; // forecolor
document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>
<div id="myid">Hello There !!</div>
<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>
Here is how you might do it with generics:
public T GetAnything<T>()
{
T t = //Code to create instance
return t;
}
But you would have to know what type you wanted returned at design time. And that would mean that you could just call a different method for each creation...
When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser
as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.
One option is to read the whole body using ioutil.ReadAll()
, which gives you the body as a byte slice.
You may use bytes.NewBuffer()
to obtain an io.Reader
from a byte slice.
The last missing piece is to make the io.Reader
an io.ReadCloser
, because bytes.Buffer
does not have a Close()
method. For this you may use ioutil.NopCloser()
which wraps an io.Reader
, and returns an io.ReadCloser
, whose added Close()
method will be a no-op (does nothing).
Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.
Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!
If you also want to read the response body, then you have to wrap the http.ResponseWriter
you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).
Here's a simple ResponseWriter
wrapper, which just caches the data, so it'll be available after the subsequent handler returns:
type MyResponseWriter struct {
http.ResponseWriter
buf *bytes.Buffer
}
func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
return mrw.buf.Write(p)
}
Note that MyResponseWriter.Write()
just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write()
method) and write the data immediately to the wrapped / embedded ResponseWriter
. You may even modify the data. You have full control.
Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.
Putting the pieces together, here's a full working example:
func loginmw(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return
}
// Work / inspect body. You may even modify it!
// And now set a new body, which will simulate the same data we read:
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
// Create a response wrapper:
mrw := &MyResponseWriter{
ResponseWriter: w,
buf: &bytes.Buffer{},
}
// Call next handler, passing the response wrapper:
handler.ServeHTTP(mrw, r)
// Now inspect response, and finally send it out:
// (You can also modify it before sending it out!)
if _, err := io.Copy(w, mrw.buf); err != nil {
log.Printf("Failed to send out response: %v", err)
}
})
}
Use the wait
built-in:
process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait
For the above example, 4 processes process1
... process4
would be started in the background, and the shell would wait until those are completed before starting the next set.
From the GNU manual:
wait [jobspec or pid ...]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:
import pandas as pd
import numpy as np
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
which displays
This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:
constants.name = ['pie','eek']
C
However it appears to have some limitations:
Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):
constants.loc[2] = dict(name='bogus', value=123.456)
constants['comment'] = ['fee','fie','fo']
constants
which looks ok but:
C
Formatting works only for values, not index entries:
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
constants.set_index('name',inplace=True)
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
OK here are my 2 cents: try passing path with each backslash as double backslash. I have found sometimes calling WIN API requires that.
The solution indicated by Guannan Shen has one drawback that usually goes unnoticed.
When you run sudo R
in order to run install.packages()
as superuser, the directories in which you install the library end up belonging to root
user, a.k.a., the superuser.
So, next time you need to update your libraries, you will not remember that you ran sudo
, therefore leaving root
as the owner of the files and directories; that eventually causes the error when trying to move files, because no one can overwrite root
but themself.
That can be averted by running
sudo chown -R yourusername:yourusername *
in the directory lib
that contains your local libraries, replacing yourusername
by the adequated value in your installation. Then you try installing once again.
The error suggests that the code you are using is expecting a virtual directory to be setup on IIS.
Look up the documentation and add the required virtual directory. It should be a directory that has a web.config
in it (not the root directory).
If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.
Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.
You could build it like this:
<?php
Schema::create('feeds', function($table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->morphs('target');
});
Build the feed model like so:
<?php
class Feed extends Eloquent
{
protected $fillable = ['user_id', 'target_type', 'target_id'];
public function user()
{
return $this->belongsTo('User');
}
public function target()
{
return $this->morphTo();
}
}
Then keep it up to date with something like:
<?php
Vote::created(function(Vote $vote) {
$target_type = 'Vote';
$target_id = $vote->id;
$user_id = $vote->user_id;
Feed::create(compact('target_type', 'target_id', 'user_id'));
});
You could make the above much more generic/robust—this is just for demonstration purposes.
At this point, your feed items are really easy to retrieve all at once:
<?php
Feed::whereIn('user_id', $my_friend_ids)
->with('user', 'target')
->orderBy('created_at', 'desc')
->get();
try this:
select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '[email protected]' )),3,32)
Java Version of Haversine Algorithm based on Roman Makarov`s reply to this thread
public class HaversineAlgorithm {
static final double _eQuatorialEarthRadius = 6378.1370D;
static final double _d2r = (Math.PI / 180D);
public static int HaversineInM(double lat1, double long1, double lat2, double long2) {
return (int) (1000D * HaversineInKM(lat1, long1, lat2, long2));
}
public static double HaversineInKM(double lat1, double long1, double lat2, double long2) {
double dlong = (long2 - long1) * _d2r;
double dlat = (lat2 - lat1) * _d2r;
double a = Math.pow(Math.sin(dlat / 2D), 2D) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r)
* Math.pow(Math.sin(dlong / 2D), 2D);
double c = 2D * Math.atan2(Math.sqrt(a), Math.sqrt(1D - a));
double d = _eQuatorialEarthRadius * c;
return d;
}
}
There is also one more solution for that kind of problem, which is rather rare, I think, and you may experience it, if you are using vim on OS X Sierra. Actually, it's a problem with Esc button — not with vim. For example, I wasnt able to exit fullscreen video on youtube using Esc, but I lived with that for a few months until I had experienced the same problem with vim.
I found this solution. If you are lazy enough to follow external link, switching off Siri and killing the process in Activity Monitor helped.
You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.
You therefore need to use javascript when the response returns to show a messagebox of some sort.
OR
using jquery on the button that calls the controller action
<script>
$(document).ready(function(){
$("#submitButton").on("click",function()
{
alert('Your Message');
});
});
<script>
You're looking for either git reset HEAD^ --soft
or git reset HEAD^ --mixed
.
There are 3 modes to the reset command as stated in the docs:
git reset HEAD^ --soft
undo the git commit
. Changes still exist in the working tree(the project folder) + the index (--cached)
git reset HEAD^ --mixed
undo git commit
+ git add
. Changes still exist in the working tree
git reset HEAD^ --hard
Like you never made these changes to the codebase. Changes are gone from the working tree.
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
The following code assumes that your table has the ID 'MyTable'
<script language="JavaScript"> <!-- var oRows = document.getElementById('MyTable').getElementsByTagName('tr'); var iRowCount = oRows.length; alert('Your table has ' + iRowCount + ' rows.'); //--> </script>
Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)
Java doesn't (yet) have a good built-in Time
class (it has one for JDBC queries, but that's not what you want).
One option would be use the JodaTime APIs and its LocalTime class.
Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date
comparison functions to see if it is before or after some other time:
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");
try {
Date userDate = parser.parse(someOtherDate);
if (userDate.after(ten) && userDate.before(eighteen)) {
...
}
} catch (ParseException e) {
// Invalid date was entered
}
Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:
Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
String hourString = m.group(1);
String minuteString = m.group(2);
int hour = Integer.parseInt(hourString);
int minute = Integer.parseInt(minuteString);
if (hour >= 10 && hour <= 18) {
...
}
}
It really all depends on what you are trying to accomplish.
What is your polynomial? If you're "processing" it, I'm envisioning some sort of tree of sub-expressions being generated at some point, and would think that it would be much simpler to use that to generate your string than to re-parse the raw expression with a regex.
Just throwing a different way of thinking out there. I'm not sure what else is going on in your app.
Here is a simple answer. Hope it helps someone.
import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
public String post(SomeRequest someRequest) {
// create a list the headers
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
interceptors.add(new HttpHeaderInterceptor("username", "user123"));
interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
// initialize RestTemplate
RestTemplate restTemplate = new RestTemplate();
// set header interceptors here
restTemplate.setInterceptors(interceptors);
// post the request. The response should be JSON string
String response = restTemplate.postForObject(Url, someRequest, String.class);
return response;
}
The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.
For the MS-SQL server driver (Microsoft SQL Server JDBC Driver).
try using:
logging.level.com.microsoft.sqlserver.jdbc=debug
in your application.properties file.
My personal preference is to set:
logging.level.com.microsoft.sqlserver.jdbc=info
logging.level.com.microsoft.sqlserver.jdbc.internals=debug
You can look at these links for reference:
Try this on Ruby. It will return a new date/time the specified number of days in the future
DateTime.now.days_since(10)
Ta da:
NSInteger myInteger = 42;
int myInt = (int) myInteger;
NSInteger
is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)
try this:
Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
If you want the caret down symbol, remove the "appearence: none" it implies to remove webkit and moz- as well from select in css.
Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1
in order to call the method:
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var theType = DLL.GetType("DLL.Class1");
var c = Activator.CreateInstance(theType);
var method = theType.GetMethod("Output");
method.Invoke(c, new object[]{@"Hello"});
Console.ReadLine();
}
}
If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.
AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.
We need to add angular-cookies.min.js file to use cookie feature.
Here is some method of AngularJS Cookie.
get(key); // This method returns the value of given cookie key.
getObject(key); //This method returns the deserialized value of given cookie key.
getAll(); //This method returns a key value object with all the cookies.
put(key, value, [options]); //This method sets a value for given cookie key.
remove(key, [options]); //This method remove given cookie.
Example
Html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>
JavaScript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);
I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.
Are you sure that the data stored in the database is actually a question mark? I would tend to suspect from the sample data that the problem is one of character set conversion where ?
is being used as the replacement character when the character can't be represented in the client character set. Possibly, the database is actually storing Microsoft "smart quote" characters rather than simple apostrophes.
What does the DUMP
function show is actually stored in the database?
SELECT column_name,
dump(column_name,1016)
FROM your_table
WHERE <<predicate that returns just the sample data you posted>>
What application are you using to view the data? What is the client's NLS_LANG
set to?
What is the database and national character set? Is the data stored in a VARCHAR2
column? Or NVARCHAR2
?
SELECT parameter, value
FROM v$nls_parameters
WHERE parameter LIKE '%CHARACTERSET';
If all the problem characters are stored in the database as 0x19 (decimal 25), your REPLACE
would need to be something like
UPDATE table_name
SET column1 = REPLACE(column1, chr(25), q'[']'),
column2 = REPLACE(column2, chr(25), q'[']'),
...
columnN = REPLACE(columnN, chr(25), q'[']')
WHERE INSTR(column1,chr(25)) > 0
OR INSTR(column2,chr(25)) > 0
...
OR INSTR(columnN,chr(25)) > 0
First of all we should get clear that Hadoop was created as a faster alternative to RDBMS. To process large amount of data at a very fast rate which earlier took a lot of time in RDBMS.
Now one should know the two terms :
Structured Data : This is the data that we used in traditional RDBMS and is divided into well defined structures.
Unstructured Data : This is important to understand, about 80% of the world data is unstructured or semi structured. These are the data which are on its raw form and cannot be processed using RDMS. Example : facebook, twitter data. (http://www.dummies.com/how-to/content/unstructured-data-in-a-big-data-environment.html).
So, large amount of data was being generated in the last few years and the data was mostly unstructured, that gave birth to HADOOP. It was mainly used for very large amount of data that takes unfeasible amount of time using RDBMS. It had many drawbacks, that it could not be used for comparatively small data in real time but they have managed to remove its drawbacks in the newer version.
Before going further I would like to tell that a new Big Data tool is created when they see a fault on the previous tools. So, whichever tool you will see that is created has been done to overcome the problem of the previous tools.
Hadoop can be simply said as two things : Mapreduce and HDFS. Mapreduce is where the processing takes place and HDFS is the DataBase where data is stored. This structure followed WORM principal i.e. write once read multiple times. So, once we have stored data in HDFS, we cannot make changes. This led to the creation of HBASE, a NOSQL product where we can make changes in the data also after writing it once.
But with time we saw that Hadoop had many faults and for that we created different environment over the Hadoop structure. PIG and HIVE are two popular examples.
HIVE was created for people with SQL background. The queries written is similar to SQL named as HIVEQL. HIVE was developed to process completely structured data. It is not used for ustructured data.
PIG on the other hand has its own query language i.e. PIG LATIN. It can be used for both structured as well as unstructured data.
Moving to the difference as when to use HIVE and when to use PIG, I don't think anyone other than the architect of PIG could say. Follow the link : https://developer.yahoo.com/blogs/hadoop/comparing-pig-latin-sql-constructing-data-processing-pipelines-444.html
I've found this useful:
select translate('your string','_0123456789','_') from dual
If the result is NULL, it's numeric (ignoring floating point numbers.)
However, I'm a bit baffled why the underscore is needed. Without it the following also returns null:
select translate('s123','0123456789', '') from dual
There is also one of my favorite tricks - not perfect if the string contains stuff like "*" or "#":
SELECT 'is a number' FROM dual WHERE UPPER('123') = LOWER('123')
When you have 'NA' values in the column, then
sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)
Adding "-EA Stop" solved this for me.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
There is even a better way to create a Map along with initialization:
Map<String, String> rightHereMap = new HashMap<String, String>()
{
{
put("key1", "value1");
put("key2", "value2");
}
};
For more options take a look here How can I initialise a static Map?
Its true the official documentation (Apache log4net™ Manual - Introduction) states there are the following levels...
... but oddly when I view assembly log4net.dll, v1.2.15.0 sealed class log4net.Core.Level I see the following levels defined...
public static readonly Level Alert;
public static readonly Level All;
public static readonly Level Critical;
public static readonly Level Debug;
public static readonly Level Emergency;
public static readonly Level Error;
public static readonly Level Fatal;
public static readonly Level Fine;
public static readonly Level Finer;
public static readonly Level Finest;
public static readonly Level Info;
public static readonly Level Log4Net_Debug;
public static readonly Level Notice;
public static readonly Level Off;
public static readonly Level Severe;
public static readonly Level Trace;
public static readonly Level Verbose;
public static readonly Level Warn;
I have been using TRACE in conjunction with PostSharp OnBoundaryEntry and OnBoundaryExit for a long time. I wonder why these other levels are not in the documentation. Furthermore, what is the true priority of all these levels?
In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.
1) make sure the media attribute of bootstrap-responsive.css
is screen
.
<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />
2) create a print.css
and make sure its media attribute print
<link href="/css/print.css" rel="stylesheet" media="print" />
3) inside print.css
, add the "width" of your website in html & body
html,
body {
width: 1200px !important;
}
4.) reproduce the necessary media query classes in print.css
because they were inside bootstrap-responsive.css
and we have disabled it when printing.
.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}
Here is full version of print.css
:
html,
body {
width: 1200px !important;
}
.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}
action=""
will resolve to the page's address. action="#"
will resolve to the page's address + #
, which will mean an empty fragment identifier.
Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.
Usually, authors just put #
in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action=""
(or omit it if validation allows).
There are three packagers, and two compilers:
free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC
http://search.cpan.org/dist/B-C/perlcompile.pod
(Note: perlfaq3 is still wrong)
For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.
Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.
I reccomend you to use the following tools for online base64 encoding/decoding:
Check the "Format as Data URL" option to format as a Data URL.
Try this // html example
<span>✓</span>
// css example
span {
content: "\2713";
}
Typically, software will run in different environments:
development
testing
staging
production
The dependencies which are declared in the require
section of composer.json
are typically dependencies which are required for running an application or a package in
staging
production
environments, whereas the dependencies declared in the require-dev
section are typically dependencies which are required in
developing
testing
environments.
For example, in addition to the packages used for actually running an application, packages might be needed for developing the software, such as:
friendsofphp/php-cs-fixer
(to detect and fix coding style issues)squizlabs/php_codesniffer
(to detect and fix coding style issues)phpunit/phpunit
(to drive the development using tests)Now, in development
and testing
environments, you would typically run
$ composer install
to install both production
and development
dependencies.
However, in staging
and production
environments, you only want to install dependencies which are required for running the application, and as part of the deployment process, you would typically run
$ composer install --no-dev
to install only production
dependencies.
In other words, the sections
require
require-dev
indicate to composer
which packages should be installed when you run
$ composer install
or
$ composer install --no-dev
That is all.
Note Development dependencies of packages your application or package depend on will never be installed
For reference, see:
I use the ffmpeg-python
binding. You can find more information here.
import ffmpeg
(
ffmpeg
.input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
.output('movie.mp4')
.run()
)
// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
return float32(in)
}
// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
return float64(in)
}
ALTER USER myuser WITH SUPERUSER;
You can read more at the Documentation
If you have double-encoded UTF8 characters (various smart quotes, dashes, apostrophe ’, quotation mark “, etc), in mysql you can dump the data, then read it back in to fix the broken encoding.
Like this:
mysqldump -h DB_HOST -u DB_USER -p DB_PASSWORD --opt --quote-names \
--skip-set-charset --default-character-set=latin1 DB_NAME > DB_NAME-dump.sql
mysql -h DB_HOST -u DB_USER -p DB_PASSWORD \
--default-character-set=utf8 DB_NAME < DB_NAME-dump.sql
This was a 100% fix for my double encoded UTF-8.
Source: http://blog.hno3.org/2010/04/22/fixing-double-encoded-utf-8-data-in-mysql/
With a simple for loop:
var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
// Using $() to re-wrap the element.
$(testimonials[i]).text('a');
}
Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:
var array = [];
calendars.forEach(function(item) {
array.push(item.id);
});
console.log(array);
You can also use the map()
method to generate an Array filled with the results of calling the specified function on each element. Something like:
var array = calendars.map(function(item) {
return item.id;
});
console.log(array);
And, since ECMAScript 2015 has been released, you may start seeing examples using let
or const
instead of var
and the =>
syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):
let array = calendars.map(item => item.id);
console.log(array);
A very simple Java 8 solution:
File[] directories = new File("/your/path/").listFiles(File::isDirectory);
It's equivalent to using a FileFilter (works with older Java as well):
File[] directories = new File("/your/path/").listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory();
}
});
There are many different freely available java linear algebra libraries. http://www.ujmp.org/java-matrix/benchmark/ Unfortunately that benchmark only gives you info about matrix multiplication (with transposing the test does not allow the different libraries to exploit their respective design features).
What you should look at is how these linear algebra libraries perform when asked to compute various matrix decompositions. http://ojalgo.org/matrix_compare.html
My setup for a Debian server:
I had the problem when multiple packages contained the same name.
For example apache2
. So this was my solution:
function _apt_install() {
apt-get install -y $1 > /dev/null
}
function _apt_install_norecommends() {
apt-get install -y --no-install-recommends $1 > /dev/null
}
function _apt_available() {
if [ `apt-cache search $1 | grep -o "$1" | uniq | wc -l` = "1" ]; then
echo "Package is available : $1"
PACKAGE_INSTALL="1"
else
echo "Package $1 is NOT available for install"
echo "We can not continue without this package..."
echo "Exitting now.."
exit 0
fi
}
function _package_install {
_apt_available $1
if [ "${PACKAGE_INSTALL}" = "1" ]; then
if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
echo "package is already_installed: $1"
else
echo "installing package : $1, please wait.."
_apt_install $1
sleep 0.5
fi
fi
}
function _package_install_no_recommends {
_apt_available $1
if [ "${PACKAGE_INSTALL}" = "1" ]; then
if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
echo "package is already_installed: $1"
else
echo "installing package : $1, please wait.."
_apt_install_norecommends $1
sleep 0.5
fi
fi
}
Very often the error /usr/bin/codesign failed with exit code 1
occurred in case the user has no file extensions for texture files in Models.scnassets
folder. macOS
very often generates a files with hidden extensions.
For example: you have a file
myTexture
but it must include an extension as well –myTexture.png
.
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
BasicResponseHandler throws if the status is not 2xx. See its javadoc.
Here is how I would do it:
HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream
Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout()
. The problem is that update()
is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update
is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update()
within the code block is within scope now.
I also prefer the $(function() { ... }
shortened block form and rather than calling setTimeout()
within update()
you can just use setInterval()
instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.
I had the same problem and finally resolved it by changing the order of pem blocks in certificate file.
The cert block should be put in the beginning of the file, then intermediate blocks, then root block.
I realized this problem by comparing a problematic certificate file with a working certificate file.
You can use Apache commons-lang
StringUtils.isEmpty(String str)
- Checks if a String is empty ("") or null.
or
StringUtils.isBlank(String str)
- Checks if a String is whitespace, empty ("") or null.
the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API
For Laravel 5.8, setting the csrf meta tag for your layout and setting the request header for csrf in ajax settings won't work if you are using ajax to submit a form that already includes a _token
input field generated by the Laravel blade templating engine.
You must include the already generated csrf token from the form with your ajax request because the server would be expecting it and not the one in your meta tag.
For instance, this is how the _token
input field generated by Blade looks like:
<form>
<input name="_token" type="hidden" value="cf54ty6y7yuuyyygytfggfd56667DfrSH8i">
<input name="my_data" type="text" value="">
<!-- other input fields -->
</form>
You then submit your form with ajax like this:
<script>
$(document).ready(function() {
let token = $('form').find('input[name="_token"]').val();
let myData = $('form').find('input[name="my_data"]').val();
$('form').submit(function() {
$.ajax({
type:'POST',
url:'/ajax',
data: {_token: token, my_data: myData}
// headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, // unnecessary
// other ajax settings
});
return false;
});
});
</script>
The csrf token in the meta header is only useful when you are submitting a form without a Blade generated _token
input field.
It seems that the latest function for this in windows 7 is robocopy.
Usage example:
robocopy <source> <destination> /e /xf <file to exclude> <another file>
/e copies subdirectories including empty ones, /xf excludes certain files from being copied.
More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx
You can create very easy a dropdown from this array (It was a time-consuming task to put this together and test it). We already use this list in some of our apps.
It is very important to store timezone identifiers in your database and not just the timezone offset like "GMT+2", because of Daylight Saving Times.
I updated/corrected the timezones list (also checkout: https://github.com/paptamas/timezones):
<?php
$timezones = array (
'(GMT-11:00) Midway Island' => 'Pacific/Midway',
'(GMT-11:00) Samoa' => 'Pacific/Samoa',
'(GMT-10:00) Hawaii' => 'Pacific/Honolulu',
'(GMT-09:00) Alaska' => 'US/Alaska',
'(GMT-08:00) Pacific Time (US & Canada)' => 'America/Los_Angeles',
'(GMT-08:00) Tijuana' => 'America/Tijuana',
'(GMT-07:00) Arizona' => 'US/Arizona',
'(GMT-07:00) Chihuahua' => 'America/Chihuahua',
'(GMT-07:00) La Paz' => 'America/Chihuahua',
'(GMT-07:00) Mazatlan' => 'America/Mazatlan',
'(GMT-07:00) Mountain Time (US & Canada)' => 'US/Mountain',
'(GMT-06:00) Central America' => 'America/Managua',
'(GMT-06:00) Central Time (US & Canada)' => 'US/Central',
'(GMT-06:00) Guadalajara' => 'America/Mexico_City',
'(GMT-06:00) Mexico City' => 'America/Mexico_City',
'(GMT-06:00) Monterrey' => 'America/Monterrey',
'(GMT-06:00) Saskatchewan' => 'Canada/Saskatchewan',
'(GMT-05:00) Bogota' => 'America/Bogota',
'(GMT-05:00) Eastern Time (US & Canada)' => 'US/Eastern',
'(GMT-05:00) Indiana (East)' => 'US/East-Indiana',
'(GMT-05:00) Lima' => 'America/Lima',
'(GMT-05:00) Quito' => 'America/Bogota',
'(GMT-04:00) Atlantic Time (Canada)' => 'Canada/Atlantic',
'(GMT-04:30) Caracas' => 'America/Caracas',
'(GMT-04:00) La Paz' => 'America/La_Paz',
'(GMT-04:00) Santiago' => 'America/Santiago',
'(GMT-03:30) Newfoundland' => 'Canada/Newfoundland',
'(GMT-03:00) Brasilia' => 'America/Sao_Paulo',
'(GMT-03:00) Buenos Aires' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Georgetown' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Greenland' => 'America/Godthab',
'(GMT-02:00) Mid-Atlantic' => 'America/Noronha',
'(GMT-01:00) Azores' => 'Atlantic/Azores',
'(GMT-01:00) Cape Verde Is.' => 'Atlantic/Cape_Verde',
'(GMT+00:00) Casablanca' => 'Africa/Casablanca',
'(GMT+00:00) Edinburgh' => 'Europe/London',
'(GMT+00:00) Greenwich Mean Time : Dublin' => 'Etc/Greenwich',
'(GMT+00:00) Lisbon' => 'Europe/Lisbon',
'(GMT+00:00) London' => 'Europe/London',
'(GMT+00:00) Monrovia' => 'Africa/Monrovia',
'(GMT+00:00) UTC' => 'UTC',
'(GMT+01:00) Amsterdam' => 'Europe/Amsterdam',
'(GMT+01:00) Belgrade' => 'Europe/Belgrade',
'(GMT+01:00) Berlin' => 'Europe/Berlin',
'(GMT+01:00) Bern' => 'Europe/Berlin',
'(GMT+01:00) Bratislava' => 'Europe/Bratislava',
'(GMT+01:00) Brussels' => 'Europe/Brussels',
'(GMT+01:00) Budapest' => 'Europe/Budapest',
'(GMT+01:00) Copenhagen' => 'Europe/Copenhagen',
'(GMT+01:00) Ljubljana' => 'Europe/Ljubljana',
'(GMT+01:00) Madrid' => 'Europe/Madrid',
'(GMT+01:00) Paris' => 'Europe/Paris',
'(GMT+01:00) Prague' => 'Europe/Prague',
'(GMT+01:00) Rome' => 'Europe/Rome',
'(GMT+01:00) Sarajevo' => 'Europe/Sarajevo',
'(GMT+01:00) Skopje' => 'Europe/Skopje',
'(GMT+01:00) Stockholm' => 'Europe/Stockholm',
'(GMT+01:00) Vienna' => 'Europe/Vienna',
'(GMT+01:00) Warsaw' => 'Europe/Warsaw',
'(GMT+01:00) West Central Africa' => 'Africa/Lagos',
'(GMT+01:00) Zagreb' => 'Europe/Zagreb',
'(GMT+02:00) Athens' => 'Europe/Athens',
'(GMT+02:00) Bucharest' => 'Europe/Bucharest',
'(GMT+02:00) Cairo' => 'Africa/Cairo',
'(GMT+02:00) Harare' => 'Africa/Harare',
'(GMT+02:00) Helsinki' => 'Europe/Helsinki',
'(GMT+02:00) Istanbul' => 'Europe/Istanbul',
'(GMT+02:00) Jerusalem' => 'Asia/Jerusalem',
'(GMT+02:00) Kyiv' => 'Europe/Helsinki',
'(GMT+02:00) Pretoria' => 'Africa/Johannesburg',
'(GMT+02:00) Riga' => 'Europe/Riga',
'(GMT+02:00) Sofia' => 'Europe/Sofia',
'(GMT+02:00) Tallinn' => 'Europe/Tallinn',
'(GMT+02:00) Vilnius' => 'Europe/Vilnius',
'(GMT+03:00) Baghdad' => 'Asia/Baghdad',
'(GMT+03:00) Kuwait' => 'Asia/Kuwait',
'(GMT+03:00) Minsk' => 'Europe/Minsk',
'(GMT+03:00) Nairobi' => 'Africa/Nairobi',
'(GMT+03:00) Riyadh' => 'Asia/Riyadh',
'(GMT+03:00) Volgograd' => 'Europe/Volgograd',
'(GMT+03:30) Tehran' => 'Asia/Tehran',
'(GMT+04:00) Abu Dhabi' => 'Asia/Muscat',
'(GMT+04:00) Baku' => 'Asia/Baku',
'(GMT+04:00) Moscow' => 'Europe/Moscow',
'(GMT+04:00) Muscat' => 'Asia/Muscat',
'(GMT+04:00) St. Petersburg' => 'Europe/Moscow',
'(GMT+04:00) Tbilisi' => 'Asia/Tbilisi',
'(GMT+04:00) Yerevan' => 'Asia/Yerevan',
'(GMT+04:30) Kabul' => 'Asia/Kabul',
'(GMT+05:00) Islamabad' => 'Asia/Karachi',
'(GMT+05:00) Karachi' => 'Asia/Karachi',
'(GMT+05:00) Tashkent' => 'Asia/Tashkent',
'(GMT+05:30) Chennai' => 'Asia/Calcutta',
'(GMT+05:30) Kolkata' => 'Asia/Kolkata',
'(GMT+05:30) Mumbai' => 'Asia/Calcutta',
'(GMT+05:30) New Delhi' => 'Asia/Calcutta',
'(GMT+05:30) Sri Jayawardenepura' => 'Asia/Calcutta',
'(GMT+05:45) Kathmandu' => 'Asia/Katmandu',
'(GMT+06:00) Almaty' => 'Asia/Almaty',
'(GMT+06:00) Astana' => 'Asia/Dhaka',
'(GMT+06:00) Dhaka' => 'Asia/Dhaka',
'(GMT+06:00) Ekaterinburg' => 'Asia/Yekaterinburg',
'(GMT+06:30) Rangoon' => 'Asia/Rangoon',
'(GMT+07:00) Bangkok' => 'Asia/Bangkok',
'(GMT+07:00) Hanoi' => 'Asia/Bangkok',
'(GMT+07:00) Jakarta' => 'Asia/Jakarta',
'(GMT+07:00) Novosibirsk' => 'Asia/Novosibirsk',
'(GMT+08:00) Beijing' => 'Asia/Hong_Kong',
'(GMT+08:00) Chongqing' => 'Asia/Chongqing',
'(GMT+08:00) Hong Kong' => 'Asia/Hong_Kong',
'(GMT+08:00) Krasnoyarsk' => 'Asia/Krasnoyarsk',
'(GMT+08:00) Kuala Lumpur' => 'Asia/Kuala_Lumpur',
'(GMT+08:00) Perth' => 'Australia/Perth',
'(GMT+08:00) Singapore' => 'Asia/Singapore',
'(GMT+08:00) Taipei' => 'Asia/Taipei',
'(GMT+08:00) Ulaan Bataar' => 'Asia/Ulan_Bator',
'(GMT+08:00) Urumqi' => 'Asia/Urumqi',
'(GMT+09:00) Irkutsk' => 'Asia/Irkutsk',
'(GMT+09:00) Osaka' => 'Asia/Tokyo',
'(GMT+09:00) Sapporo' => 'Asia/Tokyo',
'(GMT+09:00) Seoul' => 'Asia/Seoul',
'(GMT+09:00) Tokyo' => 'Asia/Tokyo',
'(GMT+09:30) Adelaide' => 'Australia/Adelaide',
'(GMT+09:30) Darwin' => 'Australia/Darwin',
'(GMT+10:00) Brisbane' => 'Australia/Brisbane',
'(GMT+10:00) Canberra' => 'Australia/Canberra',
'(GMT+10:00) Guam' => 'Pacific/Guam',
'(GMT+10:00) Hobart' => 'Australia/Hobart',
'(GMT+10:00) Melbourne' => 'Australia/Melbourne',
'(GMT+10:00) Port Moresby' => 'Pacific/Port_Moresby',
'(GMT+10:00) Sydney' => 'Australia/Sydney',
'(GMT+10:00) Yakutsk' => 'Asia/Yakutsk',
'(GMT+11:00) Vladivostok' => 'Asia/Vladivostok',
'(GMT+12:00) Auckland' => 'Pacific/Auckland',
'(GMT+12:00) Fiji' => 'Pacific/Fiji',
'(GMT+12:00) International Date Line West' => 'Pacific/Kwajalein',
'(GMT+12:00) Kamchatka' => 'Asia/Kamchatka',
'(GMT+12:00) Magadan' => 'Asia/Magadan',
'(GMT+12:00) Marshall Is.' => 'Pacific/Fiji',
'(GMT+12:00) New Caledonia' => 'Asia/Magadan',
'(GMT+12:00) Solomon Is.' => 'Asia/Magadan',
'(GMT+12:00) Wellington' => 'Pacific/Auckland',
'(GMT+13:00) Nuku\'alofa' => 'Pacific/Tongatapu'
);
?>
jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)
var singleAjax = function singleAjax_constructor(url, params) {
// remember last jQuery's get request
if (this.lastInstance) {
this.lastInstance.abort(); // triggers .always() and .fail()
this.lastInstance = false;
}
// how to use Deferred : http://api.jquery.com/category/deferred-object/
var $def = new $.Deferred();
// pass the deferrer's request handlers into the get response handlers
this.lastInstance = $.get(url, params)
.fail($def.reject) // triggers .always() and .fail()
.success($def.resolve); // triggers .always() and .done()
// return the deferrer's "control object", the promise object
return $def.promise();
}
// initiate first call
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// second call kills first one
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// here you might use .always() .fail() .success() etc.
this way work properly and I used it in many projects! for example I get data of views the last 30 days:
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(*) as views'))
->groupBy('date')
->get();
If you want to get the number of views based on different IPs, you can use the DISTINCT
like below :
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(DISTINCT user_ip) as visitors'))
->groupBy('date')
->get();
You can easily customize it by manipulating the columns name
-If you host multiple domain names (Optional)
-If all those domain names are using https (as they should)
-if you want all those domain names to use www dot domainName
This will avoid doble redirection (http://non www to http://www and then to https://www)
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*)$ https://www.%1$1 [R=301,L]
</VirtualHost>
And
<VirtualHost *:443>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>
You should change the redirection code 301 to the most convenient one
{% load static %}
Please add this template tag on top of the HTML or base HTML file
Use angular.copy when assigning value of object or array to another variable and that object
value should not be changed.
Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
function($scope) {_x000D_
$scope.printToConsole = function() {_x000D_
$scope.main = {_x000D_
first: 'first',_x000D_
second: 'second'_x000D_
};_x000D_
_x000D_
$scope.child = angular.copy($scope.main);_x000D_
console.log('Main object :');_x000D_
console.log($scope.main);_x000D_
console.log('Child object with angular.copy :');_x000D_
console.log($scope.child);_x000D_
_x000D_
$scope.child.first = 'last';_x000D_
console.log('New Child object :')_x000D_
console.log($scope.child);_x000D_
console.log('Main object after child change and using angular.copy :');_x000D_
console.log($scope.main);_x000D_
console.log('Assing main object without copy and updating child');_x000D_
_x000D_
$scope.child = $scope.main;_x000D_
$scope.child.first = 'last';_x000D_
console.log('Main object after update:');_x000D_
console.log($scope.main);_x000D_
console.log('Child object after update:');_x000D_
console.log($scope.child);_x000D_
}_x000D_
}_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
first: 'first',_x000D_
second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
<button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
If you are using Cloudflare then this is always the Cloudflare IP address from the node which is serving you.
In this case you get the real IP address from the $_SERVER['HTTP_FORWARDED_FOR']
entry as described in the the other answers.
Brace expansion doesn't work, but *
, ?
and []
do. If you set shopt -s extglob
then you can also use extended pattern matching:
?()
- zero or one occurrences of pattern*()
- zero or more occurrences of pattern+()
- one or more occurrences of pattern@()
- one occurrence of pattern!()
- anything except the patternHere's an example:
shopt -s extglob
for arg in apple be cd meet o mississippi
do
# call functions based on arguments
case "$arg" in
a* ) foo;; # matches anything starting with "a"
b? ) bar;; # matches any two-character string starting with "b"
c[de] ) baz;; # matches "cd" or "ce"
me?(e)t ) qux;; # matches "met" or "meet"
@(a|e|i|o|u) ) fuzz;; # matches one vowel
m+(iss)?(ippi) ) fizz;; # matches "miss" or "mississippi" or others
* ) bazinga;; # catchall, matches anything not matched above
esac
done
Let’s say you are making an executable that uses some functions found in a library.
If the library you are using is static, the linker will copy the object code for these functions directly from the library and insert them into the executable.
Now if this executable is run it has every thing it needs, so the executable loader just loads it into memory and runs it.
If the library is dynamic the linker will not insert object code but rather it will insert a stub which basically says this function is located in this DLL at this location.
Now if this executable is run, bits of the executable are missing (i.e the stubs) so the loader goes through the executable fixing up the missing stubs. Only after all the stubs have been resolved will the executable be allowed to run.
To see this in action delete or rename the DLL and watch how the loader will report a missing DLL error when you try to run the executable.
Hence the name Dynamic Link Library, parts of the linking process is being done dynamically at run time by the executable loader.
One a final note, if you don't link to the DLL then no stubs will be inserted by the linker, but Windows still provides the GetProcAddress API that allows you to load an execute the DLL function entry point long after the executable has started.
Try the SetField method:
table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);
This should get the job done and is a bit "cleaner" than using Rows[i][j].
The reason why your code doesn't work is because $watch
by default does reference check. So in a nutshell it make sure that the object which is passed to it is new object. But in your case you are just modifying some property of form object not creating a new one. In order to make it work you can pass true
as the third parameter.
$scope.$watch('form', function(newVal, oldVal){
console.log('invoked');
}, true);
It will work but You can use $watchCollection which will be more efficient then $watch because $watchCollection
will watch for shallow properties on form object. E.g.
$scope.$watchCollection('form', function (newVal, oldVal) {
console.log(newVal, oldVal);
});
The below definition is from the real world example.
Example Overview
For every client data, we are storing an identifier to find that client data and we will send back that identifier to that client for reference.
POST
PUT
PATCH
Note: On Put Method, We are not throwing an exception if an identifier is not found. But in Patch method, we are throwing an exception if the identifier is not found.
Do let me know if you have any queries on the above.
Eclipse is launching your application with whatever JRE you defined in your launch configuration. Since you're running the 32-bit Eclipse, you're running/debugging against its 32-bit SWT libraries, and you'll need to run a 32-bit JRE.
Your 64-bit JRE is, for whatever reason, your default Installed JRE.
To change this, first make sure you have a 32-bit JRE configured in the Installed JREs preference. Go to Window -> Preferences and navigate to Java -> Installed JREs:
You can click Add and navigate to your 32-bit JVM's JAVA_HOME
to add it.
Then in your Run Configuration, find your Eclipse Application and make sure the Runtime JRE is set to the 32-bit JRE you just configured:
(Note the combobox that is poorly highlighted.)
Don't try replacing SWT jars, that will likely end poorly.
If you want to achieve the same for the jquery-ui selectmenu control then you have to set 'display: none' in the open event handler and add '-menu' to the id string.
<select id="myid">
<option value="" disabled="disabled" selected="selected">Please select name</option>
<option value="Tom">Tom</option>
<option value="Marry">Mary</option>
<option value="Jane">Jane</option>
<option value="Harry">Harry</option>
</select>
$('select#listsTypeSelect').selectmenu({
change: function( event, data ) {
alert($(this).val());
},
open: function( event, ui ) {
$('ul#myid-menu li:first-child').css('display', 'none');
}
});
It worked - To change in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.
Default VM Arguments = -Xms128m -Xmx1024m
If you happened to run npm install
command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.
Like @benvie said, its more efficient to change a style sheet rather than using jQuery.css (which will loop through all of the elements in the set). It is also important not to add a new style to the head every time the function is called because it will create a memory leak and thousands of CSS rules that have to be individually applied by the browser. I would do something like this:
//Add the stylesheet once and store a cached jQuery object
var $style = $("<style type='text/css'>").appendTo('head');
function onResize() {
var css = "\
.someClass {\
left: "+leftVal+";\
width: "+widthVal+";\
height: "+heightVal+";\
}";
$style.html(css);
}
This solution will change your styles by modifying the DOM only once per resize. Note that for effective js minification and compression, you probably don't want to pretty-print the css, but I did for clarity.
On Android platforms, Oruxmaps (http://www.oruxmaps.com) does a great job at caching all WMS sources. It is available in the play store. I use it daily in remote areas without any connectivity, works like a charm.
When using JetBrains IDE's with Git, "stashing and unstashing actions are supported in addition to shelving and unshelving. These features have much in common; the major difference is in the way patches are generated and applied. Shelve can operate with either individual files or bunch of files, while Stash can only operate with a whole bunch of changed files at once. Here are some more details on the differences between them."
You should define the struct out of the class like this:
#include <iostream>
using namespace std;
struct X
{
int v;
};
class E
{
public:
X var;
};
int main(){
E object;
object.var.v=10;
return 0;
}
I wrote a very large blog post about the topic. I've found that unit testing alone isn't worth the work and usually gets cut when deadlines get closer.
Instead of talking about unit testing from the "test-after" verification point of view, we should look at the true value found when you set out to write a spec/test/idea before the implementation.
This simple idea has changed the way I write software and I wouldn't go back to the "old" way.
Here is the optimised solution in Swift5, including handling the wrong indexPath. - Michael Lin Liu
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
targetContentOffset.pointee = scrollView.contentOffset
//M: Get the first visiable item's indexPath from visibaleItems.
var indexPaths = *YOURCOLLECTIONVIEW*.indexPathsForVisibleItems
indexPaths.sort()
var indexPath = indexPaths.first!
//M: Use the velocity to detect the paging control movement.
//M: If the movement is forward, then increase the indexPath.
if velocity.x > 0{
indexPath.row += 1
//M: If the movement is in the next section, which means the indexPath's row is out range. We set the indexPath to the first row of the next section.
if indexPath.row == *YOURCOLLECTIONVIEW*.numberOfItems(inSection: indexPath.section){
indexPath.row = 0
indexPath.section += 1
}
}
else{
//M: If the movement is backward, the indexPath will be automatically changed to the first visiable item which is indexPath.row - 1. So there is no need to write the logic.
}
//M: Tell the collection view to scroll to the next item.
*YOURCOLLECTIONVIEW*.scrollToItem(at: indexPath, at: .left, animated: true )
}
Be very careful: all of the answers on this page are implicitly taking the decision of where the binning starts - the left-hand edge of the left-most bin, if you like - out of the user's hands. If the user is combining any of these functions for binning data with his/her own decision about where binning starts (as is done on the blog which is linked to above) the functions above are all incorrect. With an arbitrary starting point for binning 'Min', the correct function is:
bin(x) = width*(floor((x-Min)/width)+0.5) + Min
You can see why this is correct sequentially (it helps to draw a few bins and a point somewhere in one of them). Subtract Min from your data point to see how far into the binning range it is. Then divide by binwidth so that you're effectively working in units of 'bins'. Then 'floor' the result to go to the left-hand edge of that bin, add 0.5 to go to the middle of the bin, multiply by the width so that you're no longer working in units of bins but in an absolute scale again, then finally add back on the Min offset you subtracted at the start.
Consider this function in action:
Min = 0.25 # where binning starts
Max = 2.25 # where binning ends
n = 2 # the number of bins
width = (Max-Min)/n # binwidth; evaluates to 1.0
bin(x) = width*(floor((x-Min)/width)+0.5) + Min
e.g. the value 1.1 truly falls in the left bin:
Born2Smile's answer is only correct if the bin boundaries occur at (n+0.5)*binwidth (where n runs over integers). mas90's answer is only correct if the bin boundaries occur at n*binwidth.
neat and clean
void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...
Just add this somewhere in your code:
$(document).ready(
$('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
e.preventDefault();
}),
$('[data-toggle="collapse"]').on('click', function(e) {
e.preventDefault();
$($(this).data('target')).toggleClass('in');
})
);
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
Load testing = putting a specified amount of load on the server for certain amount of time. 100 simultaneous users for 10 minutes. Ensure stability of software. Stress testing = increasing the amount of load steadily until the software crashes. 10 simultaneous users increasing every 2 minutes until the server crashes.
To make a comparison to weight lifting: You "max" your weight to see what you can do for 1 rep (stress testing) and then on regular workouts you do 85% of your max value for 3 sets of 10 reps (load testing)
If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
?var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);??????
After long time stuck this issue, finally solved like this
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
create folder like this res/values/dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="textsize">8sp</dimen>
</resources>
COPY README.md package.json gulpfile.js __BUILD_NUMBER ./
or
COPY ["__BUILD_NUMBER", "README.md", "gulpfile", "another_file", "./"]
You can also use wildcard characters in the sourcefile specification. See the docs for a little more detail.
Directories are special! If you write
COPY dir1 dir2 ./
that actually works like
COPY dir1/* dir2/* ./
If you want to copy multiple directories (not their contents) under a destination directory in a single command, you'll need to set up the build context so that your source directories are under a common parent and then COPY
that parent.
TestClass.instance_methods
or without all the inherited methods
TestClass.instance_methods - Object.methods
(Was 'TestClass.methods - Object.methods')
You can move your files to other folder and then pull whole folder.
adb shell mkdir /sdcard/tmp adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end) adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back adb shell rmdir /sdcard/tmp # remove temporary directory
Use scikit-learn:
from sklearn.preprocessing import MinMaxScaler
data = np.array([1,2,3]).reshape(-1, 1)
scaler = MinMaxScaler()
scaler.fit(data)
print(scaler.transform(data))
I tried using the the Jack's Asylum cover flow but it wouldn't let me easily remove and re-add an entire coverflow. I eventually found http://finnrudolph.de/ImageFlow and not only is it more reliable, it's easier to hook into, uses less markup, and doesn't jitter when flipping through images. It's by far the best I've found, and I've tried several on this page.
Two things come to mind:
If you are dealing with String[] instead of int[], We can use
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(StringArray));
For me it was simply that I hadn't added react-scripts
to the project so:
npm i -S react-scripts
If this doesn't work, then rm node_modules
as suggested by others
rm -r node_modules
npm i
The most likely explanations for that error are:
CreateProcess
requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute
rather than CreateProcess
.Reading down to the bottom of the code, I can see that the problem is number 1.
There are multiple ways to do this:
data
in your table. Column properties, constraints, keys, indices, stored procedures, triggers, security settings, users, logons, etc. are not transferred. However it is very simple process and can be done simply by going through wizard in SQL Server Management Studio. Manual procedure for method #1 (using SSIS) is the following:
You can automate it by creating SSIS package and re-executing it any time you like to re-import the data. Note that you can only import using SSIS to a clean DB, you cannot do incremental updates to your local database once you already done it once.
Method #2 (SSID data plus schema objects) is very simple. First go though a steps described above, then create DB Creation script (righ click on database in SSMS, choose Generate Scripts -> Database Create). Then re-play this script on your local database.
Method #3 is described in the Blog here: http://dacguy.wordpress.com/2012/01/24/sql-azure-importexport-service-has-hit-production/. There is a video clip with the process of transferring DB contents to Azure Blob storage as BACPAC. After that you can copy the file locally and import it to your SQL instance. Process of importing BACPAC to Data-Tier application is described here: http://msdn.microsoft.com/en-us/library/hh710052.aspx.
If you have Qt/KDE installed, you can use kdialog, which pops up a Qt dialog window. You can easily specify to display a Yes/No dialog, OK/Cancel, simple text input, password input etc. You then have access to the return values from these dialogs at the shell.
These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.
if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
//Do not reload the gridview.
}
else
{
reload my gridview.
}
SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked
If you want a specific date in next month, you can do this:
// Calculate the timestamp
$expire = strtotime('first day of +1 month');
// Format the timestamp as a string
echo date('m/d/Y', $expire);
Note that this actually works more reliably where +1 month
can be confusing. For example...
Current Day | first day of +1 month | +1 month
---------------------------------------------------------------------------
2015-01-01 | 2015-02-01 | 2015-02-01
2015-01-30 | 2015-02-01 | 2015-03-02 (skips Feb)
2015-01-31 | 2015-02-01 | 2015-03-03 (skips Feb)
2015-03-31 | 2015-04-01 | 2015-05-01 (skips April)
2015-12-31 | 2016-01-01 | 2016-01-31
The MVC framework supports this natively. The System.Web.MVC.Controller.File controller provides methods to return a file by name/stream/array.
For example using a virtual path to the file you could do the following.
return File(virtualFilePath, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(virtualFilePath));
Reformatted the answer by @epascarello:
u.dotted {_x000D_
border-bottom: 1px dashed #999;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<u class="dotted">I like cheese</u>
_x000D_
Sometimes the reason of these errors are not the DataBinding
itself, but some other part of our code. In my case I had an error in Room
database so the compiler couldn't generate the binding classes and it gives me these errors.
According to Google:
Previous versions of the data binding compiler generated the binding classes in the same step that compiles your managed code. If your managed code fails to compile, you might get multiple errors reporting that the binding classes aren't found. The new data binding compiler prevents these errors by generating the binding classes before the managed compiler builds your app.
So to enable new data binding compiler, add the following option to your gradle.properties file:
android.databinding.enableV2=true
You can also enable the new compiler in your gradle command by adding the following parameter:
-Pandroid.databinding.enableV2=true
Note that the new compiler in Android Studio version 3.2 is enabled by default.
You can't use CSS to disable Textbox. solution would be HTML Attribute.
disabled="disabled"
If you want to count all values at once you can do it very fast using numpy arrays and bincount
as follows
import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)
which gives
>>> array([0, 3, 1, 1, 2])
You should use the Spring Boot Maven Plugin:
<project>
...
<build>
...
<plugins>
...
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.1.RELEASE</version>
<configuration>
<profiles>
<profile>foo</profile>
<profile>bar</profile>
</profiles>
</configuration>
...
</plugin>
...
</plugins>
...
</build>
...
</project>
And in addition to the above nice answers.
RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.
Other SQL implementations have similar restrictions. The reason is that adding a column requires adding values for that column (logically, even if not physically), which default to NULL
. If you don't allow NULL
, and don't have a default
, what is the value going to be?
Since SQL Server supports ADD CONSTRAINT
, I'd recommend Pavel's approach of creating a nullable column, and then adding a NOT NULL
constraint after you've filled it with non-NULL
values.
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
When working on a project that requires the use of multiple dockerfiles, simply create each dockerfile in a separate directory. For instance,
app/ db/
Each of the above directories will contain their dockerfile. When an application is being built, docker will search all directories and build all dockerfiles.
Since there is the [vba] tag, split is also easy:
str1 = "001 baseball"
str2 = Split(str1)
Then use str2(1).
You can use System.arraycopy()
.
int[] source = new int[1000];
int[] part1 = new int[500];
int[] part2 = new int[500];
// (src , src-offset , dest , offset, count)
System.arraycopy(source, 0 , part1, 0 , part1.length);
System.arraycopy(source, part1.length, part2, 0 , part2.length);
Additionally for gists, it seems you must leave out the username
git remote set-url origin [email protected]:<Project code>
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
The approved solution doesn't work in my case, so my solution is the following one:
''' The column name in the example case is "Unnamed: 7"
but it works with any other name ("Unnamed: 0" for example). '''
df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)
# Then, drop the column as usual.
df.drop(["a"], axis=1, inplace=True)
Hope it helps others.
var idsArr = [];
$('#tableID').find('input[type=checkbox]:checked').each(function() {
idsArr .push(this.value);
});
console.log(idsArr);
The matrix you pasted
[[ 1, 8, 50],
[ 8, 64, 400],
[ 50, 400, 2500]]
Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)
Add this
node_modules/
to .gitignore
file to ignore all directories called node_modules
in current folder and any subfolders
There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.
The steps in Excel 2010 are:
In a cell enter a formula like this
=VLOOKUP(A2,$D$3:$E$5,2,FALSE)
which will return the matching value from the second part of your list.
Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.
The steps in Excel 2010 are:
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));
This article may be useful too http://mito-team.com/article/2012/collapse-button-for-ckeditor-for-drupal
There are code samples and step-by-step guide about building your own CKEditor plugin with custom button.
The shortest solution without any dependencies:
await new Promise(resolve => setTimeout(resolve, 5000));
<script type="text/javascript" runat="server">
public void Page_Load(object Sender, System.EventArgs e)
{
double rad=0.0;
TextBox1.Attributes.Add("Visible", "False");
if (TextBox1.Text != "")
rad = Convert.ToDouble(TextBox1.Text);
Button1.Attributes.Add("OnClick","alert("+ rad +")");
}
</script>
<asp:Button ID="Button1" runat="server" Text="Diameter"
style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server"
AutoPostBack="true"
style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>
use the help of this, hope it will be usefull
Let's, just as example:
public class Test { public Test() { System.out.println("NO ARGS"); } public Test(String s) { this(); System.out.println("1 ARG"); } public static void main(String args[]) { Test t = new Test("s"); } }
It will print
>>> NO ARGS >>> 1 ARG
The correct way to call the constructor is by:
this();
Others explained very well and just want to give with simple examples.
Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.
$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.'
It will give this:
All sorts of things are ignored in single quotes, like $ & * ; |.
The only thing that cannot be put within single quotes is a single quote.
Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.
$ echo "Here's how we can use single ' and double \" quotes within double quotes"
It will give this:
Here's how we can use single ' and double " quotes within double quotes
It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.
$ echo "The current Oracle SID is $ORACLE_SID"
It will give this:
The current Oracle SID is test
Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.
$ today=`date '+%A, %B %d, %Y'`
$ echo $today
It will give this:
Monday, September 28, 2015
If you are inside a .then() block and you want to execute a settimeout()
.then(() => {
console.log('wait for 10 seconds . . . . ');
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log('10 seconds Timer expired!!!');
resolve();
}, 10000)
});
})
.then(() => {
console.log('promise resolved!!!');
})
output will as shown below
wait for 10 seconds . . . .
10 seconds Timer expired!!!
promise resolved!!!
Happy Coding!
I suggest using Hits's answer, but adding a Locale format, this is how Android Developers recommends:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
return dateFormat.format(new Date()); // Find todays date
} catch (Exception e) {
e.printStackTrace();
return null;
}
The new C# 8.0 range operator can be a great shortcut to achieve this.
Example #1 (to answer the question):
string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd
Example #2 (to show you how awesome range operators are):
string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98
this style can be used in makefiles too (and in fact it is used quite often).
python - <<EOF
import sys
for r in range(3): print 'rob'
EOF
or
python - <<-EOF
import sys
for r in range(3): print 'rob'
EOF
in latter case leading tab characters are removed too (and some structured outlook can be achieved)
instead of EOF can stand any marker word not appearing in the here document at a beginning of a line (see also here documents in the bash manpage or here).
Little addition, to run an interpreter from the same folder, still using #!hashbang in scripts.
As example a php7.2 executable copied from /usr/bin is in a folder along a hello script.
#!./php7.2
<?php
echo "Hello!";
To run it:
./hello
Which behave just as equal as:
./php7.2 hello
The proper solutions with good documentation can be the tools linuxdeploy and/or appimage, this is using this method under the hood.
Try something like this to get the format you wanted:
Get-WebBinding | % {
$name = $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1'
New-Object psobject -Property @{
Name = $name
Binding = $_.bindinginformation.Split(":")[-1]
}
} | Group-Object -Property Name |
Format-Table Name, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap
Starting with matplotlib 1.4.0 there is now an an interactive backend for use in the notebook
%matplotlib notebook
There are a few version of IPython which do not have that alias registered, the fall back is:
%matplotlib nbagg
If that does not work update you IPython.
To play with this, goto tmpnb.org
and paste
%matplotlib notebook
import pandas as pd
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
df.plot(); plt.legend(loc='best')
into a code cell (or just modify the existing python demo notebook)
There are a few characters that are dissallowed in XML documents, even when you encapsulate data in CDATA-blocks.
If you generated the document you will need to entity encode it or strip it out. If you have an errorneous document, you should strip away these characters before trying to parse it.
See dolmens answer in this thread: Invalid Characters in XML
Where he links to this article: http://www.w3.org/TR/xml/#charsets
Basically, all characters below 0x20 is disallowed, except 0x9 (TAB), 0xA (CR?), 0xD (LF?)
A complete beginner like myself to the topic may find it harder to implement one of these answers than, if within your control, to resize the image yourself with an online editor or a photo editor like Photoshop.
A 500x500 image will appear larger on the map than a 50x50 image.
No programming required.
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
This is a very straightforward solution that I came up with after following conca's link and looking at background size. It blows the image up and then fits it centered into the outer container w/o scaling it.
<style>
#cropcontainer
{
width: 100%;
height: 100%;
background-size: 140%;
background-position: center;
background-repeat: no-repeat;
}
</style>
<div id="cropcontainer" style="background-image: url(yoururl); />
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
For negative number only, this is perfect.
^-\d*\.?\d+$
If you installed as admin ( and meant for all users )
C:\ProgramData\Anaconda3\Scripts\anaconda.exe
If you install as a normal user
C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe
if you have to pass the value you should enter url like this
localhost/yoururl/index.php/products_controller/delete_controller/70
and in controller function you can read like this
function delete_controller( $product_id = NULL ) {
echo $product_id;
}
If you are using Visual Studio, there is an easy way to setup and enable SSL using IIS Express explained here
Take a look at this recipe on GitHub: https://help.github.com/articles/importing-an-external-git-repository
I tried a number of methods before discovering git push --mirror
.
Worked like a charm!
There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.
The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip
that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.
Unzipping is easier - just treat it as a directory.
In case the web pages are lost again, here are a few of the relevant code snippets:
Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
If Len(Dir(sPath)) > 0 Then Kill sPath
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub
Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function
Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
Split97 = Evaluate("{""" & _
Application.Substitute(sStr, sdelim, """,""") & """}")
End Function
Sub Zip_File_Or_Files()
Dim strDate As String, DefPath As String, sFName As String
Dim oApp As Object, iCtr As Long, I As Integer
Dim FName, vArr, FileNameZip
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
strDate = Format(Now, " dd-mmm-yy h-mm-ss")
FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"
'Browse to the file(s), use the Ctrl key to select more files
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True, Title:="Select the files you want to zip")
If IsArray(FName) = False Then
'do nothing
Else
'Create empty Zip File
NewZip (FileNameZip)
Set oApp = CreateObject("Shell.Application")
I = 0
For iCtr = LBound(FName) To UBound(FName)
vArr = Split97(FName(iCtr), "\")
sFName = vArr(UBound(vArr))
If bIsBookOpen(sFName) Then
MsgBox "You can't zip a file that is open!" & vbLf & _
"Please close it and try again: " & FName(iCtr)
Else
'Copy the file to the compressed folder
I = I + 1
oApp.Namespace(FileNameZip).CopyHere FName(iCtr)
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(FileNameZip).items.Count = I
Application.Wait (Now + TimeValue("0:00:01"))
Loop
On Error GoTo 0
End If
Next iCtr
MsgBox "You find the zipfile here: " & FileNameZip
End If
End Sub
Sub Unzip1()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim strDate As String
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=False)
If Fname = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Create the folder name
strDate = Format(Now, " dd-mm-yy h-mm-ss")
FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"
'Make the normal folder in DefPath
MkDir FileNameFolder
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
'If you want to extract only one file you can use this:
'oApp.Namespace(FileNameFolder).CopyHere _
'oApp.Namespace(Fname).items.Item("test.txt")
MsgBox "You find the files here: " & FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub
You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:
// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");
// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
// Append the element to the end of Array list
dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?
See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/
This assumes that you're not using JQuery, and you only have the basic DOM API to work with.
Logging has different levels such as :
Trace – A fine-grained debug message, typically capturing the flow through the application.
Debug- A general debugging event should be logged under this.
ALL – All events could be logged.
INFO- An informational purpose, information written in plain english.
Warn- An event that might possible lead to an error.
Error- An error in the application, possibly recoverable.
Logging captured with debug level is information helpful to developers as well as other personnel, so it captures in broad range. If your code doesn't have exception or errors then you should be alright to use DEBUG level of logging, otherwise you should carefully choose options.
I tried http://gitstats.sourceforge.net/, starts are very interesting.
Once git clone git://repo.or.cz/gitstats.git
is done, go to that folder and say gitstats <git repo location> <report output folder>
(create a new folder for report as this generates lots of files)
Here is a quick list of stats from this:
I resolved this issue by escaping the inner double quotes
projectID=$(cat file.json | jq -r ".resource[] | select(.username==\"$EMAILID\") | .id")
I faced Same issue, the issues was there are some inner classes with the static keyword.After removing the static keyword it started working and also the inner class should implements to Serializable
class A implements Serializable{
class static B{
}
}
class A implements Serializable{
class B implements Serializable{
}
}
Update : STYLE GUIDE is now on Angular docs.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.
The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.
- John Papa
Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide
Yet another SQLite wrapper for Swift 2 and Swift 3: http://github.com/groue/GRDB.swift
Features:
An API that will look familiar to users of ccgus/fmdb
A low-level SQLite API that leverages the Swift standard library
A pretty Swift query interface for SQL-allergic developers
Support for the SQLite WAL mode, and concurrent database access for extra performance
A Record class that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations
Swift type freedom: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.
Database Migrations
Based on the above suggestions, the following data.table
solution worked very fast for me:
library(data.table)
set.seed(45)
DT <- data.table(matrix(sample(10, 10^7, TRUE), ncol=10))
system.time(
DT[, col_max := colnames(.SD)[max.col(.SD, ties.method = "first")]]
)
#> user system elapsed
#> 0.15 0.06 0.21
DT[]
#> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 col_max
#> 1: 7 4 1 2 3 7 6 6 6 1 V1
#> 2: 4 6 9 10 6 2 7 7 1 3 V4
#> 3: 3 4 9 8 9 9 8 8 6 7 V3
#> 4: 4 8 8 9 7 5 9 2 7 1 V4
#> 5: 4 3 9 10 2 7 9 6 6 9 V4
#> ---
#> 999996: 4 6 10 5 4 7 3 8 2 8 V3
#> 999997: 8 7 6 6 3 10 2 3 10 1 V6
#> 999998: 2 3 2 7 4 7 5 2 7 3 V4
#> 999999: 8 10 3 2 3 4 5 1 1 4 V2
#> 1000000: 10 4 2 6 6 2 8 4 7 4 V1
And also comes with the advantage that can always specify what columns .SD
should consider by mentioning them in .SDcols
:
DT[, MAX2 := colnames(.SD)[max.col(.SD, ties.method="first")], .SDcols = c("V9", "V10")]
In case we need the column name of the smallest value, as suggested by @lwshang, one just needs to use -.SD
:
DT[, col_min := colnames(.SD)[max.col(-.SD, ties.method = "first")]]
FOR SQLALCHEMY AND PYTHON
The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:
e = create_engine(
"mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
A simple solution would be:
package nl;
public class Padder {
public static void main(String[] args) {
String s = "123" ;
System.out.println("#"+(" " + s).substring(s.length())+"#");
}
}
The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.
You need to set both the user-agent and the referer:
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip
A more concise--but not necessarily faster--method is to use DataFrame.isin()
and DataFrame.any()
In [27]: n = 10
In [28]: df = DataFrame(randint(4, size=(n, 2)), columns=list('ab'))
In [29]: df
Out[29]:
a b
0 0 0
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
7 3 0
8 1 1
9 2 2
[10 rows x 2 columns]
In [30]: df.isin([1, 2])
Out[30]:
a b
0 False False
1 True True
2 True True
3 True False
4 True False
5 False True
6 True True
7 False False
8 True True
9 True True
[10 rows x 2 columns]
In [31]: df.isin([1, 2]).any(1)
Out[31]:
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True
dtype: bool
In [32]: df.loc[df.isin([1, 2]).any(1)]
Out[32]:
a b
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
8 1 1
9 2 2
[8 rows x 2 columns]
// This is for normal triangle
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print(" *");
}
System.out.print("\n");
}
// This is for left triangle, just removed space before printing *
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print("*");
}
System.out.print("\n");
}
#Use the small trick to make the data json interpret-able
#Since your data is not directly interpreted by json.loads()
>>> import json
>>> f=open("sampledata.txt","r+")
>>> data = f.read()
>>> for x in data.split("\n"):
... strlist = "["+x+"]"
... datalist=json.loads(strlist)
... for y in datalist:
... print(type(y))
... print(y)
...
...
<type 'dict'>
{u'0': [[10.8, 36.0], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'1': [[10.8, 36.1], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'2': [[10.8, 36.2], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'3': [[10.8, 36.300000000000004], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'4': [[10.8, 36.4], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'5': [[10.8, 36.5], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'6': [[10.8, 36.6], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'7': [[10.8, 36.7], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'8': [[10.8, 36.800000000000004], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'9': [[10.8, 36.9], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
Same everyday problem.
I just created a simple vc project to solve this problem.
It copies the file as Base64 encoded data directly to the clipboard, and then this can be pasted into the PuTTY console and decoded on the remote side.
This solution is for relatively small files (relative to the connection speed to your remote console).
Download clip_b64.exe
and place it in the SendTo folder (or a .lnk
shortcut to it). To open this folder, in the address bar of the explorer, enter shell:sendto
or %appdata%\Microsoft\Windows\SendTo
.
You may need to install VC 2017 redist to run it, or use the statically linked clip_b64s.exe
execution.
In the File Explorer, right-click the file you are transferring to open the context menu, then go to the "Send To" section and select Clip_B64
from the list.
Run the shell command base64 -d > file-name-you-want
and right-click in the console (or press Shift + Insert
) to place the clipboard content in it, and then press Ctrl + D
to finish.
voila
Your Approach is fine, but you can add UIActionSheet
with other way with ease.
You can add UIActionSheetDelegate
in UIViewController` like
class ViewController: UIViewController ,UIActionSheetDelegate
Set you method like,
@IBAction func downloadSheet(sender: AnyObject)
{
let actionSheet = UIActionSheet(title: "Choose Option", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Save", "Delete")
actionSheet.showInView(self.view)
}
You can get your button index when it clicked like
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
{
println("\(buttonIndex)")
switch (buttonIndex){
case 0:
println("Cancel")
case 1:
println("Save")
case 2:
println("Delete")
default:
println("Default")
//Some code here..
}
}
Update 1: for iOS8+
//Create the AlertController and add Its action like button in Actionsheet
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .ActionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel")
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default)
{ _ in
print("Save")
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default)
{ _ in
print("Delete")
}
actionSheetControllerIOS8.addAction(deleteActionButton)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)