On bitbucket.org the voted solution wouldn't work. Instead, when using headers (with ##), it is possible to reference them as anchors by prefixing them as #markdown-header-my-header-name, where #markdown-header- is an implicit prefix generated by the renderer, and the rest is the lower-cased header title with dashes replacing spaces.
Example
## My paragraph title
will produce an implicit anchor like this
#markdown-header-my-paragraph-title
The whole URL before each anchor reference is optional, i.e.
[Some text](#markdown-header-my-paragraph-title)
is equivalent of
[Some text](https://bitbucket.org/some_project/some_page#markdown-header-my-paragraph-title)
provided that they are in the same page.
Source: https://bitbucket.org/tutorials/markdowndemo/overview (edit source of this .md file and look at how anchors are made).
run cmd
Enter wmic baseboard get product,version,serialnumber
Press the enter key. The result you see under serial number column is your motherboard serial number
I use in my batch files - c:\progra~2\
instead of C:\Program Files (x86)\
and it works.
Here is an alternative that worked for me:
$('div#somediv').css({'width': '70%'});
I add 2 website domains, set "*" in subdomain is not working but specific subdomain "WWW" and non-subdomain have been worked for my websites using the same Google Map API key.
Hope it help.
div[disabled]
{
pointer-events: none;
opacity: 0.6;
background: rgba(200, 54, 54, 0.5);
background-color: yellow;
filter: alpha(opacity=50);
zoom: 1;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
-moz-opacity: 0.5;
-khtml-opacity: 0.5;
}
You've changed your scheme destination to a simulator instead of Generic iOS Device.
That's why it is greyed out.
A solution with reduce()
:
int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97
In the code above, reduce()
returns data in Optional
format, which you can convert to int
by getAsInt()
.
If we want to compare the max value with a certain number, we can set a start value in reduce()
:
int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100
In the code above, when reduce()
with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:
double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
Wouldn't the generic T t = new T();
work?
In my case , aLengthMenu is not working. So i used this. And it is working.
jQuery('#dyntable3').dataTable({
oLanguage: {sLengthMenu: "<select>"+
"<option value='100'>100</option>"+
"<option value='200'>200</option>"+
"<option value='300'>300</option>"+
"<option value='-1'>All</option>"+
"</select>"},
"iDisplayLength": 100
});
Thank you
I recently used prettytable
for rendering a nice ASCII table. It's similar to the postgres CLI output.
import pandas as pd
from prettytable import PrettyTable
data = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame(data, columns=['one', 'two', 'three'])
def generate_ascii_table(df):
x = PrettyTable()
x.field_names = df.columns.tolist()
for row in df.values:
x.add_row(row)
print(x)
return x
generate_ascii_table(df)
Output:
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
+-----+-----+-------+
You can use this one: • You can type it by pressing Alt key and typing 0149.
for API below 21, you can use theme attribute in EditText
put below code into style file
<style name="MyEditTextTheme">
<item name="colorControlNormal">#FFFFFF</item>
<item name="colorControlActivated">#FFFFFF</item>
<item name="colorControlHighlight">#FFFFFF</item>
</style>
use this style in EditText
as
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="@dimen/user_input_field_height"
android:layout_marginTop="40dp"
android:hint="@string/password_hint"
android:theme="@style/MyEditTextTheme"
android:singleLine="true" />
In Workbook events:
Private Sub Workbook_Open()
RunEveryTwoMinutes
End Sub
In a module:
Sub RunEveryTwoMinutes()
//Add code here for whatever you want to happen
Application.OnTime Now + TimeValue("00:02:00"), "RunEveryTwoMinutes"
End Sub
If you only want the first piece of code to execute after the workbook opens then just add a delay of 2 minutes into the Workbook_Open
event
By using the ref
keyword with reference types you are effectively passing a reference to the reference. In many ways it's the same as using the out
keyword but with the minor difference that there's no guarantee that the method will actually assign anything to the ref
'ed parameter.
Public Function _
CreateTextArrayFromSourceTexts(ParamArray SourceTexts() As Variant) As String()
ReDim TargetTextArray(0 To UBound(SourceTexts)) As String
For SourceTextsCellNumber = 0 To UBound(SourceTexts)
TargetTextArray(SourceTextsCellNumber) = SourceTexts(SourceTextsCellNumber)
Next SourceTextsCellNumber
CreateTextArrayFromSourceTexts = TargetTextArray
End Function
Example:
Dim TT() As String
TT = CreateTextArrayFromSourceTexts("hi", "bye", "hi", "bcd", "bYe")
Result:
TT(0)="hi"
TT(1)="bye"
TT(2)="hi"
TT(3)="bcd"
TT(4)="bYe"
Enjoy!
Edit: I removed the duplicatedtexts deleting feature and made the code smaller and easier to use.
If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv
In firebase-messaging:17.1.0
and newer the FirebaseInstanceIdService is deprecated, you can get the onNewToken
on the FirebaseMessagingService
class as explained on https://stackoverflow.com/a/51475096/1351469
But if you want to just get the token any time, then now you can do it like this:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( this.getActivity(), new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String newToken = instanceIdResult.getToken();
Log.e("newToken",newToken);
}
});
I was getting the same error even after doing above changes and what i did is
Right click on the project->properties->java compiler->Compiler compliance level->changes it to 1.6
This change is particular for the project. This should hopefully work.
As aready proposed in this answer and this other answer Microsoft.VisualBasic.CompilerServices.Operators.LikeString
could be a good option for simple tasks, when a RegExp is overkill. Syntax is different from RegExp and SQL LIKE operator, but it's really simple to learn (mainly because it's also very limited).
Assembly Microsoft.VisualBasic
must be added as a reference to the project to use this method.
For more information see Operators.LikeString Method and for a description of the syntax see Like Operator (Visual Basic).
It can be used as an extension method to String class:
/// <summary>
/// Visual Basic like operator. Performs simple, case insensitive, string pattern matching.
/// </summary>
/// <param name="thisString"></param>
/// <param name="pattern"> ? = Any single character. * = Zero or more characters. # = Any single digit (0–9)</param>
/// <returns>true if the string matches the pattern</returns>
public static bool Like(this string thisString, string pattern)
=> Microsoft.VisualBasic.CompilerServices.Operators
.LikeString(thisString, pattern, Microsoft.VisualBasic.CompareMethod.Text);
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
To really get this clear, here's my for-beginners answer:
You inputed the arguments in the wrong order.
A keyword argument has this style:
nullable=True, unique=False
A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:
name="Ricardo", fruit="chontaduro"
This syntax error asks you to first put name="Ricardo"
and all of its kind (non-keyword) before those like nullable=True.
How about select cast(cast my_datetime_field as date) as datetime)
? This results in the same date, with the time set to 00:00, but avoids any conversion to text and also avoids any explicit numeric rounding.
You can use IETester (http://www.my-debugbar.com/wiki/IETester/HomePage)
For me the problem was that spring was not able to download http://www.springframework.org/schema/beans/spring-beans.xsd or http://www.springframework.org/schema/context/spring-context.xsd
However I was able to access those from my browser as it was using my machines proxy. So I just copied the content of the two xsds to files named spring-beans.xsd and spring-context.xsd and replaced the http url with the file names and it worked for me.
Since Java 11 you may use that:
public FileReader(String fileName, Charset charset) throws IOException;
Usually for jumping people use Rigidbody2D.AddForce
with Forcemode.Impulse
. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.
Example:
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
Sometimes, even when the file is in the right directory, there is still the "file not found" exception. One thing you could do is to drop the text file inside eclipse, where your classes are, on the left side. It is going to ask you if you want to copy, click yes. Sometimes it helps.
This is an easy solution that counts the number of files in a directory containing sub-folders. It may come in handy;
import os
from pathlib import Path
def count_files(rootdir):
'''counts the number of files in each subfolder in a directory'''
for path in pathlib.Path(rootdir).iterdir():
if path.is_dir():
print("There are " + str(len([name for name in os.listdir(path) \
if os.path.isfile(os.path.join(path, name))])) + " files in " + \
str(path.name))
count_files(data_dir) # data_dir is the directory you want files counted.
You should get an output similar to this (with the placeholders changed, of course);
There are {number of files} files in {name of sub-folder1}
There are {number of files} files in {name of sub-folder2}
Use minDate as string:
$('#datePickerId').datepicker({minDate: '0'});
This would set today as minimum selectable date .
In my case I deployed via a YAML file like kubectl apply -f deployment.yaml
and the solution appears to be to delete via kubectl delete -f deployment.yaml
In addition to @csgillespie's answer, segments
is also vectorised to help with this sort of thing:
plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)
JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.
this works (i only tested ie & ff):
<html>
<head>
<style type="text/css">
#parent {
height: 300px;
width: 300px;
background-color: #ccc;
border: 1px solid red;
position: relative;
}
#child {
height: 100px;
width: 30px;
background-color: #eee;
border: 1px solid green;
position: absolute;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div id="parent">parent
<div id="child">child</div>
</div>
outside
</body>
</html>
hope that helps.
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.
If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:
BufferedReader reader = request.getReader();
Json post processing example (uses org.json package )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
You can also use info files
to list all the sections of all the binaries loaded in process binary.
This can be done with 3 lines of CSS and is compatible back to (and including) IE9:
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
Example: http://jsfiddle.net/cas07zq8/
I do not recommend keeping bad data in the database and then only correcting it on the output. We have a database where phone numbers are entered in variously as :
Different people in an organization may write various retrieval functions and updates to the database, and therefore it would be harder to set in place formatting and retrieval rules. I am therefore correcting the data in the database first and foremost and then setting in place rules and form validations that protect the integrity of this database going forward.
I see no justification for keeping bad data unless as suggested a duplicate column be added with corrected formatting and the original data kept around for redundancy and reference, and YES I consider badly formatted data as BAD data.
I finally got it:
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix
:
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('');
}]);
Don't forget to set the base in your HTML <head>
:
<head>
<base href="/">
...
</head>
More info about the changelog here.
I also got this error. Though, I did not use boot2docker but just installed "plain" docker on Ubuntu (see https://docs.docker.com/installation/ubuntulinux/).
I got the error ("dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?") because the docker daemon was not running, yet.
On Ubuntu, you need to start the service:
sudo service docker start
See also http://blog.arungupta.me/resolve-dial-unix-docker-sock-error-techtip64
If you're not tagetting IE6, then float the second <div>
and give it a margin equal to (or maybe a little bigger than) the first <div>
's fixed width.
HTML:
<div id="main-wrapper">
<div id="fixed-width"> lorem ipsum </div>
<div id="rest-of-space"> dolor sit amet </div>
</div>
CSS:
#main-wrapper {
100%;
background:red;
}
#fixed-width {
width:100px;
float:left
}
#rest-of-space {
margin-left:101px;
/* May have to increase depending on borders and margin of the fixd width div*/
background:blue;
}
The margin accounts for the possibility that the 'rest-of-space' <div>
may contain more content than the 'fixed-width' <div>
.
Don't give the fixed width one a background; if you need to visibly see these as different 'columns' then use the Faux Columns trick.
I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.
$http({
url:'/login/user',
method : 'POST',
headers: {
'Content-Type': 'application/json'
},
data: userData
}).success(function(loginDetails){
$scope.updLoginDetails = loginDetails;
if($scope.updLoginDetails.successful == true)
{
loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
$window.location='/login/homepage';
}
else
alert('No access available.');
}).error(function(err,status){
alert('No access available.');
});
And it worked for me.
Here is how you can retrieve your user id from a username:
$url = "https://api.instagram.com/v1/users/search?q=[username]&access_token=[your_token]";
$obj = json_decode(@file_get_contents($url));
echo $obj->data[0]->id;
A really good way of detecting mobile or tablet devices is by looking if the browser can create a touch event.
Plain JavaScript Code:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
if (isMobile()) {
# do whatever you wanna do!
}
This worked for me really well, but there may be a problem with laptop devices which include a touchscreen display.
I am not sure if a touchscreen Laptop will get detected as a mobile device because I haven't tested it yet.
Procedure to auto fix AUTO_INCREMENT value of table
DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(64))
BEGIN
DECLARE _max_stmt VARCHAR(1024);
DECLARE _stmt VARCHAR(1024);
SET @inc := 0;
SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(`id`), 0) + 1 INTO @inc FROM ', _table);
PREPARE _max_stmt FROM @MAX_SQL;
EXECUTE _max_stmt;
DEALLOCATE PREPARE _max_stmt;
SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT = ', @inc);
PREPARE _stmt FROM @SQL;
EXECUTE _stmt;
DEALLOCATE PREPARE _stmt;
END//
DELIMITER ;
CALL update_auto_increment('your_table_name')
I find it particularly helpful when doing web development if I want to set a variable to a value sent in the request if it is defined or to some default value if it is not.
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
<a href="javascript:alert('Hello');"></a>
is just shorthand for:
<a href="" onclick="alert('Hello'); return false;"></a>
Try following steps:
ipconfig
(or ifconfig
on Linux) at command prompt. This will give you the IP address of your own machine. For example, your machine's IP address is 192.168.1.6. So your broadcast IP address is 192.168.1.255.ping 192.168.1.255
(may require -b
on Linux)arp -a
. You will get the list of all IP addresses on your segment.If its just a natty little app with one or two ListViews
I normally just create a little helper property:
private ListViewItem SelectedItem { get { return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null); } }
If I have loads, then move it out to a helper class:
internal static class ListViewEx
{
internal static ListViewItem GetSelectedItem(this ListView listView1)
{
return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null);
}
}
so:
ListViewItem item = lstFixtures.GetSelectedItem();
The ListView
interface is a bit rubbish so I normally find the helper class grows quite quickly.
This post has a method to achieve this
from (zvrba) You can do it by redirecting the output to a file first. For example:
echo zz > bla.txt
set /p VV=<bla.txt
echo %VV%
You want to use %p
to print a pointer. From the spec:
p
The argument shall be a pointer tovoid
. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
And don't forget the cast, e.g.
printf("%p\n",(void*)&a);
Short answer No. CSS is not specific to brands.
Below are the articles to implement for iOS using media only.
https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
http://stephen.io/mediaqueries/
Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance
You are trying to use the wrong interface type. The type Function is not appropriate in this case because it receives a parameter and has a return value. Instead you should use Consumer (formerly known as Block)
The Function type is declared as
interface Function<T,R> {
R apply(T t);
}
However, the Consumer type is compatible with that you are looking for:
interface Consumer<T> {
void accept(T t);
}
As such, Consumer is compatible with methods that receive a T and return nothing (void). And this is what you want.
For instance, if I wanted to display all element in a list I could simply create a consumer for that with a lambda expression:
List<String> allJedi = asList("Luke","Obiwan","Quigon");
allJedi.forEach( jedi -> System.out.println(jedi) );
You can see above that in this case, the lambda expression receives a parameter and has no return value.
Now, if I wanted to use a method reference instead of a lambda expression to create a consume of this type, then I need a method that receives a String and returns void, right?.
I could use different types of method references, but in this case let's take advantage of an object method reference by using the println
method in the System.out
object, like this:
Consumer<String> block = System.out::println
Or I could simply do
allJedi.forEach(System.out::println);
The println
method is appropriate because it receives a value and has a return type void, just like the accept
method in Consumer.
So, in your code, you need to change your method signature to somewhat like:
public static void myForEach(List<Integer> list, Consumer<Integer> myBlock) {
list.forEach(myBlock);
}
And then you should be able to create a consumer, using a static method reference, in your case by doing:
myForEach(theList, Test::displayInt);
Ultimately, you could even get rid of your myForEach
method altogether and simply do:
theList.forEach(Test::displayInt);
About Functions as First Class Citizens
All been said, the truth is that Java 8 will not have functions as first-class citizens since a structural function type will not be added to the language. Java will simply offer an alternative way to create implementations of functional interfaces out of lambda expressions and method references. Ultimately lambda expressions and method references will be bound to object references, therefore all we have is objects as first-class citizens. The important thing is the functionality is there since we can pass objects as parameters, bound them to variable references and return them as values from other methods, then they pretty much serve a similar purpose.
ALTER TABLE TABLE_NAME ADD INDEX (COLUMN_NAME);
i would assume fastest and simplest way would be have python call the system commands...
example..
import os
cmd = '<command line call>'
os.system(cmd)
Tar and gzip up the directory.... unzip and untar the directory in the desired place.
yah?
In C#, you can write
(long)(date - new DateTime(1970, 1, 1)).TotalMilliseconds
Prepend the url prefix git+
(See VCS Support):
pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6
And specify the branch name without the leading /
.
I've had a lot of success using thoonk.js along with thoonk.py. Thoonk leverages Redis (in-memory key-value store) to give you feed (think publish/subscribe), queue and job patterns for communication.
Why is this better than unix sockets or direct tcp sockets? Overall performance may be decreased a little, however Thoonk provides a really simple API that simplifies having to manually deal with a socket. Thoonk also helps make it really trivial to implement a distributed computing model that allows you to scale your python workers to increase performance, since you just spin up new instances of your python workers and connect them to the same redis server.
In python
3.6.3 with pandas
0.22.0 you can also use concat
as long as you set as index the columns you want to use for the joining
pd.concat(
(iDF.set_index('name') for iDF in [df1, df2, df3]),
axis=1, join='inner'
).reset_index()
where df1
, df2
, and df3
are defined as in John Galt's answer
import pandas as pd
df1 = pd.DataFrame(np.array([
['a', 5, 9],
['b', 4, 61],
['c', 24, 9]]),
columns=['name', 'attr11', 'attr12']
)
df2 = pd.DataFrame(np.array([
['a', 5, 19],
['b', 14, 16],
['c', 4, 9]]),
columns=['name', 'attr21', 'attr22']
)
df3 = pd.DataFrame(np.array([
['a', 15, 49],
['b', 4, 36],
['c', 14, 9]]),
columns=['name', 'attr31', 'attr32']
)
You need to be aware about how AngularJS works in order to understand it.
First and foremost, AngularJS defines a concept of a so-called digest cycle. This cycle can be considered as a loop, during which AngularJS checks if there are any changes to all the variables watched by all the $scope
s. So if you have $scope.myVar
defined in your controller and this variable was marked for being watched, then you are implicitly telling AngularJS to monitor the changes on myVar
in each iteration of the loop.
A natural follow-up question would be: Is everything attached to $scope
being watched? Fortunately, no. If you would watch for changes to every object in your $scope
, then quickly a digest loop would take ages to evaluate and you would quickly run into performance issues. That is why the AngularJS team gave us two ways of declaring some $scope
variable as being watched (read below).
There are two ways of declaring a $scope
variable as being watched.
<span>{{myVar}}</span>
$watch
serviceAd 1)
This is the most common scenario and I'm sure you've seen it before, but you didn't know that this has created a watch in the background. Yes, it had! Using AngularJS directives (such as ng-repeat
) can also create implicit watches.
Ad 2)
This is how you create your own watches. $watch
service helps you to run some code when some value attached to the $scope
has changed. It is rarely used, but sometimes is helpful. For instance, if you want to run some code each time 'myVar' changes, you could do the following:
function MyController($scope) {
$scope.myVar = 1;
$scope.$watch('myVar', function() {
alert('hey, myVar has changed!');
});
$scope.buttonClicked = function() {
$scope.myVar = 2; // This will trigger $watch expression to kick in
};
}
You can think of the $apply
function as of an integration mechanism. You see, each time you change some watched variable attached to the $scope
object directly, AngularJS will know that the change has happened. This is because AngularJS already knew to monitor those changes. So if it happens in code managed by the framework, the digest cycle will carry on.
However, sometimes you want to change some value outside of the AngularJS world and see the changes propagate normally.
Consider this - you have a $scope.myVar
value which will be modified within a jQuery's $.ajax()
handler. This will happen at some point in future. AngularJS can't wait for this to happen, since it hasn't been instructed to wait on jQuery.
To tackle this, $apply
has been introduced. It lets you start the digestion cycle explicitly. However, you should only use this to migrate some data to AngularJS (integration with other frameworks), but never use this method combined with regular AngularJS code, as AngularJS will throw an error then.
Well, you should really follow the tutorial again, now that you know all this. The digest cycle will make sure that the UI and the JavaScript code stay synchronised, by evaluating every watcher attached to all $scope
s as long as nothing changes. If no more changes happen in the digest loop, then it's considered to be finished.
You can attach objects to the $scope
object either explicitly in the Controller, or by declaring them in {{expression}}
form directly in the view.
I hope that helps to clarify some basic knowledge about all this.
Further readings:
To provide another approach similar to the answer by @IvanCollantes.
It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked
checkbox.
jQuery(function($) {_x000D_
var requiredCheckboxes = $(':checkbox[required]');_x000D_
requiredCheckboxes.on('change', function(e) {_x000D_
var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');_x000D_
var isChecked = checkboxGroup.is(':checked');_x000D_
checkboxGroup.prop('required', !isChecked);_x000D_
});_x000D_
requiredCheckboxes.trigger('change');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form target="_blank">_x000D_
<p>_x000D_
At least one checkbox from each group is required..._x000D_
</p>_x000D_
<fieldset>_x000D_
<legend>Checkboxes Group test</legend>_x000D_
<label>_x000D_
<input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test[]" value="2" required="required">test-2_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test[]" value="3" required="required">test-3_x000D_
</label>_x000D_
</fieldset>_x000D_
<br>_x000D_
<fieldset>_x000D_
<legend>Checkboxes Group test2</legend>_x000D_
<label>_x000D_
<input type="checkbox" name="test2[]" value="1" required="required">test2-1_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test2[]" value="2" required="required">test2-2_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test2[]" value="3" required="required">test2-3_x000D_
</label>_x000D_
</fieldset>_x000D_
<hr>_x000D_
<button type="submit" value="submit">Submit</button>_x000D_
</form>
_x000D_
I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator
ListIterator<Integer> i = a.listIterator();
//changed the value of first element in List
Integer x =null;
if(i.hasNext()) {
x = i.next();
x = Integer.valueOf(9);
}
//set method sets the recent iterated element in ArrayList
i.set(x);
//initialized the iterator again and print all the elements
i = a.listIterator();
while(i.hasNext())
System.out.print(i.next());
But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection
@John Woo's accepted answer has some caveats which you should be aware of:
So, there is an intermediate level between your SQL Server instance and the session which you can use to control the default language setting for session - login level.
SQL Server Instance level setting
-> User login level setting
-> Query Session level setting
This can help you in case you want to set default language of all new sessions belonging to some specific user only.
Simply change the default language setting of the target user login as per this link and you are all set. You can also do it from SQL Server Management Studio (SSMS) UI. Below you can see the default language setting in properties window of sa
user in SQL Server:
Note: Also, it is important to know that changing the setting doesn't affect the default language of already active sessions from that user login. It will affect only the new sessions created after changing the setting.
I would put an absolutely positioned, z-index: 100;
span (or spans) with the background: url("myImageWithRoundedCorners.jpg");
set on it inside the #mainWrapperDivWithBGImage
.
For anyone redirected from "https://stackoverflow.com/questions/4393017/md5-implementation-in-c" because it's been incorrectly labelled a duplicate.
The example located here works:
http://www.zedwood.com/article/cpp-md5-function
If you are compiling in VC++2010 then you will need to change his main.cpp to this:
#include <iostream> //for std::cout
#include <string.h> //for std::string
#include "MD5.h"
using std::cout; using std::endl;
int main(int argc, char *argv[])
{
std::string Temp = md5("The quick brown fox jumps over the lazy dog");
cout << Temp.c_str() << endl;
return 0;
}
You will have to change the MD5 class slightly if you are to read in a char * array instead of a string to answer the question on this page here.
EDIT:
Apparently modifying the MD5 library isn't clear, well a Full VC++2010 solution is here for your convenience to include char *'s:
https://github.com/alm4096/MD5-Hash-Example-VS
A bit of an explanation is here:
#include <iostream> //for std::cout
#include <string.h> //for std::string
#include <fstream>
#include "MD5.h"
using std::cout; using std::endl;
int main(int argc, char *argv[])
{
//Start opening your file
ifstream inBigArrayfile;
inBigArrayfile.open ("Data.dat", std::ios::binary | std::ios::in);
//Find length of file
inBigArrayfile.seekg (0, std::ios::end);
long Length = inBigArrayfile.tellg();
inBigArrayfile.seekg (0, std::ios::beg);
//read in the data from your file
char * InFileData = new char[Length];
inBigArrayfile.read(InFileData,Length);
//Calculate MD5 hash
std::string Temp = md5(InFileData,Length);
cout << Temp.c_str() << endl;
//Clean up
delete [] InFileData;
return 0;
}
I have simply added the following into the MD5 library:
MD5.cpp:
MD5::MD5(char * Input, long length)
{
init();
update(Input, length);
finalize();
}
MD5.h:
std::string md5(char * Input, long length);
C based languages copy C to some degree. The tm
structure (defined in time.h
) has an integer field tm_mon
with the (commented) range of 0-11.
C based languages start arrays at index 0. So this was convenient for outputting a string in an array of month names, with tm_mon
as the index.
Short version of (correct) tzaman answer will be (for fresh SVN)
svn switch ^/branches/v1p2p3
--relocate
switch is deprecated anyway, when it needed you'll have to use svn relocate
command
Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)
On Windows, the caret character (^
) must be escaped:
svn switch ^^/branches/v1p2p3
just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.
let's play a bit ;) :
import cv2
import numpy as np
>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168, 58, 2, 1], # uninitialized memory counts as random, too ? fun ;)
[ 0, 100, 2, 0, 101],
[ 0, 0, 106, 2, 0],
[131, 2, 0, 90, 3],
[ 0, 100, 1, 0, 83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99)) # normal
array([[ 0, 76, 0, 129, 0],
[ 0, 0, 0, 188, 27],
[ 0, 152, 0, 0, 0],
[ 0, 0, 134, 79, 0],
[ 0, 181, 36, 128, 0]], dtype=uint8)
>>> cv2.randu(im,(0),(99)) # uniform
array([[19, 53, 2, 86, 82],
[86, 73, 40, 64, 78],
[34, 20, 62, 80, 7],
[24, 92, 37, 60, 72],
[40, 12, 27, 33, 18]], dtype=uint8)
to apply it to an existing image, just generate noise in the desired range, and add it:
img = ...
noise = ...
image = img + noise
Here is what I use
$textToStore = nl2br(htmlentities($inputText, ENT_QUOTES, 'UTF-8'));
$inputText
is the text provided by either the form or textarea.
$textToStore
is the returned text from nl2br
and htmlentities
, to be stored in your database.
ENT_QUOTES
will convert both double and single quotes, so you'll have no trouble with those.
I... don't think so. You can redirect the subdomain (such as blah.something.com
) to point to something.com:25566
, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.
If you are using numpy
and your array is an np.array
of np.array
elements like:
A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
and you want to access the inner elements (like 10,11,12 13,14.......
) then use:
A[0][0]
instead of A[0,0]
For example:
>>> import numpy as np
>>>A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
>>> A[0][0]
>>> 10
>>> A[0,0]
>>> Throws ERROR
(P.S.: Might be useful when using numpy.array_split()
)
You have several options
integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)
Here's my contribution:
http://jsfiddle.net/g6m5t8co/1/
<!doctype html>
<html>
<head>
<style>
#container {
position:absolute;
background-color: blue;
}
#elem{
position: absolute;
background-color: green;
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
-khtml-user-select: none;
user-select: none;
}
</style>
<script>
var mydragg = function(){
return {
move : function(divid,xpos,ypos){
divid.style.left = xpos + 'px';
divid.style.top = ypos + 'px';
},
startMoving : function(divid,container,evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
divTop = divid.style.top,
divLeft = divid.style.left,
eWi = parseInt(divid.style.width),
eHe = parseInt(divid.style.height),
cWi = parseInt(document.getElementById(container).style.width),
cHe = parseInt(document.getElementById(container).style.height);
document.getElementById(container).style.cursor='move';
divTop = divTop.replace('px','');
divLeft = divLeft.replace('px','');
var diffX = posX - divLeft,
diffY = posY - divTop;
document.onmousemove = function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
aX = posX - diffX,
aY = posY - diffY;
if (aX < 0) aX = 0;
if (aY < 0) aY = 0;
if (aX + eWi > cWi) aX = cWi - eWi;
if (aY + eHe > cHe) aY = cHe -eHe;
mydragg.move(divid,aX,aY);
}
},
stopMoving : function(container){
var a = document.createElement('script');
document.getElementById(container).style.cursor='default';
document.onmousemove = function(){}
},
}
}();
</script>
</head>
<body>
<div id='container' style="width: 600px;height: 400px;top:50px;left:50px;">
<div id="elem" onmousedown='mydragg.startMoving(this,"container",event);' onmouseup='mydragg.stopMoving("container");' style="width: 200px;height: 100px;">
<div style='width:100%;height:100%;padding:10px'>
<select id=test>
<option value=1>first
<option value=2>second
</select>
<INPUT TYPE=text value="123">
</div>
</div>
</div>
</body>
</html>
puts
or p
is a good start to do that.
p "asd" # => "asd"
puts "asd" # => asd
here is more information about that: http://www.ruby-doc.org/core-1.9.3/ARGF.html
I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:
if (!place) return <NotFound />;
hope that helps!
With the differents answers, I implemented this code to use an external file JSON loaded in "app.locals"
Parameters
{
"web": {
"title" : "Le titre de ma Page",
"cssFile" : "20200608_1018.css"
}
}
Application
var express = require('express');
var appli = express();
var serveur = require('http').Server(appli);
var myParams = require('./include/my_params.json');
var myFonctions = require('./include/my_fonctions.js');
appli.locals = myParams;
EJS Page
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title><%= web.title %></title>
<link rel="stylesheet" type="text/css" href="/css/<%= web.cssFile %>">
</head>
</body>
</html>
Hoping it will help
You can try also this (it works on PHP 5.* and 7):
$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip
Tip: it returns an empty string if the file doesn't have an extension
What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?
From Google's "I'm Feeling Lucky" on vmalloc
:
kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.
No need to apologize for asking a question! Try using the RIGHT
function. It returns the last n characters of a string.
=RIGHT(A1, 1)
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
There are CSS options for the audio tag.
Like: html 5 audio tag width
But if you play around with it you'll see results can be unexpected - as of August 2012.
Be sure you're running the right instance of Python with the right directories on the path. In my case, this error resulted from running the python
executable by accident - I had actually installed Django under the python2.7
framework & libraries. The same could happen as a result of virtualenv as well.
Try this:
xcopy %1 %2 /y /e
The %1
and %2
are the source and destination arguments you pass to the batch file. i.e. C:\MyBatchFile.bat C:\CopyMe D:\ToHere
The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.
In case you don't know how to find them: Open the Error List
(View
> Error List
) and click on Warning
.
Works fine in Xcode 8.1.2 with Swift 3
.cornerRadius
is the key property to set rounded edges. If you are using the same style for all labels in your application, I would recommend for an extension method.
Code:
// extension Class
extension UILabel {
// extension user defined Method
func setRoundEdge() {
let myGreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
//Width of border
self.layer.borderWidth = 1.0
//How much the edge to be rounded
self.layer.cornerRadius = 5.0
// following properties are optional
//color for border
self.layer.borderColor = myGreenColor.cgColor
//color for text
self.textColor = UIColor.red
// Mask the bound
self.layer.masksToBounds = true
//clip the pixel contents
self.clipsToBounds = true
}
}
Output:
Why Extension method?
Create a Swift file and add the following code, which has the Extention method to the "UILabel" class, where this method is user defined but will work for all the label in your application and will help to maintain consistency and clean code, if you change any style in future require only in the extension method.
Given that the Apache Subversion server will be moved to this new DNS alias: sub.someaddress.com.tr
:
With Subversion 1.7 or higher, use svn relocate
. Relocate is used when the SVN server's location changes. switch
is only used if you want to change your local working copy to another branch or another path. If using TortoiseSVN, you may follow instructions from the TortoiseSVN Manual. If using the SVN command line interface, refer to this section of SVN's documentation. The command should look like this:
svn relocate svn://sub.someaddress.com.tr/project
Keep using /project
given that the actual contents of your repository probably won't change.
Note: svn relocate
is not available before version 1.7 (thanks to ColinM for the info). In older versions you would use:
svn switch --relocate OLD NEW
As of ECMAScript 2016 you can use includes()
arr.includes(obj);
If you want to support IE or other older browsers:
function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}
EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:
Mozilla's (ECMA-262) version:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
Daniel James's version:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
roosteronacid's version:
Array.prototype.hasObject = (
!Array.indexOf ? function (o)
{
var l = this.length + 1;
while (l -= 1)
{
if (this[l - 1] === o)
{
return true;
}
}
return false;
} : function (o)
{
return (this.indexOf(o) !== -1);
}
);
Take for example a framework or a library you're designing for other users, these users eventually will have a main function
in their code in order to execute their app. If the user directly imports a sub-package of your library's project then the init
of that sub-package will be called(once) first of all. The same for the root package of the library, etc...
There are many times when you may want a code block to be executed without the existence of a main func
, directly or not.
If you, as the developer of the imaginary library, import your library's sub-package that has an init
function, it will be called first and once, you don't have a main func
but you need to make sure that some variables, or a table, will be initialized before the calls of other functions.
A good thing to remember and not to worry about, is that:
the init
always execute once per application.
init
execution happens:
init
function of the "caller" package,main func
,var = [...] or cost = [...]
, When you import a package it will run all of its init functions, by order.
I'll will give a very good example of an init function. It will add mime types to a standard go's library named mime
and a package-level function will use the mime
standard package directly to get the custom mime types that are already be initialized at its init
function:
package mime
import (
"mime"
"path/filepath"
)
var types = map[string]string{
".3dm": "x-world/x-3dmf",
".3dmf": "x-world/x-3dmf",
".7z": "application/x-7z-compressed",
".a": "application/octet-stream",
".aab": "application/x-authorware-bin",
".aam": "application/x-authorware-map",
".aas": "application/x-authorware-seg",
".abc": "text/vndabc",
".ace": "application/x-ace-compressed",
".acgi": "text/html",
".afl": "video/animaflex",
".ai": "application/postscript",
".aif": "audio/aiff",
".aifc": "audio/aiff",
".aiff": "audio/aiff",
".aim": "application/x-aim",
".aip": "text/x-audiosoft-intra",
".alz": "application/x-alz-compressed",
".ani": "application/x-navi-animation",
".aos": "application/x-nokia-9000-communicator-add-on-software",
".aps": "application/mime",
".apk": "application/vnd.android.package-archive",
".arc": "application/x-arc-compressed",
".arj": "application/arj",
".art": "image/x-jg",
".asf": "video/x-ms-asf",
".asm": "text/x-asm",
".asp": "text/asp",
".asx": "application/x-mplayer2",
".au": "audio/basic",
".avi": "video/x-msvideo",
".avs": "video/avs-video",
".bcpio": "application/x-bcpio",
".bin": "application/mac-binary",
".bmp": "image/bmp",
".boo": "application/book",
".book": "application/book",
".boz": "application/x-bzip2",
".bsh": "application/x-bsh",
".bz2": "application/x-bzip2",
".bz": "application/x-bzip",
".c++": "text/plain",
".c": "text/x-c",
".cab": "application/vnd.ms-cab-compressed",
".cat": "application/vndms-pkiseccat",
".cc": "text/x-c",
".ccad": "application/clariscad",
".cco": "application/x-cocoa",
".cdf": "application/cdf",
".cer": "application/pkix-cert",
".cha": "application/x-chat",
".chat": "application/x-chat",
".chrt": "application/vnd.kde.kchart",
".class": "application/java",
".com": "text/plain",
".conf": "text/plain",
".cpio": "application/x-cpio",
".cpp": "text/x-c",
".cpt": "application/mac-compactpro",
".crl": "application/pkcs-crl",
".crt": "application/pkix-cert",
".crx": "application/x-chrome-extension",
".csh": "text/x-scriptcsh",
".css": "text/css",
".csv": "text/csv",
".cxx": "text/plain",
".dar": "application/x-dar",
".dcr": "application/x-director",
".deb": "application/x-debian-package",
".deepv": "application/x-deepv",
".def": "text/plain",
".der": "application/x-x509-ca-cert",
".dif": "video/x-dv",
".dir": "application/x-director",
".divx": "video/divx",
".dl": "video/dl",
".dmg": "application/x-apple-diskimage",
".doc": "application/msword",
".dot": "application/msword",
".dp": "application/commonground",
".drw": "application/drafting",
".dump": "application/octet-stream",
".dv": "video/x-dv",
".dvi": "application/x-dvi",
".dwf": "drawing/x-dwf=(old)",
".dwg": "application/acad",
".dxf": "application/dxf",
".dxr": "application/x-director",
".el": "text/x-scriptelisp",
".elc": "application/x-bytecodeelisp=(compiled=elisp)",
".eml": "message/rfc822",
".env": "application/x-envoy",
".eps": "application/postscript",
".es": "application/x-esrehber",
".etx": "text/x-setext",
".evy": "application/envoy",
".exe": "application/octet-stream",
".f77": "text/x-fortran",
".f90": "text/x-fortran",
".f": "text/x-fortran",
".fdf": "application/vndfdf",
".fif": "application/fractals",
".fli": "video/fli",
".flo": "image/florian",
".flv": "video/x-flv",
".flx": "text/vndfmiflexstor",
".fmf": "video/x-atomic3d-feature",
".for": "text/x-fortran",
".fpx": "image/vndfpx",
".frl": "application/freeloader",
".funk": "audio/make",
".g3": "image/g3fax",
".g": "text/plain",
".gif": "image/gif",
".gl": "video/gl",
".gsd": "audio/x-gsm",
".gsm": "audio/x-gsm",
".gsp": "application/x-gsp",
".gss": "application/x-gss",
".gtar": "application/x-gtar",
".gz": "application/x-compressed",
".gzip": "application/x-gzip",
".h": "text/x-h",
".hdf": "application/x-hdf",
".help": "application/x-helpfile",
".hgl": "application/vndhp-hpgl",
".hh": "text/x-h",
".hlb": "text/x-script",
".hlp": "application/hlp",
".hpg": "application/vndhp-hpgl",
".hpgl": "application/vndhp-hpgl",
".hqx": "application/binhex",
".hta": "application/hta",
".htc": "text/x-component",
".htm": "text/html",
".html": "text/html",
".htmls": "text/html",
".htt": "text/webviewhtml",
".htx": "text/html",
".ice": "x-conference/x-cooltalk",
".ico": "image/x-icon",
".ics": "text/calendar",
".icz": "text/calendar",
".idc": "text/plain",
".ief": "image/ief",
".iefs": "image/ief",
".iges": "application/iges",
".igs": "application/iges",
".ima": "application/x-ima",
".imap": "application/x-httpd-imap",
".inf": "application/inf",
".ins": "application/x-internett-signup",
".ip": "application/x-ip2",
".isu": "video/x-isvideo",
".it": "audio/it",
".iv": "application/x-inventor",
".ivr": "i-world/i-vrml",
".ivy": "application/x-livescreen",
".jam": "audio/x-jam",
".jav": "text/x-java-source",
".java": "text/x-java-source",
".jcm": "application/x-java-commerce",
".jfif-tbnl": "image/jpeg",
".jfif": "image/jpeg",
".jnlp": "application/x-java-jnlp-file",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".jps": "image/x-jps",
".js": "application/javascript",
".json": "application/json",
".jut": "image/jutvision",
".kar": "audio/midi",
".karbon": "application/vnd.kde.karbon",
".kfo": "application/vnd.kde.kformula",
".flw": "application/vnd.kde.kivio",
".kml": "application/vnd.google-earth.kml+xml",
".kmz": "application/vnd.google-earth.kmz",
".kon": "application/vnd.kde.kontour",
".kpr": "application/vnd.kde.kpresenter",
".kpt": "application/vnd.kde.kpresenter",
".ksp": "application/vnd.kde.kspread",
".kwd": "application/vnd.kde.kword",
".kwt": "application/vnd.kde.kword",
".ksh": "text/x-scriptksh",
".la": "audio/nspaudio",
".lam": "audio/x-liveaudio",
".latex": "application/x-latex",
".lha": "application/lha",
".lhx": "application/octet-stream",
".list": "text/plain",
".lma": "audio/nspaudio",
".log": "text/plain",
".lsp": "text/x-scriptlisp",
".lst": "text/plain",
".lsx": "text/x-la-asf",
".ltx": "application/x-latex",
".lzh": "application/octet-stream",
".lzx": "application/lzx",
".m1v": "video/mpeg",
".m2a": "audio/mpeg",
".m2v": "video/mpeg",
".m3u": "audio/x-mpegurl",
".m": "text/x-m",
".man": "application/x-troff-man",
".manifest": "text/cache-manifest",
".map": "application/x-navimap",
".mar": "text/plain",
".mbd": "application/mbedlet",
".mc$": "application/x-magic-cap-package-10",
".mcd": "application/mcad",
".mcf": "text/mcf",
".mcp": "application/netmc",
".me": "application/x-troff-me",
".mht": "message/rfc822",
".mhtml": "message/rfc822",
".mid": "application/x-midi",
".midi": "application/x-midi",
".mif": "application/x-frame",
".mime": "message/rfc822",
".mjf": "audio/x-vndaudioexplosionmjuicemediafile",
".mjpg": "video/x-motion-jpeg",
".mm": "application/base64",
".mme": "application/base64",
".mod": "audio/mod",
".moov": "video/quicktime",
".mov": "video/quicktime",
".movie": "video/x-sgi-movie",
".mp2": "audio/mpeg",
".mp3": "audio/mpeg3",
".mp4": "video/mp4",
".mpa": "audio/mpeg",
".mpc": "application/x-project",
".mpe": "video/mpeg",
".mpeg": "video/mpeg",
".mpg": "video/mpeg",
".mpga": "audio/mpeg",
".mpp": "application/vndms-project",
".mpt": "application/x-project",
".mpv": "application/x-project",
".mpx": "application/x-project",
".mrc": "application/marc",
".ms": "application/x-troff-ms",
".mv": "video/x-sgi-movie",
".my": "audio/make",
".mzz": "application/x-vndaudioexplosionmzz",
".nap": "image/naplps",
".naplps": "image/naplps",
".nc": "application/x-netcdf",
".ncm": "application/vndnokiaconfiguration-message",
".nif": "image/x-niff",
".niff": "image/x-niff",
".nix": "application/x-mix-transfer",
".nsc": "application/x-conference",
".nvd": "application/x-navidoc",
".o": "application/octet-stream",
".oda": "application/oda",
".odb": "application/vnd.oasis.opendocument.database",
".odc": "application/vnd.oasis.opendocument.chart",
".odf": "application/vnd.oasis.opendocument.formula",
".odg": "application/vnd.oasis.opendocument.graphics",
".odi": "application/vnd.oasis.opendocument.image",
".odm": "application/vnd.oasis.opendocument.text-master",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/vnd.oasis.opendocument.spreadsheet",
".odt": "application/vnd.oasis.opendocument.text",
".oga": "audio/ogg",
".ogg": "audio/ogg",
".ogv": "video/ogg",
".omc": "application/x-omc",
".omcd": "application/x-omcdatamaker",
".omcr": "application/x-omcregerator",
".otc": "application/vnd.oasis.opendocument.chart-template",
".otf": "application/vnd.oasis.opendocument.formula-template",
".otg": "application/vnd.oasis.opendocument.graphics-template",
".oth": "application/vnd.oasis.opendocument.text-web",
".oti": "application/vnd.oasis.opendocument.image-template",
".otm": "application/vnd.oasis.opendocument.text-master",
".otp": "application/vnd.oasis.opendocument.presentation-template",
".ots": "application/vnd.oasis.opendocument.spreadsheet-template",
".ott": "application/vnd.oasis.opendocument.text-template",
".p10": "application/pkcs10",
".p12": "application/pkcs-12",
".p7a": "application/x-pkcs7-signature",
".p7c": "application/pkcs7-mime",
".p7m": "application/pkcs7-mime",
".p7r": "application/x-pkcs7-certreqresp",
".p7s": "application/pkcs7-signature",
".p": "text/x-pascal",
".part": "application/pro_eng",
".pas": "text/pascal",
".pbm": "image/x-portable-bitmap",
".pcl": "application/vndhp-pcl",
".pct": "image/x-pict",
".pcx": "image/x-pcx",
".pdb": "chemical/x-pdb",
".pdf": "application/pdf",
".pfunk": "audio/make",
".pgm": "image/x-portable-graymap",
".pic": "image/pict",
".pict": "image/pict",
".pkg": "application/x-newton-compatible-pkg",
".pko": "application/vndms-pkipko",
".pl": "text/x-scriptperl",
".plx": "application/x-pixclscript",
".pm4": "application/x-pagemaker",
".pm5": "application/x-pagemaker",
".pm": "text/x-scriptperl-module",
".png": "image/png",
".pnm": "application/x-portable-anymap",
".pot": "application/mspowerpoint",
".pov": "model/x-pov",
".ppa": "application/vndms-powerpoint",
".ppm": "image/x-portable-pixmap",
".pps": "application/mspowerpoint",
".ppt": "application/mspowerpoint",
".ppz": "application/mspowerpoint",
".pre": "application/x-freelance",
".prt": "application/pro_eng",
".ps": "application/postscript",
".psd": "application/octet-stream",
".pvu": "paleovu/x-pv",
".pwz": "application/vndms-powerpoint",
".py": "text/x-scriptphyton",
".pyc": "application/x-bytecodepython",
".qcp": "audio/vndqcelp",
".qd3": "x-world/x-3dmf",
".qd3d": "x-world/x-3dmf",
".qif": "image/x-quicktime",
".qt": "video/quicktime",
".qtc": "video/x-qtc",
".qti": "image/x-quicktime",
".qtif": "image/x-quicktime",
".ra": "audio/x-pn-realaudio",
".ram": "audio/x-pn-realaudio",
".rar": "application/x-rar-compressed",
".ras": "application/x-cmu-raster",
".rast": "image/cmu-raster",
".rexx": "text/x-scriptrexx",
".rf": "image/vndrn-realflash",
".rgb": "image/x-rgb",
".rm": "application/vndrn-realmedia",
".rmi": "audio/mid",
".rmm": "audio/x-pn-realaudio",
".rmp": "audio/x-pn-realaudio",
".rng": "application/ringing-tones",
".rnx": "application/vndrn-realplayer",
".roff": "application/x-troff",
".rp": "image/vndrn-realpix",
".rpm": "audio/x-pn-realaudio-plugin",
".rt": "text/vndrn-realtext",
".rtf": "text/richtext",
".rtx": "text/richtext",
".rv": "video/vndrn-realvideo",
".s": "text/x-asm",
".s3m": "audio/s3m",
".s7z": "application/x-7z-compressed",
".saveme": "application/octet-stream",
".sbk": "application/x-tbook",
".scm": "text/x-scriptscheme",
".sdml": "text/plain",
".sdp": "application/sdp",
".sdr": "application/sounder",
".sea": "application/sea",
".set": "application/set",
".sgm": "text/x-sgml",
".sgml": "text/x-sgml",
".sh": "text/x-scriptsh",
".shar": "application/x-bsh",
".shtml": "text/x-server-parsed-html",
".sid": "audio/x-psid",
".skd": "application/x-koan",
".skm": "application/x-koan",
".skp": "application/x-koan",
".skt": "application/x-koan",
".sit": "application/x-stuffit",
".sitx": "application/x-stuffitx",
".sl": "application/x-seelogo",
".smi": "application/smil",
".smil": "application/smil",
".snd": "audio/basic",
".sol": "application/solids",
".spc": "text/x-speech",
".spl": "application/futuresplash",
".spr": "application/x-sprite",
".sprite": "application/x-sprite",
".spx": "audio/ogg",
".src": "application/x-wais-source",
".ssi": "text/x-server-parsed-html",
".ssm": "application/streamingmedia",
".sst": "application/vndms-pkicertstore",
".step": "application/step",
".stl": "application/sla",
".stp": "application/step",
".sv4cpio": "application/x-sv4cpio",
".sv4crc": "application/x-sv4crc",
".svf": "image/vnddwg",
".svg": "image/svg+xml",
".svr": "application/x-world",
".swf": "application/x-shockwave-flash",
".t": "application/x-troff",
".talk": "text/x-speech",
".tar": "application/x-tar",
".tbk": "application/toolbook",
".tcl": "text/x-scripttcl",
".tcsh": "text/x-scripttcsh",
".tex": "application/x-tex",
".texi": "application/x-texinfo",
".texinfo": "application/x-texinfo",
".text": "text/plain",
".tgz": "application/gnutar",
".tif": "image/tiff",
".tiff": "image/tiff",
".tr": "application/x-troff",
".tsi": "audio/tsp-audio",
".tsp": "application/dsptype",
".tsv": "text/tab-separated-values",
".turbot": "image/florian",
".txt": "text/plain",
".uil": "text/x-uil",
".uni": "text/uri-list",
".unis": "text/uri-list",
".unv": "application/i-deas",
".uri": "text/uri-list",
".uris": "text/uri-list",
".ustar": "application/x-ustar",
".uu": "text/x-uuencode",
".uue": "text/x-uuencode",
".vcd": "application/x-cdlink",
".vcf": "text/x-vcard",
".vcard": "text/x-vcard",
".vcs": "text/x-vcalendar",
".vda": "application/vda",
".vdo": "video/vdo",
".vew": "application/groupwise",
".viv": "video/vivo",
".vivo": "video/vivo",
".vmd": "application/vocaltec-media-desc",
".vmf": "application/vocaltec-media-file",
".voc": "audio/voc",
".vos": "video/vosaic",
".vox": "audio/voxware",
".vqe": "audio/x-twinvq-plugin",
".vqf": "audio/x-twinvq",
".vql": "audio/x-twinvq-plugin",
".vrml": "application/x-vrml",
".vrt": "x-world/x-vrt",
".vsd": "application/x-visio",
".vst": "application/x-visio",
".vsw": "application/x-visio",
".w60": "application/wordperfect60",
".w61": "application/wordperfect61",
".w6w": "application/msword",
".wav": "audio/wav",
".wb1": "application/x-qpro",
".wbmp": "image/vnd.wap.wbmp",
".web": "application/vndxara",
".wiz": "application/msword",
".wk1": "application/x-123",
".wmf": "windows/metafile",
".wml": "text/vnd.wap.wml",
".wmlc": "application/vnd.wap.wmlc",
".wmls": "text/vnd.wap.wmlscript",
".wmlsc": "application/vnd.wap.wmlscriptc",
".word": "application/msword",
".wp5": "application/wordperfect",
".wp6": "application/wordperfect",
".wp": "application/wordperfect",
".wpd": "application/wordperfect",
".wq1": "application/x-lotus",
".wri": "application/mswrite",
".wrl": "application/x-world",
".wrz": "model/vrml",
".wsc": "text/scriplet",
".wsrc": "application/x-wais-source",
".wtk": "application/x-wintalk",
".x-png": "image/png",
".xbm": "image/x-xbitmap",
".xdr": "video/x-amt-demorun",
".xgz": "xgl/drawing",
".xif": "image/vndxiff",
".xl": "application/excel",
".xla": "application/excel",
".xlb": "application/excel",
".xlc": "application/excel",
".xld": "application/excel",
".xlk": "application/excel",
".xll": "application/excel",
".xlm": "application/excel",
".xls": "application/excel",
".xlt": "application/excel",
".xlv": "application/excel",
".xlw": "application/excel",
".xm": "audio/xm",
".xml": "text/xml",
".xmz": "xgl/movie",
".xpix": "application/x-vndls-xpix",
".xpm": "image/x-xpixmap",
".xsr": "video/x-amt-showrun",
".xwd": "image/x-xwd",
".xyz": "chemical/x-pdb",
".z": "application/x-compress",
".zip": "application/zip",
".zoo": "application/octet-stream",
".zsh": "text/x-scriptzsh",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".docm": "application/vnd.ms-word.document.macroEnabled.12",
".dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
".dotm": "application/vnd.ms-word.template.macroEnabled.12",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
".xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
".xltm": "application/vnd.ms-excel.template.macroEnabled.12",
".xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
".xlam": "application/vnd.ms-excel.addin.macroEnabled.12",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
".ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
".ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
".potx": "application/vnd.openxmlformats-officedocument.presentationml.template",
".potm": "application/vnd.ms-powerpoint.template.macroEnabled.12",
".ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12",
".sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide",
".sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12",
".thmx": "application/vnd.ms-officetheme",
".onetoc": "application/onenote",
".onetoc2": "application/onenote",
".onetmp": "application/onenote",
".onepkg": "application/onenote",
".xpi": "application/x-xpinstall",
}
func init() {
for ext, typ := range types {
// skip errors
mime.AddExtensionType(ext, typ)
}
}
// typeByExtension returns the MIME type associated with the file extension ext.
// The extension ext should begin with a leading dot, as in ".html".
// When ext has no associated type, typeByExtension returns "".
//
// Extensions are looked up first case-sensitively, then case-insensitively.
//
// The built-in table is small but on unix it is augmented by the local
// system's mime.types file(s) if available under one or more of these
// names:
//
// /etc/mime.types
// /etc/apache2/mime.types
// /etc/apache/mime.types
//
// On Windows, MIME types are extracted from the registry.
//
// Text types have the charset parameter set to "utf-8" by default.
func TypeByExtension(fullfilename string) string {
ext := filepath.Ext(fullfilename)
typ := mime.TypeByExtension(ext)
// mime.TypeByExtension returns as text/plain; | charset=utf-8 the static .js (not always)
if ext == ".js" && (typ == "text/plain" || typ == "text/plain; charset=utf-8") {
if ext == ".js" {
typ = "application/javascript"
}
}
return typ
}
Hope that helped you and other users, don't hesitate to post again if you have more questions!
It depends on how many times you want to sample the distribution.
Suppose you want to sample the distribution K times. Then, the time complexity using np.random.choice()
each time is O(K(n + log(n)))
when n
is the number of items in the distribution.
In my case, I needed to sample the same distribution multiple times of the order of 10^3 where n is of the order of 10^6. I used the below code, which precomputes the cumulative distribution and samples it in O(log(n))
. Overall time complexity is O(n+K*log(n))
.
import numpy as np
n,k = 10**6,10**3
# Create dummy distribution
a = np.array([i+1 for i in range(n)])
p = np.array([1.0/n]*n)
cfd = p.cumsum()
for _ in range(k):
x = np.random.uniform()
idx = cfd.searchsorted(x, side='right')
sampled_element = a[idx]
Do right thing, do thing right!
--->Zero Open your terminal,
--Firstly input python -V
, It likely shows:
Python 2.7.10
-Secondly input python3 -V
, It likely shows:
Python 3.7.2
--Thirdly input where python
or which python
, It likely shows:
/usr/bin/python
---Fourthly input where python3
or which python3
, It likely shows:
/usr/local/bin/python3
--Fifthly add the following line at the bottom of your PATH environment variable file in ~/.profile file or ~/.bash_profile
under Bash or ~/.zshrc
under zsh.
alias python='/usr/local/bin/python3'
OR
alias python=python3
-Sixthly input source ~/.bash_profile
under Bash or source ~/.zshrc
under zsh.
--Seventhly Quit the terminal.
---Eighthly Open your terminal, and input python -V
, It likely shows:
Python 3.7.2
I had done successfully try it.
Others, the ~/.bash_profile
under zsh is not that ~/.bash_profile
.
The PATH environment variable under zsh instead ~/.profile
(or ~/.bash_file
) via ~/.zshrc
.
Help you guys!
$(function(){
var _top = $(window).scrollTop();
var _direction;
$(window).scroll(function(){
var _cur_top = $(window).scrollTop();
if(_top < _cur_top)
{
_direction = 'down';
}
else
{
_direction = 'up';
}
_top = _cur_top;
console.log(_direction);
});
});
It may be something like this in HTML:
<div class="container-outer">
<div class="container-inner">
<!-- Your images over here -->
</div>
</div>
With this stylesheet:
.container-outer { overflow: scroll; width: 500px; height: 210px; }
.container-inner { width: 10000px; }
You can even create an intelligent script to calculate the inner container width, like this one:
$(document).ready(function() {
var container_width = SINGLE_IMAGE_WIDTH * $(".container-inner a").length;
$(".container-inner").css("width", container_width);
});
Direct answer: No
But you can simulate reference with wrappers.
And do the following:
void changeString( _<String> str ) {
str.s("def");
}
void testRef() {
_<String> abc = new _<String>("abc");
changeString( abc );
out.println( abc ); // prints def
}
Out
void setString( _<String> ref ) {
str.s( "def" );
}
void testOut(){
_<String> abc = _<String>();
setString( abc );
out.println(abc); // prints def
}
And basically any other type such as:
_<Integer> one = new <Integer>(1);
addOneTo( one );
out.println( one ); // May print 2
datetime.datetime.now() - datetime.timedelta(0, 15 * 60)
timedelta
is a "change in time". It takes days as the first parameter and seconds in the second parameter. 15 * 60
seconds is 15 minutes.
Using the .val()
function on a multi-select list will return an array of the selected values:
var selectedValues = $('#multipleSelect').val();
and in your html:
<select id="multipleSelect" multiple="multiple">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
As the chosen answer is pretty old, and things changed, here is the new procedure, if you use 64 bits Notepad++. 64 bits version does not come with Plugin Manager nor NppExport. All details provided here.
To resume quickly, Plugin Manager is no longer develloped and NppExport can be found just here.
You could create a helper function:
def re_match_group(pattern, str, out_groups):
del out_groups[:]
result = re.match(pattern, str)
if result:
out_groups[:len(result.groups())] = result.groups()
return result
And then use it like this:
groups = []
if re_match_group("I love (\w+)", statement, groups):
print "He loves", groups[0]
elif re_match_group("Ich liebe (\w+)", statement, groups):
print "Er liebt", groups[0]
elif re_match_group("Je t'aime (\w+)", statement, groups):
print "Il aime", groups[0]
It's a little clunky, but it gets the job done.
If the image is smaller than parent...
.img_100 {
width: 100%;
}
// this class will authenticate LDAP UserName or Email
// simply call LdapAuth.authenticateUserAndGetInfo (username,password);
//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex
import java.util.*;
import javax.naming.*;
import java.util.regex.*;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapAuth {
private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";
private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
private static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};
// see you active directory user OU's hirarchy
private static String[] ADSearchPaths =
{
"OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Migrated Users,OU=TES-Users"
};
private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided
private static void authenticateUserAndGetInfo (String user, String password) throws Exception {
try {
Hashtable<String,String> env = new Hashtable <String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, ldapURI);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, password);
DirContext ctx = new InitialDirContext(env);
String filter = "(sAMAccountName="+user+")"; // default for search filter username
if(user.contains("@")) // if user name is a email then
{
//String parts[] = user.split("\\@");
//use different filter for email
filter = "(userPrincipalName="+user+")";
}
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctrl.setReturningAttributes(requiredAttributes);
NamingEnumeration userInfo = null;
Integer i = 0;
do
{
userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
i++;
} while(!userInfo.hasMore() && i < ADSearchPaths.length );
if (userInfo.hasMore()) {
SearchResult UserDetails = (SearchResult) userInfo.next();
Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());
System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());
System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());
System.out.println("name = "+userAttr.get("cn").get(0).toString());
System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());
}
userInfo.close();
}
catch (javax.naming.AuthenticationException e) {
}
}
}
To create a clickable reference to a channel in a Slack conversation, just type #
followed by the channel name. For example: #general
.
To share the channel URL externally, you can grab its link by control-clicking (Mac) or right-clicking (Windows) on the channel name:
The link would look like this:
https://yourteam.slack.com/messages/C69S1L3SS
Note that this link doesn't change even if you change the name of the channel. So, it is better to use this link rather than the one based on channel's name.
https://yourteam.slack.com/channels/<channel_name>
Opening the above URL from a browser would launch the Slack client (if available) or open the slack channel on the browser itself.
https://yourteam.slack.com/channels/<username>
Official(?) instructions: http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages
If you have replaced a package with another version, then you can just delete the package(s) you don't need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).
If you want to delete the currently installed version of a package (or all versions of a package), you should first run:
easy_install -mxN PackageName
This will ensure that Python doesn't continue to search for a package you're planning to remove. After you've done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.
You can find the instructions here. Basically you just add
[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128
http-proxy-compression = no
to your ~/.subversion/servers
file.
In case anyone has the same problem in the future:
$ adb shell
$ su
# mount -o rw,remount /system
Both adb remount
and adb root
don't work on a production build without altering ro.secure, but you can still remount /system by opening a shell, asking for root permissions and typing the mount command.
None
is just a value that commonly is used to signify 'empty', or 'no value here'. It is a signal object; it only has meaning because the Python documentation says it has that meaning.
There is only one copy of that object in a given Python interpreter session.
If you write a function, and that function doesn't use an explicit return
statement, None
is returned instead, for example. That way, programming with functions is much simplified; a function always returns something, even if it is only that one None
object.
You can test for it explicitly:
if foo is None:
# foo is set to None
if bar is not None:
# bar is set to something *other* than None
Another use is to give optional parameters to functions an 'empty' default:
def spam(foo=None):
if foo is not None:
# foo was specified, do something clever!
The function spam()
has a optional argument; if you call spam()
without specifying it, the default value None
is given to it, making it easy to detect if the function was called with an argument or not.
Other languages have similar concepts. SQL has NULL
; JavaScript has undefined
and null
, etc.
Note that in Python, variables exist by virtue of being used. You don't need to declare a variable first, so there are no really empty variables in Python. Setting a variable to None
is then not the same thing as setting it to a default empty value; None
is a value too, albeit one that is often used to signal emptyness. The book you are reading is misleading on that point.
To show child or sibling elements it's possible with CSS only. If you use :hover
before combinators (+
, ~
, >
, space
). Then the style applies not to hovered element.
HTML
<body>
<div class="trigger">
Hover here.
</div>
<div class="hidden">
This message shows up.
</div>
</body>
CSS
.hidden { display: none; }
.trigger:hover + .hidden { display: inline; }
Writing record arrays as CSV files with headers requires a bit more work.
This example reads from a CSV file ('example.csv'
) and writes its contents to another CSV file (out.csv
).
import numpy as np
# Write an example CSV file with headers on first line
with open('example.csv', 'w') as fp:
fp.write('''\
col1,col2,col3
1,100.1,string1
2,222.2,second string
''')
# Read it as a Numpy record array
ar = np.recfromcsv('example.csv')
print(repr(ar))
# rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')],
# dtype=[('col1', '<i4'), ('col2', '<f8'), ('col3', 'S13')])
# Write as a CSV file with headers on first line
with open('out.csv', 'w') as fp:
fp.write(','.join(ar.dtype.names) + '\n')
np.savetxt(fp, ar, '%s', ',')
Note that the above example cannot handle values which are strings with commas. To always enclose non-numeric values within quotes, use the csv
package:
import csv
with open('out2.csv', 'wb') as fp:
writer = csv.writer(fp, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(ar.dtype.names)
writer.writerows(ar.tolist())
Use this both installation and then go ahead with your python code
pip install google-cloud
pip install google-cloud-vision
Last I looked -- a couple of years ago -- there wasn't an easy option and the "solution" (which I did not agree with) was screen-scraping a number of websites. It may be easier now but I would still be surprised to see something, well, useful.
The problem here is that the data is immensely valuable (and very expensive), so while defining a method of retrieving it would be easy, getting the trading venues to part with their data would be next to impossible. Some of the MTFs (currently) provide their data for free but I'm not sure how you would get it without paying someone else, like Reuters, for it.
Suppose there are multiple static synchronized methods (m1, m2, m3, m4) in a class, and suppose one thread is accessing m1, then no other thread at the same time can access any other static synchronized methods.
Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)
Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:
#import "someFile.h"
Or in the case of frameworks:
#import <SomeLibrary/SomeFile.h>
Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include
statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h
and SomeFileB.h
; SomeFileA.h
includes SomeFileB.h
, and SomeFileB.h
includes SomeFileA.h
. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.
When using #import
, you don’t need to worry about this issue or write header guards to avoid it. However, #import
is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)
Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import
.
Returning to the previous example of importing a framework:
#import <SomeLibrary/SomeFile.h>
To import this library as a module, the code would be changed to:
@import SomeLibrary;
This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:
@import AwesomeLibrary.AwesomeObject;
For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import
and @import
statements in your code together without any concern.
You can indeed run multiple animations simultaneously, but your example has two problems. First, the syntax you use only specifies one animation. The second style rule hides the first. You can specify two animations using syntax like this:
-webkit-animation-name: spin, scale
-webkit-animation-duration: 2s, 4s
as in this fiddle (where I replaced "scale" with "fade" due to the other problem explained below... Bear with me.): http://jsfiddle.net/rwaldin/fwk5bqt6/
Second, both of your animations alter the same CSS property (transform) of the same DOM element. I don't believe you can do that. You can specify two animations on different elements, the image and a container element perhaps. Just apply one of the animations to the container, as in this fiddle: http://jsfiddle.net/rwaldin/fwk5bqt6/2/
The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.
Using MySQL as an example (if for no other reason because it's most popular), you have DATE
, DATETIME
, TIME
and TIMESTAMP
column data types; just as you have CHAR
, VARCHAR
, FLOAT
and INTEGER
.
So, you ask, what's the difference? Well, some of them are self-explanatory. DATE
only stores a date, TIME
only stores a time of day, while DATETIME
stores both.
The difference between DATETIME
and TIMESTAMP
is a bit more subtle: DATETIME
is formatted as YYYY-MM-DD HH:MM:SS
. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP
looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME
stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP
only stores the number of seconds since 1970-01-01, it uses 4 bytes.
You can read more about the differences between time formats in MySQL here.
In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME
. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP
. Do you only need to store a date? Use DATE
. Do you only need to store a time? Use TIME
.
Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp
and :datetime
will default to DATETIME
, while :date
and :time
corresponds to DATE
and TIME
, respectively.
This means that within Rails, you only have to decide whether you need to store date, time or both.
Temporary tablespaces are used for database sorting and joining operations and for storing global temporary tables. It may grow in size over a period of time and thus either we need to recreate temporary tablespace or shrink it to release the unused space.
Assembly is the fundamental part of programming with .NET Framework. It contain code that CLR executes MSIL(Microsoft Intermediate Language) code in a portable executable file will not be executed if it does not have an associated assembly manifest.
As mentioned, the error message shows you the exact problem: you are passing 25 characters into a field set up to hold 20. You might also want to consider defining the columns a little more precisely. You can define whether the VARCHAR2 column will store a certain number of bytes or characters. You may encounter a problem in the future where you try to insert a multi byte character into the field, for example this is 5 characters in length but it won't fit into 5 bytes: 'ÀÈÌÕÛ'
Here is an example:
CREATE TABLE Customers(CustomerID VARCHAR2(9 BYTE), ...
or
CREATE TABLE Customers(CustomerID VARCHAR2(9 CHAR), ...
If this is something you'll need to do often...then you may want to denormalize the relationship between tables A and B.
For example, on insert to table B, you could write zero or more entries to a juncion table mapping B to A based on partial mapping. Similarly, changes to either table could update this association.
This all depends on how frequently tables A and B are modified. If they are fairly static, then taking a hit on INSERT is less painful then repeated hits on SELECT.
very simple, just concatenate the long to a string.
long date = curDateFld.getDate();
String str = ""+date;
I can't believe that no one mentioned that MySQL doesn't support Common Table Expressions (CTE) / "with" statements. It's a pretty annoying difference.
$sql="SELECT * FROM TABLE_NAME WHERE item_id=".$item_id;
$query=mysql_query($sql);
while($myrow=mysql_fetch_array($query)) {
echo print_r($myrow,1);
}
If you want to do this with 2 queries, you can always do something similar to this:
1) grab ids from the table with:
SELECT group_concat(id) as csv_result FROM your_table WHERE whatever = 'test' ...
Then copy result with mouse/keyboard or programming language to XXX below:
2) DELETE FROM your_table WHERE id IN ( XXX )
Maybe you could do this in one query, but this is what I prefer.
Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:
Item.objects.values("contest").annotate(Count("id"))
I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.
Usually one uses text editor to create source files (like JavaScript). I use VisualStudio which have intellisence supprt for JavaScript, but any other editor will do (vim or notepad on Windows are both fine).
To run JavaScript by itself you need something that can do that. I.e. on Windows you can directly run script from console using CScript script.js
command. There are other ways to run JavaScript on Windows and other OS.
Browsers (like Chrome) do not run JavaScript by itself, only as part of a page or extensions. It is unclear what one would expect of browser to do with JavaScript by itself.
pp does the job too, no gem requiring is required.
@a = Accrual.first ; pp @a
#<Accrual:0x007ff521e5ba50
id: 4,
year: 2018,
Jan: #<BigDecimal:7ff521e58f08,'0.11E2',9(27)>,
Feb: #<BigDecimal:7ff521e585d0,'0.88E2',9(27)>,
Mar: #<BigDecimal:7ff521e58030,'0.0',9(27)>,
Apr: #<BigDecimal:7ff521e53698,'0.88E2',9(27)>,
May: #<BigDecimal:7ff521e52fb8,'0.8E1',9(27)>,
June: #<BigDecimal:7ff521e52900,'0.8E1',9(27)>,
July: #<BigDecimal:7ff521e51ff0,'0.8E1',9(27)>,
Aug: #<BigDecimal:7ff521e51bb8,'0.88E2',9(27)>,
Sep: #<BigDecimal:7ff521e512f8,'0.88E2',9(27)>,
Oct: #<BigDecimal:7ff521e506c8,'0.0',9(27)>,
Nov: #<BigDecimal:7ff521e43d38,'0.888E3',9(27)>,
Dec: #<BigDecimal:7ff521e43478,'0.0',9(27)>,
You can also print two instances of an object:
pp( Accrual.first , Accrual.second)
`
`
`
This did the trick for me
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs
In Java >=8 you could also use the Streaming API:
Optional<String> first = set.stream().findFirst();
(Useful if the Set/List may be empty.)
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
Specify the ax
argument to matplotlib.pyplot.colorbar()
, e.g.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
for i in range(2):
for j in range(2):
data = np.array([[i, j], [i+0.5, j+0.5]])
im = ax[i, j].imshow(data)
plt.colorbar(im, ax=ax[i, j])
plt.show()
MattBryant's answer is a good one, but if you want to exclude more types of letters than just spaces, it will get clunky. Here's a variation on your current code using Counter
that will work:
from collections import Counter
import string
def count_letters(word, valid_letters=string.ascii_letters):
count = Counter(word) # this counts all the letters, including invalid ones
return sum(count[letter] for letter in valid_letters) # add up valid letters
Example output:
>>> count_letters("The grey old fox is an idiot.") # the period will be ignored
22
//call Facebook onclick on your customized button on click by the following
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
}
@Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
setContentView(R.layout.activity_main);
Button mycustomizeedbutton=(Button)findViewById(R.id.mycustomizeedbutton);
mycustomizeedbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
}
});
}
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 20px;
resize: both;
overflow: auto;
}
img{
height: 100%;
width: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<h1>The resize Property</h1>
<div>
<p>Let the user resize both the height and the width of this 1234567891011 div
element.
</p>
<p>To resize: Click and drag the bottom right corner of this div element.</p>
<img src="images/scenery.jpg" alt="Italian ">
</div>
<p><b>Note:</b> Internet Explorer does not support the resize property.</p>
</body>
</html>
For me (selectionChange)
and the suggested (onSelectionChange)
didn't work and I'm not using ReactiveForms
. What I ended up doing was using the (valueChange)
event like:
<mat-select (valueChange)="someFunction()">
And this worked for me
is null is the syntax I use for such things, when COALESCE is of no help.
Try:
if (@zipCode is null)
begin
([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)
end
else
begin
([Portal].[dbo].[Address].PostalCode=@zipCode )
end
The other answers have pointed out the solution for the majority of cases involving PropertySources
, but none have mentioned that certain property sources are unable to be casted into useful types.
One such example is the property source for command line arguments. The class that is used is SimpleCommandLinePropertySource
. This private class is returned by a public method, thus making it extremely tricky to access the data inside the object. I had to use reflection in order to read the data and eventually replace the property source.
If anyone out there has a better solution, I would really like to see it; however, this is the only hack I have gotten to work.
I have often thought that using elseif and dropping through case instances (where the language permits) are code odours, if not smells.
For myself, I have normally found that nested (if/then/else)s usually reflect things better than elseifs, and that for mutually exclusive cases (often where one combination of attributes takes precedence over another), case or something similar is clearer to read two years later.
I think the select statement used by Rexx is a particularly good example of how to do "Case" well (no drop-throughs) (silly example):
Select
When (Vehicle ¬= "Car") Then
Name = "Red Bus"
When (Colour == "Red") Then
Name = "Ferrari"
Otherwise
Name = "Plain old other car"
End
Oh, and if the optimisation isn't up to it, get a new compiler or language...
In addition to all the other answers, you could use switch
. But it does seem a bit long.
switch ($result->vocation) {
case 1:
echo 'Sorcerer';
break;
case 2:
echo 'Druid';
break;
case 3:
echo 'Paladin';
break;
case 4:
echo 'Knight';
break;
case 5:
echo 'Master Sorcerer';
break;
case 6:
echo 'Elder Druid';
break;
case 7:
echo 'Royal Paladin';
break;
default:
echo 'Elite Knight';
break;
}
Specifying a flex attribute to the container worked for me:
.container {
flex: 0 0 auto;
}
This ensures the height is set and doesn't grow either.
EDIT After some hunting around, this seems to be the best option:
https://github.com/googlemaps/js-info-bubble/blob/gh-pages/examples/example.html
You can see a customised version of this InfoBubble that I used on Dive Seven, a website for online scuba dive logging. It looks like this:
There are some more examples here. They definitely don't look as nice as the example in your screenshot, however.
You could send yourself an email an look in the email header (In Outlook: Open the mail, View->Options, there is 'Internet headers)
I found out one way to do it that gives the same result in almost all browsers. At the very least up-to-date browsers. It works in Firefox, Chrome, Safari, Opera. In IE it will just look almost as if there were no rules applied for inputs or labels (i.e., it'll still have the label a few pixels below the input), so I think it's excusable.
HTML
<label class="boxfix"><input type="radio">Label</label>
CSS
.boxfix {
vertical-align: bottom;
}
.boxfix input {
margin: 0;
vertical-align: bottom;
position: relative;
top: 1.999px; /* the inputs are slightly more centered in IE at 1px (they don't interpret the .999 here), and Opera will round it to 2px with three decimals */
}
Below code is working for me to record a outgoing phone call
//Call Recording varibales
private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
AUDIO_RECORDER_FILE_EXT_3GP };
AudioManager audioManager;
//put this methods to outside of oncreate() method
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
@Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(CallActivity.this,
"Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(CallActivity.this,
"Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
.show();
}
};
//below part of code to make your device on speaker
audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
//below part of code to start recording
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
//recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
Log.e("REDORDING :: ",e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e("REDORDING :: ",e.getMessage());
e.printStackTrace();
}
//For stop recording and keep in mind to set speaker off while call end or stop
audioManager.setSpeakerphoneOn(false);
try{
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}catch(RuntimeException stopException){
}
And give permission to manifest file,
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.
There's a niche case where git mv
remains very useful: when you want to change the casing of a file name on a case-insensitive file system. Both APFS (mac) and NTFS (windows) are, by default, case-insensitive (but case-preserving).
greg.kindel mentions this in a comment on CB Bailey's answer.
Suppose you are working on a mac and have a file Mytest.txt
managed by git. You want to change the file name to MyTest.txt
.
You could try:
$ mv Mytest.txt MyTest.txt
overwrite MyTest.txt? (y/n [n]) y
$ git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
Oh dear. Git doesn't acknowledge there's been any change to the file.
You could work around this with by renaming the file completely then renaming it back:
$ mv Mytest.txt temp.txt
$ git rm Mytest.txt
rm 'Mytest.txt'
$ mv temp.txt MyTest.txt
$ git add MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: Mytest.txt -> MyTest.txt
Hurray!
Or you could save yourself all that bother by using git mv
:
$ git mv Mytest.txt MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: Mytest.txt -> MyTest.txt
You can use this code in your button onclick method:
<button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>
There isn't a direct equivalent. Just store it numerically, e.g. number of seconds or something appropriate to your required accuracy.
change code of init like following,
public void init(){
menuDB = new MenuDBAdapter(this);
ll = (TableLayout) findViewById(R.id.displayLinear);
ll.removeAllViews()
for (int i = 0; i <2; i++) {
TableRow row=(TableRow)findViewById(R.id.display_row);
checkBox = new CheckBox(this);
tv = new TextView(this);
addBtn = new ImageButton(this);
addBtn.setImageResource(R.drawable.add);
minusBtn = new ImageButton(this);
minusBtn.setImageResource(R.drawable.minus);
qty = new TextView(this);
checkBox.setText("hello");
qty.setText("10");
row.addView(checkBox);
row.addView(minusBtn);
row.addView(qty);
row.addView(addBtn);
ll.addView(row,i);
}
You could use Map to make higher abstraction on instance of
private final Map<Class, Consumer<String>> actions = new HashMap<>();
Then having such map add some action to it:
actions.put(String.class, new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("action for String");
}
};
Then having an Object of not known type you could get specific action from that map:
actions.get(someObject).accept(someObject)
there are 2 ways start mongoDB Install location ( ex : C:/ )
first of all : copy mongoDB install folder into C:/ location then changed name to "mongodb" or something what u want. here is ex with "mongodb" name
1 : setup mongoDB is an windows service
1.1 : Make directory name "data" in C:/ ( so we have C:/data ),after that make directory "C:/data/db" <br>
1.2 : run in CMD ( Run as Admin) command -> "echo logpath=C:/mongodb/log/mongo.log > C:/mongodb/mongodb.cfg" <br>
1.3 : run in CMD (Run as Adin) command -> "C:/mongodb/bin/mongod.exe --config C:/mongodb/mongod.cfg --install" <br>
1.4 : run command "net start MongoDB" <br>
2: a small .BAT file to start mongoDB without install copy and paste to notepad and save file with filetype ".bat" here is it :
C:\mongodb\bin\mongod.exe –dbpath=C:/mongodb/data/db
PAUSE
if you getting error 1078 or 1087 lets remove all data in C:/data/db and restart mongoDB ( copy old data to new folder and back it up after restart mongoDB )
3 . GUI for mongoDB
i'm using rockmongo
have fun with it
set a reference to the Scripting.Runtime library and then use the FileSystemObject:
Dim fso as New FileSystemObject, aFile as File
if (fso.FileExists("PathToFile")) then
aFile = fso.GetFile("PathToFile")
aFile.Delete
End if
Linked lists provide very fast insertion or deletion of a list member. Each member in a linked list contains a pointer to the next member in the list so to insert a member at position i:
The disadvantage to a linked list is that random access is not possible. Accessing a member requires traversing the list until the desired member is found.
$results = DB::table('rooms')
->distinct()
->leftJoin('bookings', function($join)
{
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on('arrival','>=',DB::raw("'2012-05-01'"));
$join->on('arrival','<=',DB::raw("'2012-05-10'"));
$join->on('departure','>=',DB::raw("'2012-05-01'"));
$join->on('departure','<=',DB::raw("'2012-05-10'"));
})
->where('bookings.room_type_id', '=', NULL)
->get();
Not quite sure if the between clause can be added to the join in laravel.
Notes:
DB::raw()
instructs Laravel not to put back quotes.on()
will add AND
condition and orOn()
will add OR
condition.You need to install Entity framework by right click on your VS solution and click Manage NuGet Package solution and search there Entity framework. After installation the issue will be solved
i put this inside my head tags of the page i want a single reload on:
<?php if(!isset($_GET['mc'])) {
echo '<meta http-equiv="refresh" content= "0;URL=?mc=mobile" />';
} ?>
the value "mc" can be set to whatever you want, but both must match in the 2 lines. and the "=mobile" can be "=anythingyouwant" it just needs a value to stop the refresh.
You can throw a HttpResponseException
HttpResponseMessage response =
this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "your message");
throw new HttpResponseException(response);
As well as Amateras you could try Web Tools Project or Aptana. Although they will both give you way more than just a jsp editor.
Edit 2010/10/26 (comment from Simon Gibbs):
The Web Tools Project JSP editor is in the "Web Page Editor (Optional)" project.
Edit 2016/08/16 (extended comment from Dan Carter):
From Kepler (Eclipse 4.3.x) on, this is called "JSF Tools - Web Page Editor".
You can't declare default values for the parameters like C# (I believe) lets you, but you could simply just create an overload.
public int doSomething(int arg1, int arg2) {
//some logic here
return 0;
}
//overload supplies default values of 1 and 2
public int doSomething() {
return doSomething(1, 2);
}
If you are going to do something like this please do everyone else who works with your code a favor and make sure you mention in Javadoc comments what the default values you are using are!
To remove all files in folder
import os
import glob
files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
os.remove(file)
To remove all folders in a directory
from shutil import rmtree
import os
// os.path.join() # current working directory.
for dirct in os.listdir(os.path.join('path/to/folder')):
rmtree(os.path.join('path/to/folder',dirct))
You can also use the clock_gettime. This method can be used to measure:
Code is as follows:
#include < time.h >
#include <iostream>
int main(){
timespec ts_beg, ts_end;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_beg);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_end);
std::cout << (ts_end.tv_sec - ts_beg.tv_sec) + (ts_end.tv_nsec - ts_beg.tv_nsec) / 1e9 << " sec";
}
`
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
Button one;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.soho);
one = (Button)this.findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
}
});
}
}
Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.
In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]:
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
The following is a good solution -
import android.util.Base64;
String converted = Base64.encodeToString(toConvert.toString().getBytes(), Base64.DEFAULT);
String stringFromBase = new String(Base64.decode(converted, Base64.DEFAULT));
That's it. A single line encoding and decoding.
The href is probably generated in a javascript function. For example with jQuery:
$(function() {
$('a.view').attr('href', 'http://www.google.com');
});
You should use NVARCHAR anytime you have to store multiple languages. I believe you have to use it for the Asian languages but don't quote me on it.
Here's the problem if you take Russian for example and store it in a varchar, you will be fine so long as you define the correct code page. But let's say your using a default english sql install, then the russian characters will not be handled correctly. If you were using NVARCHAR() they would be handled properly.
Ok let me quote MSDN and maybee I was to specific but you don't want to store more then one code page in a varcar column, while you can you shouldn't
When you deal with text data that is stored in the char, varchar, varchar(max), or text data type, the most important limitation to consider is that only information from a single code page can be validated by the system. (You can store data from multiple code pages, but this is not recommended.) The exact code page used to validate and store the data depends on the collation of the column. If a column-level collation has not been defined, the collation of the database is used. To determine the code page that is used for a given column, you can use the COLLATIONPROPERTY function, as shown in the following code examples:
Here's some more:
This example illustrates the fact that many locales, such as Georgian and Hindi, do not have code pages, as they are Unicode-only collations. Those collations are not appropriate for columns that use the char, varchar, or text data type
So Georgian or Hindi really need to be stored as nvarchar. Arabic is also a problem:
Another problem you might encounter is the inability to store data when not all of the characters you wish to support are contained in the code page. In many cases, Windows considers a particular code page to be a "best fit" code page, which means there is no guarantee that you can rely on the code page to handle all text; it is merely the best one available. An example of this is the Arabic script: it supports a wide array of languages, including Baluchi, Berber, Farsi, Kashmiri, Kazakh, Kirghiz, Pashto, Sindhi, Uighur, Urdu, and more. All of these languages have additional characters beyond those in the Arabic language as defined in Windows code page 1256. If you attempt to store these extra characters in a non-Unicode column that has the Arabic collation, the characters are converted into question marks.
Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h.
All in all with all the issues you have to deal with when dealing with internalitionalization. It is my opinion that is easier to just use Unicode characters from the start, avoid the extra conversions and take the space hit. Hence my statement earlier.
Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster") {
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
else {
cLayout = "~/Views/Shared/_Layout.cshtml";
}
Layout = cLayout;
}
Procedure 2 : Set Layout by Returning from ActionResult
One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.
public ActionResult Index()
{
SampleModel model = new SampleModel();
//Any Logic
return View("Index", "_WebmasterLayout", model);
}
Procedure 3 : View - wise Layout (By defining Layout within each view on the top)
ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
Procedure 4 : Placing _ViewStart file in each of the directories
This is a very useful way to set different Layouts for each Controller in your ASP.NET MVC application. If we want to set default Layout for each directories than we can do this by putting _ViewStart file in each of the directories with the required Layout information as shown below:
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
There is often the tip to use 'echo.'
But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.
You could use echo(
. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.
More about the different ECHO:/\
variants is at DOS tips: ECHO. FAILS to give text or blank line.
Another option is to use GKMersenneTwisterRandomSource from GameKit. The docs say:
A deterministic pseudo-random source that generates random numbers based on a mersenne twister algorithm. This is a deterministic random source suitable for creating reliable gameplay mechanics. It is slightly slower than an Arc4 source, but more random, in that it has a longer period until repeating sequences. While deterministic, this is not a cryptographic random source. It is however suitable for obfuscation of gameplay data.
import GameKit
let minValue = 0
let maxValue = 100
var randomDistribution: GKRandomDistribution?
let randomSource = GKMersenneTwisterRandomSource()
randomDistribution = GKRandomDistribution(randomSource: randomSource, lowestValue: minValue, highestValue: maxValue)
let number = randomDistribution?.nextInt() ?? 0
print(number)
Example taken from Apple's sample code: https://github.com/carekit-apple/CareKit/blob/master/CareKitPrototypingTool/OCKPrototyper/CareKitPatient/RandomNumberGeneratorHelper.swift
In Typescript 1.5 and later, you can use for..of
as opposed to for..in
var numbers = [1, 2, 3];
for (var number of numbers) {
console.log(number);
}
The problem is that you forgot to import os. Add this line of code:
import os
And everything should be fine. Hope this helps!
line=`sed -n 2p myfile`
echo $line
import numpy as np
import threading
def threaded_process(items_chunk):
""" Your main process which runs in thread for each chunk"""
for item in items_chunk:
try:
api.my_operation(item)
except Exception:
print('error with item')
n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
thread_list.append(thread)
thread_list[thr].start()
for thread in thread_list:
thread.join()
Sheet.getPhysicalNumberOfRows()
does not involve some empty rows.
If you want to loop for all rows, do not use this to know the loop size.
If you have a look at Preferences -> General
you will notice at the bottom of the panel, there is a setting Load preferences from a custom folder or URL:
. There is a button next to it Save settings to Folder
.
So all you need to do is save your settings first and load it after you reinstalled your OS.
If the Save settings to Folder
is disabled, select a folder (e.g. empty) in the Load preferences from a custom folder or URL:
text box.
In iTerm2 3.3 on OSX the sequence is: iTerm2 menu, Preferences, General tab, Preferences subtab
Here you go:
public static void main (String[] args) {
System.out.println(reverserString("Akshay"));
}
private static String reverserString(String src) {
char[] sArr = src.toCharArray();
char[] dArr = new char[sArr.length];
for(int i=sArr.length; i>0; i--) {
dArr[sArr.length-i] = sArr[i-1];
}
return new String(dArr);
}
UPDATE: This no longer works in the current version, see below for correct answer (no need to vote down, this is correct on older versions).
Use the JsonTextReader
class with a StreamReader
or use the JsonSerializer
overload that takes a StreamReader
directly:
var serializer = new JsonSerializer();
serializer.Deserialize(streamReader);
The url
template tag will pass the parameter as a string and not as a function reference to reverse()
. The simplest way to get this working is adding a name
to the view:
url(r'^/logout/' , logout_view, name='logout_view')
This should work with any div
or screen size:
.center-screen {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="center-screen">_x000D_
I'm in the center_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
See more details about flex
here. This should work on most of the browsers, see compatibility matrix here.
Update: If you don't want the scroll bar, make min-height
smaller, for example min-height: 95vh;
There's also the subset
command, useful if you know which columns you want:
df <- data.frame(a = 1:10, b = 2:11, c = 3:12)
df <- subset(df, select = c(a, c))
UPDATED after comment by @hadley: To drop columns a,c you could do:
df <- subset(df, select = -c(a, c))
The %
operator in C is not the modulo operator but the remainder operator.
Modulo and remainder operators differ with respect to negative values.
With a remainder operator, the sign of the result is the same as the sign of the dividend while with a modulo operator the sign of the result is the same as the divisor.
C defines the %
operation for a % b
as:
a == (a / b * b) + a % b
with /
the integer division with truncation towards 0
. That's the truncation that is done towards 0
(and not towards negative inifinity) that defines the %
as a remainder operator rather than a modulo operator.
You also can use
NSString *className = [[myObject class] description];
on any NSObject
Check out RDFC http://www.bertel.de/software/rdfc/index-en.html
RDFC is probably not the fastest, but it does allocate data blocks. The absolutely fastest would have to use lower level API to just obtain cluster chains and put them into MFT without writing data.
Beware that there's no silver bullet here - if "creation" returns instantly that means you got a sparse file which just fakes a large file, but you won't get data blocks/chains till you write into it. If you just read is you'd get very fast zeros which could make you believe that your drive all of the sudden got blazingly fast :-)
get sock opt may be somewhat useful, however, another way would to have a signal handler installed for SIGPIPE. Basically whenever you the socket connection breaks, the kernel will send a SIGPIPE signal to the process and then you can do the needful. But this still does not provide the solution for knowing the status of the connection. hope this helps.
I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.
I have IIS 7 and installed PHP using Microsoft Web Platform Installer on Windows 7. In IIS, go to PHP Manager in settings main page -> PHP Extensions -> Enable or Disable an Extension. Intl extension is disabled by default.
I hope this helps
Basically when you hit 'return' on a function the function will stop and will not continue your iteration, so what you need to do is put it all on a list and then add it as a children of a widget
you can do something like this:
Widget getTextWidgets(List<String> strings)
{
List<Widget> list = new List<Widget>();
for(var i = 0; i < strings.length; i++){
list.add(new Text(strings[i]));
}
return new Row(children: list);
}
or even better, you can use .map() operator and do something like this:
Widget getTextWidgets(List<String> strings)
{
return new Row(children: strings.map((item) => new Text(item)).toList());
}
Using regex:
if re.match(r'^\s*$', line):
# line is empty (has only the following: \t\n\r and whitespace)
Using regex + filter()
:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
As seen on codepad.
If the intention is adding the local/working copy to SVN, I used to do it the following way.
Note: I use the TortoiseSVN client and these steps assume that you already have the TortoiseSVN client installed.
For Safari 12 and later, you can try the JSONBeautifier bookmarklet. Also works with other browsers.
I created this because JSON Formatter for Safari stopped working in Safari 12. There are a few new options for Safari 12, but I didn't find an open source one in the App Store, and I do not trust closed source browser extensions.
This can be used as a bookmarklet or the source, json-beautifier.js, can be copied and pasted into the browser console. The code is freely available for review and is less than 100 lines of code including comments. Runs entirely on your device and never sends your data over a network.
Works with local files too.
"The OPN [Debug] target overrides the OTHER_LDFLAGS build setting". This was the main issue. After adding $(inherited) in new line in other linker flags solved my issue.
If you're just comparing two files to see which is newer then -C
should work:
if (-C "file1.txt" > -C "file2.txt") {
{
/* Update */
}
There's also -M
, but I don't think it's what you want. Luckily, it's almost impossible to search for documentation on these file operators via Google.
Without any sub-processes you can:
shopt -s extglob
front=${input%%_+([a-zA-Z]).*}
digits=${front##+([a-zA-Z])_}
A very small variant of this will also work in ksh93.
ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children
$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")
Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {
$record = $indexName
foreach ($property in $_.PSObject.Properties){
#doSomething $property.Name, $property.Value
if($property.Name -like '*TextWrittenAsNumber*'){
$record = $record + "," + '"' + $property.Value + '"'
}
else{
$record = $record + "," + $property.Value
}
}
$array.add($record) | out-null
#write-host $record
}
Not PIL, but scipy.misc.imread
might still be interesting:
import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So you can iterate over it by
for y in range(im.shape[0]):
for x in range(im.shape[1]):
color = tuple(im[y][x])
r, g, b = color
For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.
I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.