You can't create pseudo elements in inline css.
However, if you can create a pseudo element in a stylesheet, then there's a way to style it inline by setting an inline style to its parent element, and then using inherit keyword to style the pseudo element, like this:
<parent style="background-image:url(path/to/file); background-size:0px;"></p>
<style>
parent:before{
content:'';
background-image:inherit;
(other)
}
</style>
sometimes this can be handy.
Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to.
As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.
Better use Uri.IsWellFormedUriString(string uriString, UriKind uriKind)
. http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx
Example :-
if(Uri.IsWellFormedUriString(slct.Text,UriKind.Absolute))
{
Uri uri = new Uri(slct.Text);
if (DeleteFileOnServer(uri))
{
nn.BalloonTipText = slct.Text + " has been deleted.";
nn.ShowBalloonTip(30);
}
}
Building on @user3114046's answer:
x <- data.frame(q=1,w=2,e=3)
x
# q w e
#1 1 2 3
names(x)[match(oldnames,names(x))] <- newnames
x
# A w B
#1 1 2 3
This won't be reliant on a specific ordering of columns in the x
dataset.
Commit: Snapshot | Changeset | Version | History-record | 'Save-as' of a repository. Git repository = series (tree) of commits.
Local repository: repository on your computer.
Remote repository: repository on a server (Github).
git commit
: Append a new commit (last commit + staged modifications) to the local repository. (Commits are stored in /.git
)
git push
, git pull
: Sync the local repository with its associated remote repository. push
- apply changes from local into remote, pull
- apply changes from remote into local.
In Swift 4, just as simple as Swift 3:
self.view.backgroundColor = UIColor.brown
Add a jQuery function,
(function($){
$.fn.regex = function(pattern, fn, fn_a){
var fn = fn || $.fn.text;
return this.filter(function() {
return pattern.test(fn.apply($(this), fn_a));
});
};
})(jQuery);
Then,
$('span').regex(/Sent/)
will select all span elements with text matches /Sent/.
$('span').regex(/tooltip.year/, $.fn.attr, ['class'])
will select all span elements with their classes match /tooltip.year/.
I'm using android:scaleType="fitCenter"
with satisfaction.
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
Could you use dircmp
?
shell_exec
- Execute command via shell and return the complete output as a string
exec
- Execute an external program.
The difference is that with shell_exec
you get output as a return value.
Datepicker is not part of jQuery. You have to get jQuery UI to use the datepicker.
When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance
@Html.LabelFor
, @Html.TextBoxFor
, etc@Html.EditorFor
, as you can assign specific behavior och looks in a editor viewI use latest CSS and "+" didn't work for me so I end up with
:first-child
As far as I have understood your question, you have listed two issues.
PROBLEM 1:
You are not able to execute the Python scripts by double clicking the Python file in Windows.
REASON:
The script runs too fast to be seen by the human eye.
SOLUTION:
Add input()
in the bottom of your script and then try executing it with double click. Now the cmd will be open until you close it.
EXAMPLE:
print("Hello World")
input()
PROBLEM 2:
./
issue
SOLUTION:
Use Tab to autocomplete the filenames rather than manually typing the filename with ./
autocomplete automatically fills all this for you.
USAGE:
CD into the directory in which .py
files are present and then assume the filename is test.py
then type python te
and then press Tab, it will be automatically converted to python ./test.py
.
I declare them as undefined when I don't assign a value because they are undefined after all.
When you compare update_date >= '2013-05-03'
postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.
So for update_date = '2013-05-03 14:45:00' your expression will be that:
'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'
This is always false
To solve this problem cast update_date to date
:
select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result
The min sdk version is the minimum version of the Android operating system required to run your application.
The target sdk version is the version of Android that your app was created to run on.
The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.
Usually the compile sdk version and the target sdk version are the same.
Just use Analyze | Inspect Code
with appropriate inspection enabled (Unused declaration under Declaration redundancy group).
Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"
The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource
annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
...
}
See @TestPropertySource in the Spring docs and Javadocs.
const setAttributes = (el, attrs) =>
Object.entries(attrs)
.forEach(args =>
el.setAttribute(...args))
This works for me in Chrome console. Any problem with this?
var { color, height } = elmo
var subelmo = { color, height }
console.log(subelmo) // {color: "red", height: "unknown"}
Select the project -> Right-Click -> clean and build and then run the project again simply solve the problem for me.
As, multiple process could bind the same port for example port 8086, In that case I have to kill all the processes involved with the port with PID. That might be cumbersome.
It's not so difficult.
You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.
Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.
This is pretty simple stuff.
For the sake of completeness, this can also be accomplished via an Action method/anonymous method combination:
//Process is a method, invoked as a method group
Dispatcher.Current.BeginInvoke((Action) Process);
//or use an anonymous method
Dispatcher.Current.BeginInvoke((Action)delegate => {
SomeFunc();
SomeOtherFunc();
});
My solution is modify or make new AndroidManifest.xml in android/app/src/debug:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
</manifest>
I am using React Native version: 0.61.5
Download the Java mail jars.
Extract the downloaded file.
Copy the ".jar" file and paste it into ProjectName\WebContent\WEB-INF\lib
folder
Right click on the Project and go to Properties
Select Java Build Path and then select Libraries
Add JARs...
Select the .jar file from ProjectName\WebContent\WEB-INF\lib
and click OK
that's all
You can start reading from here jQuery.ajax()
Actually Controller Action is a public method which can be accessed through Url. So any call of an Action from an Ajax call, either MicrosoftMvcAjax or jQuery can be made. For me, jQuery is the simplest one. It got a lots of examples in the link I gave above. The typical example for an ajax call is like this.
$.ajax({
// edit to add steve's suggestion.
//url: "/ControllerName/ActionName",
url: '<%= Url.Action("ActionName", "ControllerName") %>',
success: function(data) {
// your data could be a View or Json or what ever you returned in your action method
// parse your data here
alert(data);
}
});
More examples can be found in here
This code counts rows with date range:
Controller:
$this->load->model("YourModelName");
$data ['query'] = $this->YourModelName->get_report();
Model:
public function get_report()
{
$query = $this->db->query("SELECT *
FROM reservation WHERE arvdate <= '2016-7-20' AND dptrdate >= '2016-10-25' ");
return $query;
}
where 'arvdate' and 'dptrdate' are two dates on database and 'reservation' is the table name.
View:
<?php
echo $query->num_rows();
?>
This code is to return number of rows. To return table data, then use
$query->rows();
return $row->table_column_name;
Open the /etc/mysql/mysql.conf.d/mysqld.cnf
file and comment the
following line:
#bind-address = 127.0.0.1
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.
I tried for many ways to get my dialog be centered on the page and saw that the code:
$("#dialog").dialog("option", "position", 'top')
never change the dialog position when this was created.
Instead of, I change the selector level to get the entire dialog.
$("#dialog").parent()
<-- This is the parent object that the dialog() function create on the DOM, this is because the selector $("#dialog") does not apply the attributes, top, left.
To center my dialog, I use the jQuery-Client-Centering-Plugin
$("#dialog").parent().centerInClient();
You can use CSS hover in combination with an image background.
CSS
.image
{
background:url(images/back.png);
height:100px;
width:100px;
display: block;
float:left;
}
.image a {
display: none;
}
.image a:hover {
display: block;
}
HTML
<div class="image"><a href="#">Text you want on mouseover</a></div>
x = math.ceil(x * 100.0) / 100.0
This may work:
SELECT Count(tag) AS 'Tag Count'
FROM Table
GROUP BY tag
and
SELECT Count(tag) AS 'Negative Tag Count'
FROM Table
WHERE entryID > 0
GROUP BY tag
The reason why you are able to access the drive in when you normally run the executable from command prompt is that when u are executing it as normal exe you are running that application in the User account from which you have logged on . And that user has the privileges to access the network. But , when you install the executable as a service , by default if you see in the task manage it runs under 'SYSTEM' account . And you might be knowing that the 'SYSTEM' doesn't have rights to access network resources.
There can be two solutions to this problem.
To map the drive as persistent as already pointed above.
There is one more approach that can be followed. If you open the service manager by typing in the 'services.msc'you can go to your service and in the properties of your service there is a logOn tab where you can specify the account as any other account than 'System' you can either start service from your own logged on user account or through 'Network Service'. When you do this .. the service can access any network component and drive even if they are not persistent also. To achieve this programmatically you can look into 'CreateService' function at http://msdn.microsoft.com/en-us/library/ms682450(v=vs.85).aspx and can set the parameter 'lpServiceStartName ' to 'NT AUTHORITY\NetworkService'. This will start your service under 'Network Service' account and then you are done.
You can also try by making the service as interactive by specifying SERVICE_INTERACTIVE_PROCESS in the servicetype parameter flag of your CreateService() function but this will be limited only till XP as Vista and 7 donot support this feature.
Hope the solutions help you.. Let me know if this worked for you .
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
You can use an Explain Plan to get an objective answer.
For your problem, an Exists filter would probably perform the fastest.
<TextView
android:id="@+id/phoneNumber"
android:autoLink="phone"
android:linksClickable="true"
android:text="+91 22 2222 2222"
/>
This is how you can open EditText label assigned number on dialer directly.
A constructor in Java doesn't actually "build" the object, it is used to initialize fields.
Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.
Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.
If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.
first, give the div an id. Then, call function appendClass:
<script language="javascript">
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAdd) == -1)
{
document.getElementById(elementId).setAttribute("class", classToAppend);
}
}
</script>
As mentioned in the docs, boxes are stored at:
~/.vagrant.d/boxes
C:/Users/USERNAME/.vagrant.d/boxes
Usually, you would also have a header file that you include in your code to access the symbols.
One option is to have a separate model for such manipulations, using the same table:
class NoCallbacksModel < ActiveRecord::Base
set_table_name 'table_name_of_model_that_has_callbacks'
include CommonModelMethods # if there are
:
:
end
(Same approach might make things easier for bypassing validations)
Stephan
You can generate views and controllers for devise customization.
Use
rails g devise:controllers users -c=registrations
and
rails g devise:views
It will copy particular controllers and views from gem to your application.
Next, tell the router to use this controller:
devise_for :users, :controllers => {:registrations => "users/registrations"}
In general this error message means that you have tried to use indexing on a function. You can reproduce this error message with, for example
mean[1]
## Error in mean[1] : object of type 'closure' is not subsettable
mean[[1]]
## Error in mean[[1]] : object of type 'closure' is not subsettable
mean$a
## Error in mean$a : object of type 'closure' is not subsettable
The closure mentioned in the error message is (loosely) the function and the environment that stores the variables when the function is called.
In this specific case, as Joshua mentioned, you are trying to access the url
function as a variable. If you define a variable named url
, then the error goes away.
As a matter of good practise, you should usually avoid naming variables after base-R functions. (Calling variables data
is a common source of this error.)
There are several related errors for trying to subset operators or keywords.
`+`[1]
## Error in `+`[1] : object of type 'builtin' is not subsettable
`if`[1]
## Error in `if`[1] : object of type 'special' is not subsettable
If you're running into this problem in shiny
, the most likely cause is that you're trying to work with a reactive
expression without calling it as a function using parentheses.
library(shiny)
reactive_df <- reactive({
data.frame(col1 = c(1,2,3),
col2 = c(4,5,6))
})
While we often work with reactive expressions in shiny as if they were data frames, they are actually functions that return data frames (or other objects).
isolate({
print(reactive_df())
print(reactive_df()$col1)
})
col1 col2
1 1 4
2 2 5
3 3 6
[1] 1 2 3
But if we try to subset it without parentheses, then we're actually trying to index a function, and we get an error:
isolate(
reactive_df$col1
)
Error in reactive_df$col1 : object of type 'closure' is not subsettable
Here's a function I use that handles relative and absolute paths:
function md5hash($path)
{
$fullPath = Resolve-Path $path
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
try {
[System.BitConverter]::ToString($md5.ComputeHash($file))
} finally {
$file.Dispose()
}
}
Thanks to @davor above for the suggestion to use Open() instead of ReadAllBytes() and to @jpmc26 for the suggestion to use a finally block.
In theory, you can't deterministically find unused code. Theres a mathematical proof of this (well, this is a special case of a more general theorem). If you're curious, look up the Halting Problem.
This can manifest itself in Java code in many ways:
That being said, I use IDEA IntelliJ as my IDE of choice and it has extensive analysis tools for findign dependencies between modules, unused methods, unused members, unused classes, etc. Its quite intelligent too like a private method that isn't called is tagged unused but a public method requires more extensive analysis.
You can clean your project with gradle wrapper of your project. In linux:
$./gradlew clean
In windows:
>gradlew.bat clean
You can use find
find . -type d > output.txt
or tree
tree -d > output.txt
tree
, If not installed on your system.
If you are using ubuntu
sudo apt-get install tree
If you are using mac os
.
brew install tree
I will throw in what worked for me in the end. I needed to remove the initial commit on a repository as quarantined data had been misplaced, the commit had already been pushed.
Make sure you are are currently on the right branch.
git checkout master
git update-ref -d HEAD
git commit -m "Initial commit
git push -u origin master
This was able to resolve the problem.
Important
This was on an internal repository which was not publicly accessible, if your repository was publicly accessible please assume anything you need to revert has already been pulled down by someone else.
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
From Eclipsepedia on how to set a conditional breakpoint:
First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as
list.size()==0
. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.
There are few more considerations in prop() vs attr():
selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected..etc should be retrieved and set with the .prop() method. These do not have corresponding attributes and are only properties.
For input type checkbox
.attr('checked') //returns checked
.prop('checked') //returns true
.is(':checked') //returns true
prop method returns Boolean value for checked, selected, disabled, readOnly..etc while attr returns defined string. So, you can directly use .prop(‘checked’) in if condition.
.attr() calls .prop() internally so .attr() method will be slightly slower than accessing them directly through .prop().
Under "Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions" add _CRT_SECURE_NO_WARNINGS
Had the same problem because I was using performSelectorInBackground
.
Here's one simple way to ignore everything but valid brainfuck characters:
#define BF_VALID "+-><[].,"
if (strchr(BF_VALID, c))
code[n++] = c;
You can use display: flow-root
on the parent element to prevent margin collapsing through the containing element as it creates new Block Formatting Context.
Changing the value of the overflow property to auto or using flexbox will have the same effect.
In general you would do this with the stat module. But the command module has the creates
option which makes this very simple:
- name: touch file
command: touch /etc/file.txt
args:
creates: /etc/file.txt
I guess your touch command is just an example? Best practice would be to not check anything at all and let ansible do its job - with the correct module. So if you want to ensure the file exists you would use the file module:
- name: make sure file exists
file:
path: /etc/file.txt
state: touch
You should use what your FPGA documentation recommends. There is no portable way to initialize register values other than using a reset net. This has a hardware cost associated with it on most synthesis targets.
During startup in (-viewDidLoad or in storyboard)
do:
self.tableView.allowsMultipleSelectionDuringEditing = NO;
Override to support conditional editing of the table view. This only needs to be implemented if you are going to be returning NO
for some items. By default, all items are editable.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
}
}
add Internet permission in manifest
<uses-permission android:name="android.permission.INTERNET" />
than create methode as below,
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
return null;
}
}
now add this in your onCreate method,
ImageView img_add = (ImageView) findViewById(R.id.img_add);
img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));
this is works for me.
torch.reshape() is made to dupe the numpy reshape method.
It came after the view() and torch.resize_() and it is inside the dir(torch)
package.
import torch
x=torch.arange(24)
print(x, x.shape)
x_view = x.view(1,2,3,4) # works on is_contiguous() tensor
print(x_view.shape)
x_reshaped = x.reshape(1,2,3,4) # works on any tensor
print(x_reshaped.shape)
x_reshaped2 = torch.reshape(x_reshaped, (-1,)) # part of torch package, while view() and resize_() are not
print(x_reshaped2.shape)
Out:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23]) torch.Size([24])
torch.Size([1, 2, 3, 4])
torch.Size([1, 2, 3, 4])
torch.Size([24])
But did you know it can also work as a replacement for squeeze() and unsqueeze()
x = torch.tensor([1, 2, 3, 4])
print(x.shape)
x1 = torch.unsqueeze(x, 0)
print(x1.shape)
x2 = torch.unsqueeze(x1, 1)
print(x2.shape)
x3=x.reshape(1,1,4)
print(x3.shape)
x4=x.reshape(4)
print(x4.shape)
x5=x3.squeeze()
print(x5.shape)
Out:
torch.Size([4])
torch.Size([1, 4])
torch.Size([1, 1, 4])
torch.Size([1, 1, 4])
torch.Size([4])
torch.Size([4])
You can use TEXT
like this as part of a concatenation
=TEXT(A1,"dd-mmm-yy") & " other string"
With C++17 you can also return one ore more unmovable/uncopyable values (in certain cases). The possibility to return unmovable types come via the new guaranteed return value optimization, and it composes nicely with aggregates, and what can be called templated constructors.
template<typename T1,typename T2,typename T3>
struct many {
T1 a;
T2 b;
T3 c;
};
// guide:
template<class T1, class T2, class T3>
many(T1, T2, T3) -> many<T1, T2, T3>;
auto f(){ return many{string(),5.7, unmovable()}; };
int main(){
// in place construct x,y,z with a string, 5.7 and unmovable.
auto [x,y,z] = f();
}
The pretty thing about this is that it is guaranteed to not cause any copying or moving. You can make the example many
struct variadic too. More details:
Alternatively, since pip
itself is written in python, you can just call it with the python version you want to install the package for:
python2.7 -m pip install foo
You don't need the redirection, use only
* * * * * wget -qO /dev/null http://yoursite.com/tasks.php
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.
The returned collector throws an IllegalArgumentException
if the stream consists of two or more elements, and a NoSuchElementException
if the stream is empty.
Refer the below code for usage:
import static com.google.common.collect.MoreCollectors.onlyElement;
Person matchingPerson = objects.stream
.filter(p -> p.email().equals("testemail"))
.collect(onlyElement());
in School,
public void addTeacherName(classroom classroom, String teacherName) {
classroom.setTeacherName(teacherName);
}
BTW, use Pascal Case for class names. Also, I would suggest a Map<String, classroom>
to map a classroom name to a classroom.
Then, if you use my suggestion, this would work
public void addTeacherName(String className, String teacherName) {
classrooms.get(className).setTeacherName(teacherName);
}
function closeWindow() {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
alert("This will close the window");
window.open('','_self');
window.close();
}
closeWindow();
EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.
The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.
The value of EOF is -1 because it has to be different from any return value from getchar
that is an actual character. So getchar
returns any character value as an unsigned char, converted to int, which will therefore be non-negative.
If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar()
will return EOF
, and hence getchar() != EOF
will be false, and the loop will terminate.
[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.
If you have installed Anaconda but are not able to load the correct versions of python and ipython, or if you see conda: command not found when trying to use conda, this may be an issue with your PATH environment variable. At the prompt, type:
export PATH=~/anaconda/bin:$PATH
For this example, it is assumed that Anaconda is installed in the default ~/anaconda
location.
For posterity, I think this is quicker:
a = np.array([np.array(list()) for _ in y])
You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.
Responding to comment below:
>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object)], dtype=object)
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
In Gradle build file, add dependency:
implementation 'com.android.support:multidex:1.0.2'
or
implementation 'com.android.support:multidex:1.0.3'
or
implementation 'com.android.support:multidex:2.0.0'
And then in the "defaultConfig" section, add:
multiDexEnabled true
Under targetSdkVersion
minSdkVersion 17
targetSdkVersion 27
multiDexEnabled true
Now if you encounter this error
Error:Failed to resolve: multidex-instrumentation Open File
You need to change your gradle to 3.0.1
classpath 'com.android.tools.build:gradle:3.0.1'
And put the following code in the file gradle-wrapper.properties
distributionUrl=https://services.gradle.org/distributions/gradle-4.1-all.zip
Finally
add class Applition in project And introduce it to the AndroidManifest Which is extends from MultiDexApplication
public class App extends MultiDexApplication {
@Override
public void onCreate( ) {
super.onCreate( );
}
}
Run the project first to create an error, then clean the project
Finally, Re-launch the project and enjoy it
in my case I was using AWS SES and I had to verify both "FromEmail" and "Recipient". Once done that I could send without problems.
You need to load the URL Helper in order to use base_url()
. In your controller, do:
$this->load->helper('url');
Then in your view you can do:
echo base_url();
You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.
perhaps a:
i=2
while i < n:
if something:
do something
i += 1
else:
do something else
i = 2 #restart the loop
Since Java 8
mixedArrayList.forEach((o) -> {
String type = o.getClass().getSimpleName();
switch (type) {
case "String":
// treat as a String
break;
case "Integer":
// treat as an int
break;
case "Double":
// treat as a double
break;
...
default:
// whatever
}
});
I'm assuming mysql_fetch_array() perfroms a loop, so I'm interested in if using a while() in conjunction with it, if it saves a nested loop.
No. mysql_fetch_array
just returns the next row of the result and advances the internal pointer. It doesn't loop. (Internally it may or may not use some loop somewhere, but that's irrelevant.)
while ($row = mysql_fetch_array($result)) {
...
}
This does the following:
mysql_fetch_array
retrieves and returns the next row$row
true
, the contents of the loop are executed$row = mysql_fetch_array($result); foreach($row as $r) { ... }
This does the following:
mysql_fetch_array
retrieves and returns the next row$row
foreach
loops over the contents of the array and executes the contents of the loop as many times as there are items in the arrayIn both cases mysql_fetch_array
does exactly the same thing. You have only as many loops as you write. Both constructs do not do the same thing though. The second will only act on one row of the result, while the first will loop over all rows.
Try
data _null_;
monyy = '05May2013';
date = input(substr(strip(monyy),1,9),date9.);
put date=date9.;
run;
DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);
The problem is caused by your #grid
having a width:1140px
.
You need to set a min-width:1140px
on the body
.
This will stop the body
from getting smaller than the #grid
. Remove width:100%
as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/
html, body{
margin:0;
padding:0;
min-width: 1140px; /* this is the important part*/
}
#grid-container{
background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
width:1140px;
margin:0px auto;
}
If you want to append this css
file to header
you can do it using mounted()
function of the vue file. See the example.
Note: Assume you can access the css
file as http://www.yoursite/assets/styles/vendor.css
in the browser.
mounted() {
let style = document.createElement('link');
style.type = "text/css";
style.rel = "stylesheet";
style.href = '/assets/styles/vendor.css';
document.head.appendChild(style);
}
I had similar issue. Basically pip was looking in a wrong path (old installation path) or python. The following solution worked for me:
which python
)/usr/local/bin/pip2.7
and /usr/local/bin/pip
). The line should state the correct path to the python path. In my case, didn't. I corrected it and now it works fine.Im going to provide an argument against using socket.io.
I think using socket.io solely because it has fallbacks isnt a good idea. Let IE8 RIP.
In the past there have been many cases where new versions of NodeJS has broken socket.io. You can check these lists for examples... https://github.com/socketio/socket.io/issues?q=install+error
If you go to develop an Android app or something that needs to work with your existing app, you would probably be okay working with WS right away, socket.io might give you some trouble there...
Plus the WS module for Node.JS is amazingly simple to use.
I had some strings in the MongoDB Stored wich had to be reformated to a proper and valid dateTime field in the mongodb.
here is my code for the special date format: "2014-03-12T09:14:19.5303017+01:00"
but you can easyly take this idea and write your own regex to parse the date formats:
// format: "2014-03-12T09:14:19.5303017+01:00"
var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/;
db.Product.find().forEach(function(doc) {
var matches = myregexp.exec(doc.metadata.insertTime);
if myregexp.test(doc.metadata.insertTime)) {
var offset = matches[9] * (matches[8] == "+" ? 1 : -1);
var hours = matches[4]-(-offset)+1
var date = new Date(matches[1], matches[2]-1, matches[3],hours, matches[5], matches[6], matches[7] / 10000.0)
db.Product.update({_id : doc._id}, {$set : {"metadata.insertTime" : date}})
print("succsessfully updated");
} else {
print("not updated");
}
})
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
Coming here from first Google hit:
You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1
.
On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1
the warning will go away.
It's probably because you are building a gem from source and the gemspec shells out to git
, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git
but addressing that is for another day :)
My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
Always use the var
keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but omitting it means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:
Any variable created without the
var
keyword is created at the global scope and is not garbage collected when the function returns (because it doesn’t go out of scope), presenting the opportunity for a memory leak.
The .navbar-static-top
you are using forces your navbar
to become full-width. Remove that class and you will get a resizable navbar
. Then, you can wrap it in a span#
of the size you want.
<div class="container">
<div class="row">
<div class="span6 offset3">
<div class="navbar">
...
</div>
</div>
</div>
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
There is no difference between the %i
and %d
format specifiers for printf
. We can see this by going to the draft C99 standard section 7.19.6.1
The fprintf function which also covers printf
with respect to format specifiers and it says in paragraph 8:
The conversion specifiers and their meanings are:
and includes the following bullet:
d,i The int argument is converted to signed decimal in the style [-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.
On the other hand for scanf
there is a difference, %d
assume base 10 while %i
auto detects the base. We can see this by going to section 7.19.6.2
The fscanf function which covers scanf
with respect to format specifier, in paragraph 12 it says:
The conversion specifiers and their meanings are:
and includes the following:
d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer. i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.
I fixed @Sigh's solution by creating a (Linux) shellscript (.sh
) to do something similar. This is very crude, brutal, and requires adoption for your specific system. Use at your own risk. It might break your entire installation. Make backups of the folders before you run this script. Script can be improved.
#!/bin/bash
for J in *.jar
do
echo "Copying $J..."
mkdir -p "/tmp/$J"
cp "$J" "/tmp/$J/"
cd "/tmp/$J"
echo "Extracting $J..."
jar xf "$J"
rm "$J"
echo "Processing images..."
find . -name "*.gif" -exec convert {} -resize 200% {} \;
echo "Compressing $J..."
if [ `ls .[^.]* 2>/dev/null | wc -l` = 0 ]
then
jar cf "$J" *
else
jar cf "$J" * .[!.]*
fi
cd -
mv $J{,-bak}
mv "/tmp/$J/$J" .
rm -rf "/tmp/$J"
echo "Done."
echo ""
done
Run this in /opt/eclipse/plugins
and ~/.eclipse/org.eclipse.platform_4.x.x/plugins
(or whatever the paths for your installation are). Same issues as with @Sigh's solution: This is a brutal "fix" and breaks after every update or new installation.
Script can be perfected:
Requires imagemagick
.
.gif
?Fixes are welcome!
if(!isset($_POST['submit'])) exit();
$vars = array('login', 'password','confirm', 'name', 'email', 'phone');
$verified = TRUE;
foreach($vars as $v) {
if(!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if(!$verified) {
//error here...
exit();
}
//process here...
This is quite easy with jQuery using insertAfter()
or insertBefore()
:
<div class="left">content</div>
<div class="right">sidebar</div>
<script>
$('.right').insertBefore('left');
</script>
_x000D_
If you want to to set o condition for mobile devices you can make it like this:
<script>
var $iW = $(window).innerWidth();
if ($iW < 992){
$('.right').insertBefore('.left');
}else{
$('.right').insertAfter('.left');
}
</script>
_x000D_
example https://jsfiddle.net/w9n27k23/
Edited ZygD's answer for python 3.x.:
import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
print ("Stream #" + str(i + 1));
print ("Stream stats:");
print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
print ("Reliability: " + str(reliability[i]) + "%");
print ("HasPlaylist: " + str(isPlaylist[i]));
print ("Stream codec: " + str(codec[i]));
print ("This audio stream is " + tipe[i].lower());
print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
Its simple try below code --
a{
outline: medium none !important;
}
If happy cheers! Good day
The safest way is to modify the columns first to a binary type and then modify it back to it type using the desired charset.
Each column type have its respective binary type, as follows:
Eg.:
ALTER TABLE [TABLE_SCHEMA].[TABLE_NAME] MODIFY [COLUMN_NAME] VARBINARY;
ALTER TABLE [TABLE_SCHEMA].[TABLE_NAME] MODIFY [COLUMN_NAME] VARCHAR(140) CHARACTER SET utf8mb4;
I tried in several latin1 tables and it kept all the diacritics.
You can extract this query for all columns doing this:
SELECT
CONCAT('ALTER TABLE ', TABLE_SCHEMA,'.', TABLE_NAME,' MODIFY ', COLUMN_NAME,' VARBINARY;'),
CONCAT('ALTER TABLE ', TABLE_SCHEMA,'.', TABLE_NAME,' MODIFY ', COLUMN_NAME,' ', COLUMN_TYPE,' CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;')
FROM information_schema.columns
WHERE TABLE_SCHEMA IN ('[TABLE_SCHEMA]')
AND COLUMN_TYPE LIKE 'varchar%'
AND (COLLATION_NAME IS NOT NULL AND COLLATION_NAME NOT LIKE 'utf%');
After you do this on all your columns then you do it on all tables:
ALTER TABLE [TABLE_SCHEMA].[TABLE_NAME] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
To generate this query for all your table, use the following query:
SELECT
CONCAT('ALTER TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_COLLATION NOT LIKE 'utf8%'
and TABLE_SCHEMA in ('[TABLE_SCHEMA]');
And now that you modified all your columns and tables, do the same on the database:
ALTER DATABASE [DATA_BASE_NAME] CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci;
UPDATED: Using prop instead of attr
<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>
$('#vehicleChkBox').change(function(){
cb = $(this);
cb.val(cb.prop('checked'));
});
OUT OF DATE:
Here is the jsfiddle
<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE" />
$('#vehicleChkBox').change(function(){
if($(this).attr('checked')){
$(this).val('TRUE');
}else{
$(this).val('FALSE');
}
});
To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):
styles.css.php:
body
{
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
}
This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:
user_theme.css.php:
body
{
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
}
#panel
{
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
}
Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.
I'm using excel 2010 and below VBA code worked fine for a Form Button. It removes the assigned macro from the button and assign in next command.
To disable:
ActiveSheet.Shapes("Button Name").OnAction = Empty
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 16
To enable:
ActiveSheet.Shapes("Button Name").OnAction = ActiveWorkbook.Name & "!Macro function Name with _Click"
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 1
Pls note "ActiveWorkbook.Name" stays as it is. Do not insert workbook name instead of "Name".
Try this:
jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
Or this:
yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
You don't. Your array doesn't have a key [1]
. You could:
Make a new array, which contains the keys:
$newArray = array_keys($array);
echo $newArray[0];
But the value "one" is at $newArray[0]
, not [1]
.
A shortcut would be:
echo current(array_keys($array));
Get the first key of the array:
reset($array);
echo key($array);
Get the key corresponding to the value "value":
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1]
doesn't correspond to "one" any which way you turn it.
Since we now have inline javascript snippets I might as well add an interactive example of pre and pos increment. It's not C++ but the concept stays the same.
let A = 1;_x000D_
let B = 1;_x000D_
_x000D_
console.log('A++ === 2', A++ === 2);_x000D_
console.log('++B === 2', ++B === 2);
_x000D_
It's really easy to do from the command line. I had a gist of a script for doing this. It has now been incorporated into the ipa_sign script in https://github.com/RichardBronosky/ota-tools which I use daily. If you have any questions about using these tools, don't hesitate to ask.
The heart of it is this:
CODESIGN_ALLOCATE=`xcrun --find codesign_allocate`; export CODESIGN_ALLOCATE
IPA="/path/to/file.ipa"
PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in keychain
# unzip the ipa
unzip -q "$IPA"
# remove the signature
rm -rf Payload/*.app/_CodeSignature
# replace the provision
cp "$PROVISION" Payload/*.app/embedded.mobileprovision
# sign with the new certificate (--resource-rules has been deprecated OS X Yosemite (10.10), it can safely be removed)
/usr/bin/codesign -f -s "$CERTIFICATE" Payload/*.app
# zip it back up
zip -qr resigned.ipa Payload
Your new signed app is called resigned.ipa
Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:
'String leftShift' {
foo << bar << baz
}
'String concat' {
foo.concat(bar)
.concat(baz)
.toString()
}
The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:
Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
* JRE: 1.8.0_191
* Total Memory: 238 MB
* Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 453 7 460 469
String leftShift 287 2 289 295
String concat 169 1 170 173
GString template 24 0 24 24
Readable GString template 32 0 32 32
GString template toString 400 0 400 406
Readable GString template toString 412 0 412 419
StringBuilder 325 3 328 334
StringBuffer 390 1 391 398
StringBuffer with Allocation 259 1 260 265
You could use the append()
method defined on list
objects:
mergedlist =[]
for elem in listone:
mergedlist.append(elem)
for elem in listtwo:
mergedlist.append(elem)
You can overwrite a CSS class by making it "more specific".
You go up the HTML tree, and specify parent elements:
div.sidebar { ... }
is more specific than .sidebar { ... }
You can go all the way up to BODY if you need to:
body .sidebar { ... }
will override virtually anything.
See this handy guide: http://css-tricks.com/855-specifics-on-css-specificity/
Basically, you have three options:
EXPOSE
nor -p
EXPOSE
EXPOSE
and -p
1) If you specify neither EXPOSE
nor -p
, the service in the container will only be accessible from inside the container itself.
2) If you EXPOSE
a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.
3) If you EXPOSE
and -p
a port, the service in the container is accessible from anywhere, even outside Docker.
The reason why both are separated is IMHO because:
The documentation explicitly states:
The
EXPOSE
instruction exposes ports for use within links.
It also points you to how to link containers, which basically is the inter-container communication I talked about.
PS: If you do -p
, but do not EXPOSE
, Docker does an implicit EXPOSE
. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p
includes EXPOSE
. That's why I didn't list it above as a fourth case.
Was looking for an Answer as well, but all I could find was outdated.
This Issue is solved since HTML5: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
<option value="Microsoft Edge">
</datalist>
If I had not found that, I would have gone with this approach:
http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html
SELECT DISTINCT dbo.Table.Email,dbo.Table.FirstName dbo.Table.LastName, dbo.Table.DateOfBirth (etc) FROM dbo.Table.Contacts WHERE Email = 'name@email';
> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300
For array type Please try this one.
List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
Nothing can be worse than infinity.
The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role.
Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg
(SQL Server Client Network Utility) on each client machine.
For more information see SQL Server Browser Service on MSDN.
const b2s=t=>{let e=Math.log2(t)/10|0;return(t/1024**(e=e<=0?0:e)).toFixed(3)+"BKMGP"[e]};
console.log(b2s(0));
console.log(b2s(123));
console.log(b2s(123123));
console.log(b2s(123123123));
console.log(b2s(123123123123));
console.log(b2s(123123123123123));
_x000D_
Maybe your mac's date and time are incorrect. Just correct them.
Other answers show how to globally configure client certificates. However if you want to programmatically define the client key for one particular connection, rather than globally define it across every application running on your JVM, then you can configure your own SSLContext like so:
String keyPassphrase = "";
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("cert-key-pair.pfx"), keyPassphrase.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, null)
.build();
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpResponse response = httpClient.execute(new HttpGet("https://example.com"));
Throwing an exception will be good especially if you want to clarify the error reason:
throw "Error Message"
This will generate a terminating error.
First of all create a model POJO
import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "class_id")
public int classId;
@Column(name = "user_name")
public String userName;
//getter,setter
}
Controller
import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;
@RestController
public class HomeController {
@PersistenceUnit
private EntityManagerFactory emf;
@GetMapping("/")
public List<StdUser> actionIndex() {
EntityManager em = emf.createEntityManager(); // Without parameter
List<StdUser> arr_cust = (List<StdUser>)em
.createQuery("SELECT c FROM StdUser c")
.getResultList();
return arr_cust;
}
@GetMapping("/paramter")
public List actionJoin() {
int id = 3;
String userName = "Suresh Shrestha";
EntityManager em = emf.createEntityManager(); // With parameter
List arr_cust = em
.createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
.setParameter("Id",id)
.setParameter("UserName",userName)
.getResultList();
return arr_cust;
}
}
I use this - it never fails:
startingpoint = 'blah'
if sys.argv[1:]:
startingpoint = sys.argv[1]
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
2021 Jan.12th
the whole point for me is to explicitly specify the version as java 11 in my pom.xml, and I solved the problem by taking the following steps.
open terminal and input: java -version, then i got 1.8, and i went to .bash_profile to switch the java version to 11.2 as i have multiple java version installed. please remember "restart" your terminal and check your java version again to confirm switch is successful.
Then i went to File -> Project Structure to make sure my IntelliJ using the same version as my env, which is 11.2.
RESTART your Intellij, mvn clean install, solved, hope this could help someone with this issue, thanks.
Unlike in some laguages, empty
is not a keyword in Python. Python lists are constructed form the ground up, so if element i
has a value, then element i-1
has a value, for all i > 0
.
To do an equality check, you usually use either the ==
comparison operator.
>>> my_list = ["asdf", 0, 42, '', None, True, "LOLOL"]
>>> my_list[0] == "asdf"
True
>>> my_list[4] is None
True
>>> my_list[2] == "the universe"
False
>>> my_list[3]
""
>>> my_list[3] == ""
True
Here's a link to the strip
method: your comment indicates to me that you may have some strange file parsing error going on, so make sure you're stripping off newlines and extraneous whitespace before you expect an empty line.
As an addendum, if you want to reapply your changes on top of the remote, you can also try:
git pull --rebase origin master
If you then want to undo some of your changes (but perhaps not all of them) you can use:
git reset SHA_HASH
Then do some adjustment and recommit.
Ionic projects structure are similar as Angular projects, you can get use
ionic info
command to Print project, system, and environment information.
This command is an easy way to share information about your setup. If applicable, be sure to run ionic info within your project directory to display even more information.
We may use --json
after ionic info
to print system/environment info in JSON format
ionic info --json
If you want to use your custom pipe in your components, you can add
@Injectable({
providedIn: 'root'
})
annotation to your custom pipe. Then, you can use it as a service
For Python 3, I do the same kind of thing as shxfee's answer:
def print_list(my_list):
print('\n'.join(my_list))
a = ['foo', 'bar', 'baz']
print_list(a)
which outputs
foo
bar
baz
As an aside, I use a similar helper function to quickly see columns in a pandas DataFrame
def print_cols(df):
print('\n'.join(df.columns))
You could just use: {in and out function callback}
$(".result").hover(function () {
$(this).toggleClass("result_hover");
});
For your example, better will be to use CSS pseudo class :hover
: {no js/jquery needed}
.result {
height: 72px;
width: 100%;
border: 1px solid #000;
}
.result:hover {
background-color: #000;
}
Since Ruby has a million ways to do it, here's another way using Enumerable:
h0 = { "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1 = h0.inject({}) do |new, (name, value)|
new[name] = value;
new
end
Here is the "native" text tools way:
#!/bin/bash
string="abcd"
first=`echo $string|cut -c1|tr [a-z] [A-Z]`
second=`echo $string|cut -c2-`
echo $first$second
Yes, all browsers should not submit the disabled inputs, as they are read-only.
More information (section 17.12.1)
Attribute definitions
disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:
- Disabled controls do not receive focus.
- Disabled controls are skipped in tabbing navigation.
- Disabled controls cannot be successful.
The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.
This attribute is inherited but local declarations override the inherited value.
How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.
In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.
<INPUT disabled name="fred" value="stone">
Note. The only way to modify dynamically the value of the disabled attribute is through a script.
Use these lines in the code, because the textEntryView is the parent of username edittext and password edittext.
final EditText input1 = (EditText) textEntryView .findViewById(R.id.username);
final EditText input2 = (EditText) textEntryView .findViewById(R.id.password);
I wrote an article a while back about how closures can be used to simplify event-handling code. It compares ASP.NET event handling to client-side jQuery.
http://www.hackification.com/2009/02/20/closures-simplify-event-handling-code/
I will recommend you not to use any third party libraries for auto fetch OTP from SMS Inbox. This can be done easily if you have basic understanding of Broadcast Receiver and how it works. Just Try following approach :
Step 1) Create single interface i.e SmsListner
package com.wnrcorp.reba;
public interface SmsListener{
public void messageReceived(String messageText);}
Step 2) Create single Broadcast Receiver i.e SmsReceiver
package com.wnrcorp.reba;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
Boolean b;
String abcd,xyz;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for(int i=0;i<pdus.length;i++){
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
// b=sender.endsWith("WNRCRP"); //Just to fetch otp sent from WNRCRP
String messageBody = smsMessage.getMessageBody();
abcd=messageBody.replaceAll("[^0-9]",""); // here abcd contains otp
which is in number format
//Pass on the text to our listener.
if(b==true) {
mListener.messageReceived(abcd); // attach value to interface
object
}
else
{
}
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
}
Step 3) Add Listener i.e broadcast receiver in android manifest file
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
and add permission
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
Final Step 4) The activity where you going to auto fetch otp when it is received in inbox. In my case I'm fetching otp and setting on edittext field.
public class OtpVerificationActivity extends AppCompatActivity {
EditText ed;
TextView tv;
String otp_generated,contactNo,id1;
GlobalData gd = new GlobalData();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_verification);
ed=(EditText)findViewById(R.id.otp);
tv=(TextView) findViewById(R.id.verify_otp);
/*This is important because this will be called every time you receive
any sms */
SmsReceiver.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
ed.setText(messageText);
}
});
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try
{
InputMethodManager imm=
(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
}
catch(Exception e)
{}
if (ed.getText().toString().equals(otp_generated))
{
Toast.makeText(OtpVerificationActivity.this, "OTP Verified
Successfully !", Toast.LENGTH_SHORT).show();
}
});
}
}
Layout File for OtpVerificationActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_otp_verification"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wnrcorp.reba.OtpVerificationActivity">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/firstcard"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="10dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OTP Confirmation"
android:textSize="18sp"
android:textStyle="bold"
android:id="@+id/dialogTitle"
android:layout_margin="5dp"
android:layout_gravity="center"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/otp"
android:layout_margin="5dp"
android:hint="OTP Here"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Verify"
android:textSize="18sp"
android:id="@+id/verify_otp"
android:gravity="center"
android:padding="10dp"
android:layout_gravity="center"
android:visibility="visible"
android:layout_margin="5dp"
android:background="@color/colorPrimary"
android:textColor="#ffffff"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
Screenshots for OTP Verification Activity where you fetch OTP as soons as messages received
You can just add the overflow:auto option:
#second
{
width:300px;
height:100%;
overflow: auto;
background-color:#9ACD32;
}
Here is the code using Jackson ObjectMapper. To know more read this article.
import com.fasterxml.jackson.*
boolean compareJsonPojo(Object pojo1, Object pojo2) {
try {
ObjectMapper mapper = new ObjectMapper();
String str1 = mapper.writeValueAsString(pojo1);
String str2 = mapper.writeValueAsString(pojo2);
return mapper.readTree(str1).equals(mapper.readTree(str2));
} catch (JsonProcessingException e) {
throw new AssertionError("Error comparing JSON objects: " + e.getMessage());
}
}
Giving flex a value solved the problem for me, e.g.
flex: 1 0 auto
You need to add type assertion .(string)
. It is necessary because the map is of type map[string]interface{}
:
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port
In PHP there is a pretty good function utf8_encode() to solve this issue.
echo utf8_encode("Résumé");
//will output Résumé instead of R?sum?
git update-index function has several option you can find typing as below:
git update-index --help
Here you will find various option - how to handle with the function update-index.
[if you don't know the file name]
git update-index --really-refresh
[if you know the file name ]
git update-index --no-assume-unchanged <file>
will revert all the files those have been added in ignore list through.
git update-index --assume-unchanged <file>
Use where_in()
$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );
You could just make the join and after that select the wanted columns https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=dataframe%20join#pyspark.sql.DataFrame.join
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
You got the order of the arguments to mysqli_select_db()
backwards. And mysqli_error()
requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.
Note also that with mysqli you can specify the DB in mysqli_connect()
:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error();
}
You must use mysqli_connect_error()
, not mysqli_error()
, to get the error from mysqli_connect()
, since the latter requires you to supply a valid connection.
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
To update other branches like (backup) with your master branch copy. You can do follow either way (rebase or merge)...
Merge branches (there will be an extra commit automatically to the backup branch).
Note : Rebase is nothing but establishing a new base (a new copy)
git checkout backup git merge master git push
(Repeat for other branches if any like backup2 & etc..,)
git checkout backup git rebase master git push
(Repeat for other branches if any like backup2 & etc..,)
That's the wrong kind of question. The right question would be: "Which one is easier to understand for human readers of my code?"
If speed matters (later), don't ask, but measure. (And before that, measure whether optimizing this actually will make any noticeable difference.) Until then, write the code so that it is easiest to read.
Edit
Just to make this clear (although it already should have been): Breakthrough speedups usually come from things like using better algorithms, improving locality of data, reducing the use of dynamic memory, pre-computing results, etc. They rarely ever come from micro-optimizing single function calls, and where they do, they do so in very few places, which would only be found by careful (and time-consuming) profiling, more often than never they can be sped up by doing very non-intuitive things (like inserting noop
statements), and what's an optimization for one platform is sometimes a pessimization for another (which is why you need to measure, instead of asking, because we don't fully know/have your environment).
Let me underline this again: Even in the few applications where such things matter, they don't matter in most places they're used, and it is very unlikely that you will find the places where they matter by looking at the code. You really do need to identify the hot spots first, because otherwise optimizing code is just a waste of time.
Even if a single operation (like computing the square of some value) takes up 10% of the application's execution time (which IME is quite rare), and even if optimizing it saves 50% of the time necessary for that operation (which IME is even much, much rarer), you still made the application take only 5% less time.
Your users will need a stopwatch to even notice that. (I guess in most cases anything under 20% speedup goes unnoticed for most users. And that is four such spots you need to find.)
In SQL Server , cast text as datetime
select cast('5/21/2013 9:45:48' as datetime)
Try the Join-Path cmdlet:
Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
Join-Path -Path $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)"
}
This worked for me for cardView and will work the same for listview inside adapter calss, within onBindViewHolder()
function
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return false;
}
});
This works but password length should be exactly 8
. This is simple and requires pyDes.
from pyDes import *
def encode(data,password):
k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
return d
def decode(data,password):
k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.decrypt(data)
return d
x = encode('John Doe', 'mypass12')
y = decode(x,'mypass12')
print x
print y
OUTPUT:
³.\Þ\åS¾+æÅ`;Ê
John Doe
If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:
import socketserver
with socketserver.TCPServer(("localhost", 0), None) as s:
free_port = s.server_address[1]
Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.
For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:
import javax.mail.*
import javax.mail.internet.*
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('[email protected]', 'test1234');
}
}
def d_email = "[email protected]",
d_uname = "email",
d_password = "password",
d_host = "smtp.gmail.com",
d_port = "465", //465,587
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email."
def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".
If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".
To remove the commas, you'll need to use replace
on the string. To convert to a float so you can do the maths, you'll need parseFloat
:
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
parseFloat('500,000.00'.replace(/,/g, ''));
right click on the project and select Manage NuGet Packages..
In that select Json.NET
and install
After installation,
use the following namespace
using Newtonsoft.Json;
then use the following to deserialize
JsonConvert.DeserializeObject
Here is a complete method that only has one button, an 'ok', to close the UIAlert:
- (void) myAlert: (NSString*)errorMessage
{
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:errorMessage
message:@""
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"ok", nil];
myAlert.cancelButtonIndex = -1;
[myAlert setTag:1000];
[myAlert show];
}
In addition, you can simply convert byte array
to Bitmap
.
var bmp = new Bitmap(new MemoryStream(imgByte));
You can also get Bitmap
from file Path directly.
Bitmap bmp = new Bitmap(Image.FromFile(filePath));
The simplest answer is the one given by odinho - Velmont
First do git reset --merge ORIG_HEAD
For those looking to reset after changes are pushed, do this (Because this is the first post seen for any git reset merge questions)
git push origin HEAD --force
This will reset in a way that you won't get the merged changes back again after pull.
For anyone interested in applying this solution on a per request basis, this is an option and uses a Lambda expression. The same Lambda expression can be applied to the global filter mentioned by blak3r as well. This method appears to require .NET 4.5.
String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
In .NET 4.0, the Lambda Expression can be applied to the global filter as such
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
this worked for me .
const filterData = this.state.data2.filter(item=>((item.name.includes(text)) || (item.surname.includes(text)) || (item.email.includes(text)) || (item.userId === Number(text))) ) ;
To print the N first characters you can remove the N+1 characters up to the end of line:
$ sed 's/.//5g' <<< "defn-test"
defn
Add below line to your pg_hba.conf file. which will be present in installation directory of postgres
hostnossl all all 0.0.0.0/0 trust
It will start working.
Also, for posterity -- Clang (like GCC) accepts the -x
switch to set the language of the input files, for example,
$ clang -x c++ some_random_file.txt
This mailing list thread explains the difference between clang
and clang++
well: Difference between clang and clang++
The code is
document.addEventListener('keydown', function(event){
alert(event.keyCode);
} );
This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)
A simpler version, for easy eyes!
@(true?"yes":"no")
For Spring Boot 2.3.3.RELEASE straight from Spring Initialzr:
POM: data jpa, h2, web
application properties: spring.h2.console.enabled=true
When you run the application look for line like below in the run console:
2020-08-18 21:12:32.664 INFO 63256 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:eaa9d6da-aa2e-4ad3-9e5b-2b60eb2fcbc5'
Now use the above JDBC URL for h2-console and click on Connect
.
The @japf answer above is working fine and in my case I wanted to change the mouse cursor from a Spinning Wheel back to the normal Arrow once the CEF Browser finished loading the page. In case it can help someone, here is the code:
private void Browser_LoadingStateChanged(object sender, CefSharp.LoadingStateChangedEventArgs e) {
if (!e.IsLoading) {
// set the cursor back to arrow
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() => Mouse.OverrideCursor = Cursors.Arrow));
}
}
In my case, the problem was with a scatterplot of a dataframe X[]:
ax.scatter(X[:,0],X[:,1],c=colors,
cmap=CMAP, edgecolor='k', s=40) #c=y[:,0],
#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,
cmap=CMAP, edgecolor='k', s=40)
If you're running Angular 2 through ASP.NET Core 1 in Visual Studio 2015, you might find this solution from Jürgen Gutsch helpful. He describes it in a blog post. It was the best solution for me. Place the C# code provided below in your Startup.cs public void Configure() just before app.UseStaticFiles();
app.Use( async ( context, next ) => {
await next();
if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
context.Request.Path = "/index.html";
await next();
}
});
If you are using JetBrains editors like IntelliJ IDEA, PhpStorm, WebStorm etc. Use the following settings in Settings > File Watchers.
Convert style.scss
to style.css
set the arguments
--no-cache --update $FileName$:$FileNameWithoutExtension$.css
and output paths to refresh
$FileNameWithoutExtension$.css
Convert style.scss
to compressed style.min.css
set the arguments
--no-cache --update $FileName$:$FileNameWithoutExtension$.min.css --style compressed
and output paths to refresh
$FileNameWithoutExtension$.min.css
Beware false negatives from the trim()
function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[]
could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
If you only want to replace some characters you could use this:
import re
print re.sub(r'([\.\\\+\*\?\[\^\]\$\(\)\{\}\!\<\>\|\:\-])', r'\\\1', "example string.")
I made my own subversion repository on my Ubuntu One folder. Then, I imported the files to the repository using svn+ssh and my user account password.
When I want to do a checkout, I just checkout from my Ubuntu One folder. The commit process its analogue.
You must setup Ubutnu One on the devices that you want to grant access, then checkout the project from this folder to a temporary folder to edit it.
In my case, I use a folder in the Ubuntu One file-system, so I have the repository and my develop-folder in Ubuntu One.
A more recent version of the accepted answer.
Brief version:
$('#form').on('submit', function(e, options) {
options = options || {};
if ( !options.lots_of_stuff_done ) {
e.preventDefault();
$.ajax({
/* do lots of stuff */
}).then(function() {
// retrigger the submit event with lots_of_stuff_done set to true
$(e.currentTarget).trigger('submit', { 'lots_of_stuff_done': true });
});
} else {
/* allow default behavior to happen */
}
});
A good use case for something like this is where you may have some legacy form code that works, but you've been asked to enhance the form by adding something like email address validation before submitting the form. Instead of digging through the back-end form post code, you could write an API and then update your front-end code to hit that API first before allowing the form to do it's traditional POST.
To do that, you can implement code similar to what I've written here:
$('#signup_form').on('submit', function(e, options) {
options = options || {};
if ( !options.email_check_complete ) {
e.preventDefault(); // Prevent form from submitting.
$.ajax({
url: '/api/check_email'
type: 'get',
contentType: 'application/json',
data: {
'email_address': $('email').val()
}
})
.then(function() {
// e.type === 'submit', if you want this to be more dynamic
$(e.currentTarget).trigger(e.type, { 'email_check_complete': true });
})
.fail(function() {
alert('Email address is not valid. Please fix and try again.');
})
} else {
/**
Do traditional <form> post.
This code will be hit on the second pass through this handler because
the 'email_check_complete' option was passed in with the event.
*/
$('#notifications').html('Saving your personal settings...').fadeIn();
}
});
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
An example under Linux (Fedora 16) shows that memory is freed when R is closed:
$ free -m
total used free shared buffers cached
Mem: 3829 2854 974 0 344 1440
-/+ buffers/cache: 1069 2759
Swap: 4095 85 4010
2854 megabytes is used. Next I open an R session and create a large matrix of random numbers:
m = matrix(runif(10e7), 10000, 1000)
when the matrix is created, 3714 MB is used:
$ free -m
total used free shared buffers cached
Mem: 3829 3714 115 0 344 1442
-/+ buffers/cache: 1927 1902
Swap: 4095 85 4010
After closing the R session, I nicely get back the memory I used (2856 MB free):
$ free -m
total used free shared buffers cached
Mem: 3829 2856 972 0 344 1442
-/+ buffers/cache: 1069 2759
Swap: 4095 85 4010
Ofcourse you use Windows, but you could repeat this excercise in Windows and report how the available memory develops before and after you create this large dataset in R.
From man clock:
The clock() function returns an approximation of processor time used by the program.
So there is no indication you should treat it as milliseconds. Some standards require precise value of CLOCKS_PER_SEC
, so you could rely on it, but I don't think it is advisable.
Second thing is that, as @unwind stated, it is not float/double. Man times suggests that will be an int.
Also note that:
this function will return the same value approximately every 72 minutes
And if you are unlucky you might hit the moment it is just about to start counting from zero, thus getting negative or huge value (depending on whether you store the result as signed or unsigned value).
This:
printf("\n\n%6.3f", stop);
Will most probably print garbage as treating any int as float is really not defined behaviour (and I think this is where most of your problem comes). If you want to make sure you can always do:
printf("\n\n%6.3f", (double) stop);
Though I would rather go for printing it as long long int
at first:
printf("\n\n%lldf", (long long int) stop);
To prevent the page from jumping, you need to call e.stopPropagation();
after calling e.preventDefault();
:
stopPropagation
prevents the event from going up the DOM tree. More info here: https://api.jquery.com/event.stoppropagation/
Some time you have to give all the form element into a same div.
example:-
If you are using ajax submit with modal.
So all the elements are in modal body.
Some time we put submit button in modal footer.
Your understanding is correct. However, if we walk through:
(.*)
will swallow the whole string;(\\d+)
is satistifed (which is why 0
is captured, and not 3000
);(.*)
will then capture the rest.I am not sure what the original intent of the author was, however.
It's worth mentioning that if you need to execute a single command you can abbreviate
if [ ! -f "$file" ]; then
echo "$file"
fi
to
test -f "$file" || echo "$file"
or
[ -f "$file" ] || echo "$file"
All I had to do was run:
sudo apt-get install libfontconfig1
I was in the folder located at /usr/lib/x86_64-linux-gnu
and it worked perfectly.
I suggest using vlookup function to get the nearest match.
Prepare data range and name it: 'numberRange':
Select the range. Go to menu: Data ? Named ranges... ? define the new named range.
Use this simple formula:
=VLOOKUP(A2,numberRange,2)
This way you can ommit errors, and easily correct the result.
Having had a similar problem with data from 1800 to now, this worked for me:
data2$date=as.character(data2$date)
lct <- Sys.getlocale("LC_TIME");
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works
Firstly, I'd recommend breaking the module up into the useful things you need. But you can always create a class extending that for your invocation:
module UsefulThings
def a
puts "aaay"
end
def b
puts "beee"
end
end
def test
ob = Class.new.send(:include, UsefulThings).new
ob.a
end
test
Make sure you follow the language definition for JSON. In your second example, the section:
"labs":[{
""
}]
Is invalid since an object must be composed of zero or more key-value pairs "a" : "b"
, where "b"
may be any valid value. Some parsers may automatically interpret { "" }
to be { "" : null }
, but this is not a clearly defined case.
Also, you are using a nested array of objects [{}]
quite a bit. I would only do this if:
As already mentioned, tern.js is a new and promising project with plugins for Sublime Text, Vim and Emacs. I´ve been using TernJS for Sublime for a while and the suggestions I get are way better than the standard ones:
Tern scans all .js files in your project. You can get support for DOM, nodejs, jQuery, and more by adding "libs" in your .sublime-project file:
"ternjs": {
"exclude": ["wordpress/**", "node_modules/**"],
"libs": ["browser", "jquery"],
"plugins": {
"requirejs": {
"baseURL": "./js"
}
}
}
I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.
window.onload = function(){ doSomethingCool(); };
becomes...
window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };
Tensorflow also implemented functions for resizing/padding images tf.image.pad tf.pad.
padded_image = tf.image.pad_to_bounding_box(image, top_padding, left_padding, target_height, target_width)
padded_image = tf.pad(image, paddings, "CONSTANT")
These functions work just like other input-pipeline features of tensorflow and will work much better for machine learning applications.
It's not practical to parse URLs using regex. A full implementation of the RFC1738 rules would result in an enormously long regex (assuming it's even possible). Certainly your current expression fails many valid URLs, and passes invalid ones.
Instead:
a. use a proper URL parser that actually follows the real rules. (I don't know of one for JavaScript; it would probably be overkill. You could do it on the server side though). Or,
b. just trim away any leading or trailing spaces, then check it has one of your preferred schemes on the front (typically ‘http://’ or ‘https://’), and leave it at that. Or,
c. attempt to use the URL and see what lies at the end, for example by sending it am HTTP HEAD request from the server-side. If you get a 404 or connection error, it's probably wrong.
it return true even if url is something like "http://wwww".
Well, that is indeed a perfectly valid URL.
If you want to check whether a hostname such as ‘wwww’ actually exists, you have no choice but to look it up in the DNS. Again, this would be server-side code.