If your package.json looks something like the following:
...
"devDependencies": {
"babel": "^6.5.2",
"babel-eslint": "^6.0.4",
"babel-polyfill": "^6.8.0",
"babel-preset-es2015": "^6.6.0",
"babelify": "^7.3.0",
...
And you get the Cannot find module 'babel/polyfill'
error message, then you probably just need to change your import statement FROM:
import "babel/polyfill";
TO:
import "babel-polyfill";
And make sure it comes before any other import
statement (not necessarily at the entry point of your application).
Reference: https://babeljs.io/docs/usage/polyfill/
First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.
The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "
Source and example of polyfill here:
http://www.programmerinterview.com/index.php/html5/html5-polyfill/
Show commits and commit contents from other-branch
that are not in your current branch:
git show @..other-branch
Additionally you can apply the commits from other-branch
directly to your current branch:
git cherry-pick @..other-branch
Here's a script to get foreign keys:
SELECT TOP(150)
t.[name] AS [Table],
cols.[name] AS [Column],
t2.[name] AS [Referenced Table],
c2.[name] AS [Referenced Column],
constr.[name] AS [Constraint]
FROM sys.tables t
INNER JOIN sys.foreign_keys constr ON constr.parent_object_id = t.object_id
INNER JOIN sys.tables t2 ON t2.object_id = constr.referenced_object_id
INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = constr.object_id
INNER JOIN sys.columns cols ON cols.object_id = fkc.parent_object_id AND cols.column_id = fkc.parent_column_id
INNER JOIN sys.columns c2 ON c2.object_id = fkc.referenced_object_id AND c2.column_id = fkc.referenced_column_id
--WHERE t.[name] IN ('?', '?', ...)
ORDER BY t.[Name], cols.[name]
private void dtGrdVwRFIDTags_DataSourceChanged(object sender, EventArgs e)
{
dtGrdVwRFIDTags.Refresh();
this.dtGrdVwRFIDTags.Columns[1].Visible = false;
foreach (DataGridViewRow row in this.dtGrdVwRFIDTags.Rows)
{
if (row.Cells["TagStatus"].Value != null
&& row.Cells["TagStatus"].Value.ToString() == "Lost"
|| row.Cells["TagStatus"].Value != null
&& row.Cells["TagStatus"].Value.ToString() == "Damaged"
|| row.Cells["TagStatus"].Value != null
&& row.Cells["TagStatus"].Value.ToString() == "Discarded")
{
row.DefaultCellStyle.BackColor = Color.LightGray;
row.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
}
else
{
row.DefaultCellStyle.BackColor = Color.Ivory;
}
}
//for (int i= 0 ; i<dtGrdVwRFIDTags.Rows.Count - 1; i++)
//{
// if (dtGrdVwRFIDTags.Rows[i].Cells[3].Value.ToString() == "Damaged")
// {
// dtGrdVwRFIDTags.Rows[i].Cells["TagStatus"].Style.BackColor = Color.Red;
// }
//}
}
I've been frustrated by this myself and finally solved it. As Romain Guy hinted to, there's another state, "android:state_selected"
, that you must use. Use a state drawable for the background of your list item, and use a different state drawable for listSelector
of your list:
list_row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="@drawable/listitem_background"
>
...
</LinearLayout>
listitem_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/android:transparent" />
<item android:drawable="@drawable/listitem_normal" />
</selector>
layout.xml that includes the ListView:
...
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/listitem_selector"
/>
...
listitem_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/listitem_pressed" />
<item android:state_focused="true" android:drawable="@drawable/listitem_selected" />
</selector>
You can use lamba function:
index = df.index[lambda x : for x in df.index() ]
print(index)
For the record, the spring.jpa.hibernate.ddl-auto
property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto
.
The values create
, create-drop
, validate
, and update
basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update
operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update
operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop
so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update
to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none
or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
Firstly we should understand when we use $.ajax and when we use $.get/$.post
When we require low level control over the ajax request such as request header settings, caching settings, synchronous settings etc.then we should go for $.ajax.
$.get/$.post: When we do not require low level control over the ajax request.Only simple get/post the data to the server.It is shorthand of
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
and hence we can not use other features(sync,cache etc.) with $.get/$.post.
Hence for low level control(sync,cache,etc.) over ajax request,we should go for $.ajax
$.ajax({
type: 'GET',
url: url,
data: data,
success: success,
dataType: dataType,
async:false
});
Please don't use printf("%s", your_string.c_str());
Use cout << your_string;
instead. Short, simple and typesafe. In fact, when you're writing C++, you generally want to avoid printf
entirely -- it's a leftover from C that's rarely needed or useful in C++.
As to why you should use cout
instead of printf
, the reasons are numerous. Here's a sampling of a few of the most obvious:
printf
isn't type-safe. If the type you pass differs from that given in the conversion specifier, printf
will try to use whatever it finds on the stack as if it were the specified type, giving undefined behavior. Some compilers can warn about this under some circumstances, but some compilers can't/won't at all, and none can under all circumstances.printf
isn't extensible. You can only pass primitive types to it. The set of conversion specifiers it understands is hard-coded in its implementation, and there's no way for you to add more/others. Most well-written C++ should use these types primarily to implement types oriented toward the problem being solved.It makes decent formatting much more difficult. For an obvious example, when you're printing numbers for people to read, you typically want to insert thousands separators every few digits. The exact number of digits and the characters used as separators varies, but cout
has that covered as well. For example:
std::locale loc("");
std::cout.imbue(loc);
std::cout << 123456.78;
The nameless locale (the "") picks a locale based on the user's configuration. Therefore, on my machine (configured for US English) this prints out as 123,456.78
. For somebody who has their computer configured for (say) Germany, it would print out something like 123.456,78
. For somebody with it configured for India, it would print out as 1,23,456.78
(and of course there are many others). With printf
I get exactly one result: 123456.78
. It is consistent, but it's consistently wrong for everybody everywhere. Essentially the only way to work around it is to do the formatting separately, then pass the result as a string to printf
, because printf
itself simply will not do the job correctly.
printf
format strings can be quite unreadable. Even among C programmers who use printf
virtually every day, I'd guess at least 99% would need to look things up to be sure what the #
in %#x
means, and how that differs from what the #
in %#f
means (and yes, they mean entirely different things).The fastest way in Visual Studio 2017 is to go to Tools -> SQL Server -> New query.. Choose from Local databases and choose the desired Database name at the bottom.
Alternative way
Visual Studio 2017 Server name is:
(localdb)\MSSQLLocalDB
Add the new connection using menu Tools -> Connect to Database...
If you are designing your Javafx application using SceneBuilder
then use -fx-text-fill
(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield
.
I came here for the same problem and solved it in this way.
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
To give custom parameters to facebook share its better to give only the link and facebook gets its Title + Description + Picture automatically from the page that you are sharing. In order to "help" facebook API find those things you can put the following things in the header of the page that you are sharing:
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
If the page is not under your control use what AllisonC has shared above.
Use your own button/link/text and then you can use a modal view type of popup this way:
<script type= 'text/javascript'>
$('#twitterbtn-link,#facebookbtn-link').click(function(event) {
var width = 575,
height = 400,
left = ($(window).width() - width) / 2,
top = ($(window).height() - height) / 2,
url = this.href,
opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
window.open(url, 'twitter', opts);
return false;
});
</script>
where twitterbtn-link and facebookbtn-link are both ids of anchors.
If you are still inside the vi editor, you might be in a different mode from the one you want. Hit ESC a couple of times (until it rings or flashes) and then "i" to enter INSERT mode or "a" to enter APPEND mode (they are the same, just start before or after current character).
If you are back at the command prompt, make sure you can locate the file, then navigate to that directory and perform the mentioned "vi helloWorld.txt". Once you are in the editor, you'll need to check the vi reference to know how to perform the editions you want (you may want to google "vi reference" or "vi cheat sheet").
Once the edition is done, hit ESC again, then type :wq
to save your work or :q!
to quit without saving.
For quick reference, here you have a text-based cheat sheet.
Use a smarty template for your stuff then just set the POST array as a smarty array and open the template. In the template just echo out the array so if it passes:
if(correct){
header("Location: passed.php");
} else {
$smarty->assign("variables", $_POST);
$smarty->display("register_error.php");
exit;
}
I have not tried this yet but I am going to try it as a solution and will let you know what I find. But of course this method assumes that you are using smarty.
If not you can just recreate your form there on the error page and echo info into the form or you could send back non important data in a get from and get it
ex.
register.php?name=mr_jones&address==......
echo $_GET[name];
In the Divi Theme Documentation, it says that the theme comes with access to 'ePanel' which also has an 'Integration' section.
You should be able to add this code:
<script>
$( ".et-pb-icon" ).click(function() {
$( this ).toggleClass( "active" );
});
</script>
into the the box that says 'Add code to the head of your blog' under the 'Integration' tab, which should get the jQuery working.
Then, you should be able to style your class to what ever you need.
You could use this simple function
function getRandomColor(){
var color = "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
return color;
}
Yes, you can do that which returns boolean. The following java code in WebDriver with TestNG or JUnit can do:
protected boolean isTextPresent(String text){
try{
boolean b = driver.getPageSource().contains(text);
return b;
}
catch(Exception e){
return false;
}
}
Now call the above method as below:
assertTrue(isTextPresent("Your text"));
Or, there is another way. I think, this is the better way:
private StringBuffer verificationErrors = new StringBuffer();
try {
assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]* Your text here\r\n\r\n[\\s\\S]*$"));
} catch (Error e) {
verificationErrors.append(e.toString());
}
That seems fairly reasonable for what you're trying to do.
A slightly shorter version which leans on Python to do more of the heavy lifting might be:
for logs in mydir:
for line in mylog:
#...if the conditions are met
list1.append(line)
if any(True for line in list1 if "string" in line):
list2.extend(list1)
del list1
....
The (True for line in list1 if "string" in line)
iterates over list
and emits True
whenever a match is found. any()
uses short-circuit evaluation to return True
as soon as the first True
element is found. list2.extend()
appends the contents of list1
to the end.
To create the datepicker and set the date.
$('.next_date').datepicker({ dateFormat: 'dd-mm-yy'}).datepicker("setDate", new Date());
The bitmap constructor has resizing built in.
Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");
http://msdn.microsoft.com/en-us/library/0wh0045z.aspx
If you want control over interpolation modes see this post.
This question's bit old, but, there's a tricky scenario which also leads to this error:
In controller:
ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());
The above code will lead to an error in this part: .Select(a=>a.ToString())
because of the below reason:
You're passing a ViewBag.id
to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:
GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)
So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.
Create a script similar to this:
#!/bin/sh -e
location=~/`date +%Y%m%d_%H%M%S`.db
mysqldump -u root --password=<your password> database_name > $location
gzip $location
Then you can edit the crontab
of the user that the script is going to run as:
$> crontab -e
And append the entry
01 * * * * ~/script_path.sh
This will make it run on the first minute of every hour every day.
Then you just have to add in your rolls and other functionality and you are good to go.
After creating Set just convert it to List and get by index from List:
Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");
List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";
I had this error when accidentally putting the wmain inside a namespace. wmain should not be in any namespace. Moreover, I had a main function in one of the libs I was using, and VS took the main from there, what made it even stranger.
How about setInterval, to check for complete iteration count, brings guarantee. not sure if it won't overload the scope though but I use it and seems to be the one
_.forEach(actual_JSON, function (key, value) {
// run any action and push with each iteration
array.push(response.id)
});
setInterval(function(){
if(array.length > 300) {
callback()
}
}, 100);
All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:
public int Position {get; set}
In your view model builder you set the position 1 through 4.
BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:
<div class="@Model.GridCSS">
Move the switch statement to your view model builder and populate the CSS class there.
switch(myvar)
{
case 2 or 5:
// ...
break;
case 7 or 12:
// ...
break;
// ...
}
I have string that displays UTF-8 encoded characters
There is no such thing in .NET. The string class can only store strings in UTF-16 encoding. A UTF-8 encoded string can only exist as a byte[]. Trying to store bytes into a string will not come to a good end; UTF-8 uses byte values that don't have a valid Unicode codepoint. The content will be destroyed when the string is normalized. So it is already too late to recover the string by the time your DecodeFromUtf8() starts running.
Only handle UTF-8 encoded text with byte[]. And use UTF8Encoding.GetString() to convert it.
If you need Set
rather than List
, you can use EnumSet.allOf().
Set<EnumerationClass> set = EnumSet.allOf(EnumerationClass.class);
Update: JakeRobb is right. My answer is about java.lang.Enum instead of java.util.Enumeration. Sorry for unrelated answer.
The void
operator returns undefined
for any argument/expression passed to it. so you can test against the result (actually some minifiers change your code from undefined
to void 0
to save a couple of characters)
For example:
void 0
// undefined
if (variable === void 0) {
// variable is undefined
}
Here is the code I was looking for :
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Or
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));
I have faced the same issue in Ubuntu because the Angular app directory was having root
permission. Changing the ownership to the local user solved the issue for me.
$ sudo -i
$ chown -R <username>:<group> <ANGULAR_APP>
$ exit
$ cd <ANGULAR_APP>
$ ng serve
BOOTSTRAP 4
you can use a combination of
fa-chevron-down, fa-chevron-up
fa-sort-down, fa-sort-up
<th class="text-center">
<div class="btn-group" role="group">
<button type="button" class="btn btn-xs btn-link py-0 pl-0 pr-1">
Some Text OR icon
</button>
<div class="btn-group-vertical">
<a href="?sort=asc" class="btn btn-xs btn-link p-0">
<i class="fas fa-sort-up"></i>
</a>
<a href="?sort=desc" class="btn btn-xs btn-link p-0">
<i class="fas fa-sort-down"></i>
</a>
</div>
</div>
</th>
You could do this pretty easily with my date-shortcode package:
const dateShortcode = require('date-shortcode')
var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
This thread was helpful in finding the solution in my particular case (bootstrap 3)
@media (max-width: 767px) {
.container-fluid, .row {
padding:0px;
}
.navbar-header {
margin:0px;
}
}
Check if there is any white space after the html tag at the bottom. Remove any whitespace below helped me
System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.
If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.
source: this post
if you created your elements dynamically(using javascript), then this code doesn't work. Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.
For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..
Earlier we have .live() function
$('selector').live('click', function()
{
//your code
});
but .live() is deprecated.This can be replaced by other functions.
Delegate():
Using delegate() function you can click on dynamically generated HTML elements.
Example:
$(document).delegate('selector', 'click', function()
{
//your code
});
EDIT: The delegate() method was deprecated in version 3.0. Use the on() method instead.
ON():
Using on() function you can click on dynamically generated HTML elements.
Example:
$(document).on('click', 'selector', function()
{
// your code
});
You can use esentutl to copy (mainly big) files with a progress bar:
esentutl /y "my.file" /d "another.file" /o
the progress bar looks like this:
The downloads have moved, it says that on that very page:
In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.
http://chromedriver.storage.googleapis.com/index.html?path=2.24/
It is working for me in Win7 64 bit.
Here's an option if you need to escape multiple %'s in a string with some already escaped.
(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])
To sanitise the message before passing it to String.format, you can use the following
Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);
StringBuffer buf = new StringBuffer();
while (m1.find())
m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));
// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();
This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.
It will leave any already escaped characters alone (e.g. %%, %%%% etc.)
Is there a way to get it via $event->getComposer()->getRepositoryManager()->getAllPackages()
you can use this site to generate a proxy for you. it generates a class and can parse and validate your input JSON object.
Ideally runtime exceptions should not be thrown. A checked exception(business exception) should be created for your scenario. Because if either of these exception is thrown and logged, it misguides the developer while going through the logs. Instead business exceptions do not create that panic and usually ignored while troubleshooting logs.
instead of click on Restore Database click on Restore File and Filegroups..
thats work on my sql server
No, they are pretty different from each other.
Both are different specializations of @Component annotation (in practice, they're two different implementations of the same interface) so both can be discovered by the classpath scanning (if you declare it in your XML configuration)
@Service annotation is used in your service layer and annotates classes that perform service tasks, often you don't use it but in many case you use this annotation to represent a best practice. For example, you could directly call a DAO class to persist an object to your database but this is horrible. It is pretty good to call a service class that calls a DAO. This is a good thing to perform the separation of concerns pattern.
@Controller annotation is an annotation used in Spring MVC framework (the component of Spring Framework used to implement Web Application). The @Controller annotation indicates that a particular class serves the role of a controller. The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations.
So looking at the Spring MVC architecture you have a DispatcherServlet class (that you declare in your XML configuration) that represent a front controller that dispatch all the HTTP Request towards the appropriate controller classes (annotated by @Controller). This class perform the business logic (and can call the services) by its method. These classes (or its methods) are typically annotated also with @RequestMapping annotation that specify what HTTP Request is handled by the controller and by its method.
For example:
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
@Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
@RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
This class is a controller.
This class handles all the HTTP Request toward "/appointments" "folder" and in particular the get method is the method called to handle all the GET HTTP Request toward the folder "/appointments".
I hope that now it is more clear for you.
I needed to change an input
to an arrow in my project. Below is final work.
#in_submit {_x000D_
background-color: white;_x000D_
border-left: #B4C8E9;_x000D_
border-top: #B4C8E9;_x000D_
border-right: 3px solid black;_x000D_
border-bottom: 3px solid black;_x000D_
width: 15px;_x000D_
height: 15px;_x000D_
transform: rotate(-45deg);_x000D_
margin-top: 4px;_x000D_
margin-left: 4px;_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<input id="in_submit" type="button" class="convert_btn">
_x000D_
Here Fiddle
I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:
if (!place) return <NotFound />;
hope that helps!
I installed python-numpy python-scipy python-matplotlib, but it didn't work for me and I got the same error. Pylab isn't recognized without matplotlib. So I used this:
from matplotlib import pylab
from pylab import *
and worked for me.
This is the only one that worked for me in .cshtml file:
@Html.ActionLink(
"Name",
"Action",
"Controller",
routeValues: null,
htmlAttributes:new Dictionary<string, object> {{ "onclick", "alert('Test');" }})
I hope this helps.
This is how I used this is as an example:
CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost
You probably want something like this overload of String.Join:
String.Join<T> Method (String, IEnumerable<T>)
Docs:
http://msdn.microsoft.com/en-us/library/dd992421.aspx
In your example, you'd use
String.Join("", Client);
If you don't want to use LINQ, then:
int index;
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Prop == oProp)
{
index = i;
break;
}
}
this way you are iterating list only once.
In support to the excellent answers here, and for future convenience, there may be a case where you want to flip the truth values in the columns and have other values remain the same (nan values for instance)
In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series[series.notna()] #remove nan values
In[3]: series # without nan
Out[3]:
0 True
2 False
dtype: object
# Out[4] expected to be inverse of Out[3], pandas applies bitwise complement
# operator instead as in `lambda x : (-1*x)-1`
In[4]: ~series
Out[4]:
0 -2
2 -1
dtype: object
as a simple non-vectorized solution you can just, 1. check types2. inverse bools
In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series.apply(lambda x : not x if x is bool else x)
Out[2]:
Out[2]:
0 True
1 NaN
2 False
3 NaN
dtype: object
One thing you could do is to have the following snippet in your Workbook:
Sub SaveCodeModules()
'This code Exports all VBA modules
Dim i%, sName$
With ThisWorkbook.VBProject
For i% = 1 To .VBComponents.Count
If .VBComponents(i%).CodeModule.CountOfLines > 0 Then
sName$ = .VBComponents(i%).CodeModule.Name
.VBComponents(i%).Export "C:\Code\" & sName$ & ".vba"
End If
Next i
End With
End Sub
I found this snippet on the Internet.
Afterwards, you could use Subversion to maintain version control. For example by using the command line interface of Subversion with the 'shell' command within VBA. That would do it. I'm even thinking of doing this myself :)
Just in case someone else comes across this, to clarify the answer `n is grave accent n, not single tick n
It's compiler dependent. That said, in general using "
prioritizes headers in the current working directory over system headers. <>
usually is used for system headers. From to the specification (Section 6.10.2):
A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the
<
and>
delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read# include <h-char-sequence> new-line
with the identical contained sequence (including
>
characters, if any) from the original directive.
So on most compilers, using the ""
first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <>
starts the search with system headers.
As mentioned above several times, it's not possible to catch a StackOverflowException that was raised by the System due to corrupted process-state. But there's a way to notice the exception as an event:
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspxStarting with the .NET Framework version 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.
Nevertheless your application will terminate after exiting the event-function (a VERY dirty workaround, was to restart the app within this event haha, havn't done so and never will do). But it's good enough for logging!
In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads.
I made a method to do this below called jsonArrayToObjectList
. Its a handy static class that will take a filename and the file contains an array in JSON form.
List<Items> items = jsonArrayToObjectList(
"domain/ItemsArray.json", Item.class);
public static <T> List<T> jsonArrayToObjectList(String jsonFileName, Class<T> tClass) throws IOException {
ObjectMapper mapper = new ObjectMapper();
final File file = ResourceUtils.getFile("classpath:" + jsonFileName);
CollectionType listType = mapper.getTypeFactory()
.constructCollectionType(ArrayList.class, tClass);
List<T> ts = mapper.readValue(file, listType);
return ts;
}
og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"
console.log(og_date.split('-')); // => [ '2012', '10', '01' ]
og_date.value
would only work if the date were stored as a property on the og_date object.
Such as: var og_date = {}; og_date.value="2012-10-01";
In that case, your original console.log would work.
You could try:
$(this).closest(".column").prev().find(".inputQty").val();
<!-- xaml code-->
<Grid>
<ComboBox Name="cmbData" SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
</Grid>
//student Class
public class Student
{
public int Id { set; get; }
public string name { set; get; }
}
//set 2 properties in MainWindow.xaml.cs Class
public ObservableCollection<Student> studentInfo { set; get; }
public Student SelectedstudentInfo { set; get; }
//MainWindow.xaml.cs Constructor
public MainWindow()
{
InitializeComponent();
bindCombo();
this.DataContext = this;
cmbData.ItemsSource = studentInfo;
}
//method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
public void bindCombo()
{
ObservableCollection<Student> studentList = new ObservableCollection<Student>();
studentList.Add(new Student { Id=0 ,name="==Select=="});
studentList.Add(new Student { Id = 1, name = "zoyeb" });
studentList.Add(new Student { Id = 2, name = "siddiq" });
studentList.Add(new Student { Id = 3, name = "James" });
studentInfo=studentList;
}
//button click to get selected student MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student = SelectedstudentInfo;
if(student.Id ==0)
{
MessageBox.Show("select name from dropdown");
}
else
{
MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
}
}
i used this to extract video duration from ffprobe json output :
MOVIE_INFO=`ffprobe "path/to/movie.mp4" -show_streams -show_format -print_format json -v quiet`
MOVIE_SECONDS=`echo "$MOVIE_INFO"|grep -w \"duration\" |tail -1 | cut -d\" -f4 |cut -d \. -f 1`
it can be used to extract value from any json :
value=`echo "$jsondata"|grep -w \"key_name\" |tail -1 | cut -d\" -f4
For eslint:
"editor.codeActionsOnSave": { "source.fixAll.eslint": true }
I realize this is an old question and has been answered but this could help someone.
In your activity
private ScheduledExecutorService scheduleTaskExecutor;
In onCreate
scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
//Schedule a task to run every 5 seconds (or however long you want)
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// Do stuff here!
runOnUiThread(new Runnable() {
@Override
public void run() {
// Do stuff to update UI here!
Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
}
});
}
}, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.
I had also forgotten to actually install MySQL in the first place. Following this guide helped a lot.
http://www.djangoapp.com/blog/2011/07/24/installation-of-mysql-server-on-mac-os-x-lion/
As well as adding these lines to my .profile:
export PATH="/usr/local/mysql/bin:$PATH"
alias mysql=/usr/local/mysql/bin/mysql
alias mysqladmin=/usr/local/mysql/bin/mysqladmin
It was KB2553154. Microsoft needs to release a fix. As a developer of Excel applications we can't go to all our clients computers and delete files off them. We are getting blamed for something Microsoft caused.
You can use '
(which is iffy in IE) or '
(which should work everywhere). For a comprehensive list, see the W3C HTML5 Named Character References or the HTML entities table on WebPlatform.org.
The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.
Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.
This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.
See also here:
The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.
In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.
1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2
You need to use AND statement in your formula
=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")
And if both conditions are met, return 1.
You could also add more conditions in your AND statement.
You'll be wanting to use glob()
Example:
$files = glob('/path/to/dir/*.xml');
There are couple of way which can be used.
const stations = [
{call:'station one',frequency:'000'},
{call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)
Solution 1
<p>{callList.join(', ')}</p>
Solution 2
<ol>
{ callList && callList.map(item => <li>{item}</li>) }
</ol>
Of course there are other ways also available.
This worked for me:
<script>
function sel_file() {
$("input[name=userfile]").trigger('click');
}
</script>
<input type="file" name="userfile" id="userfile" />
<a href="javascript:sel_file();">Click</a>
I had the same issue, and it ended up being a problem with the php max post size. Increasing it solved the problem.
I found a more recent blog post in Anaconda which instructs how to install the TF easily. I used:
conda create -n tensorflow_env tensorflow
Or for the GPU version (Make sure that you have NVIDIA GPU)
conda create -n tensorflow_gpuenv tensorflow-gpu
This way you will have different environments for different TFs.
All string functions as lower
, upper
, strip
are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable
, it will fail.
x = 'hello'
x[0] = 'i' #'str' object does not support item assignment
There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them
@Test
public void testSortedMaps() {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "Josh");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "Anna");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", "Bernie");
List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
mapList.add(map1);
mapList.add(map2);
mapList.add(map3);
Collections.sort(mapList, new Comparator<Map<String, String>>() {
public int compare(final Map<String, String> o1, final Map<String, String> o2) {
return o1.get("name").compareTo(o2.get("name"));
}
});
Assert.assertEquals("Anna", mapList.get(0).get("name"));
Assert.assertEquals("Bernie", mapList.get(1).get("name"));
Assert.assertEquals("Josh", mapList.get(2).get("name"));
}
For a number, it is tricky because if a numeric cell is empty
VBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.
The following check worked for me to see if there was an actual 0 entered into the cell:
If CStr(rng.value) = "0" then
'your code here'
End If
Try
find . -type d
or
find . -type d -ls
The more extended and simplified function from sbgoran's answer.
This allow deep scan and find an array's simillarity.
var result = objectDifference({_x000D_
a:'i am unchanged',_x000D_
b:'i am deleted',_x000D_
e: {a: 1,b:false, c: null},_x000D_
f: [1,{a: 'same',b:[{a:'same'},{d: 'delete'}]}],_x000D_
g: new Date('2017.11.25'),_x000D_
h: [1,2,3,4,5]_x000D_
},_x000D_
{_x000D_
a:'i am unchanged',_x000D_
c:'i am created',_x000D_
e: {a: '1', b: '', d:'created'},_x000D_
f: [{a: 'same',b:[{a:'same'},{c: 'create'}]},1],_x000D_
g: new Date('2017.11.25'),_x000D_
h: [4,5,6,7,8]_x000D_
});_x000D_
console.log(result);_x000D_
_x000D_
function objectDifference(obj1, obj2){_x000D_
if((dataType(obj1) !== 'array' && dataType(obj1) !== 'object') || (dataType(obj2) !== 'array' && dataType(obj2) !== 'object')){_x000D_
var type = '';_x000D_
_x000D_
if(obj1 === obj2 || (dataType(obj1) === 'date' && dataType(obj2) === 'date' && obj1.getTime() === obj2.getTime()))_x000D_
type = 'unchanged';_x000D_
else if(dataType(obj1) === 'undefined')_x000D_
type = 'created';_x000D_
if(dataType(obj2) === 'undefined')_x000D_
type = 'deleted';_x000D_
else if(type === '') type = 'updated';_x000D_
_x000D_
return {_x000D_
type: type,_x000D_
data:(obj1 === undefined) ? obj2 : obj1_x000D_
};_x000D_
}_x000D_
_x000D_
if(dataType(obj1) === 'array' && dataType(obj2) === 'array'){_x000D_
var diff = [];_x000D_
obj1.sort(); obj2.sort();_x000D_
for(var i = 0; i < obj2.length; i++){_x000D_
var type = obj1.indexOf(obj2[i]) === -1?'created':'unchanged';_x000D_
if(type === 'created' && (dataType(obj2[i]) === 'array' || dataType(obj2[i]) === 'object')){_x000D_
diff.push(_x000D_
objectDifference(obj1[i], obj2[i])_x000D_
);_x000D_
continue;_x000D_
}_x000D_
diff.push({_x000D_
type: type,_x000D_
data: obj2[i]_x000D_
});_x000D_
}_x000D_
_x000D_
for(var i = 0; i < obj1.length; i++){_x000D_
if(obj2.indexOf(obj1[i]) !== -1 || dataType(obj1[i]) === 'array' || dataType(obj1[i]) === 'object')_x000D_
continue;_x000D_
diff.push({_x000D_
type: 'deleted',_x000D_
data: obj1[i]_x000D_
});_x000D_
}_x000D_
} else {_x000D_
var diff = {};_x000D_
var key = Object.keys(obj1);_x000D_
for(var i = 0; i < key.length; i++){_x000D_
var value2 = undefined;_x000D_
if(dataType(obj2[key[i]]) !== 'undefined')_x000D_
value2 = obj2[key[i]];_x000D_
_x000D_
diff[key[i]] = objectDifference(obj1[key[i]], value2);_x000D_
}_x000D_
_x000D_
var key = Object.keys(obj2);_x000D_
for(var i = 0; i < key.length; i++){_x000D_
if(dataType(diff[key[i]]) !== 'undefined')_x000D_
continue;_x000D_
_x000D_
diff[key[i]] = objectDifference(undefined, obj2[key[i]]);_x000D_
}_x000D_
}_x000D_
_x000D_
return diff;_x000D_
}_x000D_
_x000D_
function dataType(data){_x000D_
if(data === undefined || data === null) return 'undefined';_x000D_
if(data.constructor === String) return 'string';_x000D_
if(data.constructor === Array) return 'array';_x000D_
if(data.constructor === Object) return 'object';_x000D_
if(data.constructor === Number) return 'number';_x000D_
if(data.constructor === Boolean) return 'boolean';_x000D_
if(data.constructor === Function) return 'function';_x000D_
if(data.constructor === Date) return 'date';_x000D_
if(data.constructor === RegExp) return 'regex';_x000D_
return 'unknown';_x000D_
}
_x000D_
It seems that you are asking multiple things. To answer them:
You can extract the numbers by catching them in capturing parentheses:
.*(\d+) rofl.*
and using $1
to get the string out (.*
is for "the rest before and after on the same line)
With sed as example, the idea becomes this to replace all strings in a file with only the matching number:
sed -e 's/.*(\d+) rofl.*/$1/g' inputFileName > outputFileName
or:
echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'
Performance wise, they are exactly the same (at least in SQL Server).
PS: Be aware that the IMPLICIT OUTER JOIN
syntax is deprecated since SQL Server 2005. (The IMPLICIT INNER JOIN
syntax as used in the question is still supported)
Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing
Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.
I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):
public LimitedSizeQueue implements Queue
{
private int maxSize;
private LinkedList storageArea;
public LimitedSizeQueue(final int maxSize)
{
this.maxSize = maxSize;
storageArea = new LinkedList();
}
public boolean offer(ElementType element)
{
if (storageArea.size() < maxSize)
{
storageArea.addFirst(element);
}
else
{
... remove last element;
storageArea.addFirst(element);
}
}
... the rest of this class
A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:
public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
private int maxSize;
private CircularFifoBuffer storageArea;
public LimitedSizeQueue(final int maxSize)
{
if (maxSize > 0)
{
this.maxSize = maxSize;
storateArea = new CircularFifoBuffer(maxSize);
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
... implement the Queue interface using the CircularFifoBuffer class
}
You can't return two (or multiple) columns in your subquery to do the comparison in the WHERE A_ID IN (subquery)
clause - which column is it supposed to compare A_ID
to? Your subquery must only return the one column needed for the comparison to the column on the other side of the IN
. So the query needs to be of the form:
SELECT * From ThisTable WHERE ThisColumn IN (SELECT ThatColumn FROM ThatTable)
You also want to add sorting so you can select just from the top rows, but you don't need to return the COUNT as a column in order to do your sort; sorting in the ORDER
clause is independent of the columns returned by the query.
Try something like this:
select count(distinct dNum)
from myDB.dbo.AQ
where A_ID in
(SELECT DISTINCT TOP (0.1) PERCENT A_ID
FROM myDB.dbo.AQ
WHERE M > 1 and B = 0
GROUP BY A_ID
ORDER BY COUNT(DISTINCT dNum) DESC)
I created this small batch script based on the answers here, as there are many valid ones. Feel free to add to this so long as you follow the same format:
REM Parameter-testing
Setlocal EnableDelayedExpansion EnableExtensions
IF NOT "%~1"=="" (echo Percent Tilde 1 failed with quotes) ELSE (echo SUCCESS)
IF NOT [%~1]==[] (echo Percent Tilde 1 failed with brackets) ELSE (echo SUCCESS)
IF NOT "%1"=="" (echo Quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1]==[] (echo Brackets one failed) ELSE (echo SUCCESS)
IF NOT "%1."=="." (echo Appended dot quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1.]==[.] (echo Appended dot brackets one failed) ELSE (echo SUCCESS)
pause
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
Redirect aspx :
<iframe>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.avsapansiyonlar.com/altinkum-tatil-konaklari.aspx");
}
</script>
</iframe>
You can use a RegExp to replace all the non-digit characters:
var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238
I'm getting the following error when compiling Adam Rosenfield's code on Windows. It turns out few things are missing from the code.
Error (Before)
C:\C\Codes>gcc time.c -o time
time.c:3:12: error: initializer element is not constant
time_t t = time(NULL);
^
time.c:4:16: error: initializer element is not constant
struct tm tm = *localtime(&t);
^
time.c:6:8: error: expected declaration specifiers or '...' before string constant
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:36: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:55: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:70: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:82: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:94: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:105: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
C:\C\Codes>
Solution
C:\C\Codes>more time.c
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
C:\C\Codes>
Compiling
C:\C\Codes>gcc time.c -o time
C:\C\Codes>
Final Output
C:\C\Codes>time
now: 2018-3-11 15:46:36
C:\C\Codes>
I hope this will helps others too
This cannot be done from within the controller itself, but rather from your View. As I see it, you have two options:
Decorate your link with the "_blank" attribute (examples using HTML helper and straight HMTL syntax)
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank"})
<a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>
Use Javascript to open a new window
window.open("Link URL")
You can use LOG such as :
Log.e(String, String) (error)
Log.w(String, String) (warning)
Log.i(String, String) (information)
Log.d(String, String) (debug)
Log.v(String, String) (verbose)
example code:
private static final String TAG = "MyActivity";
...
Log.i(TAG, "MyClass.getView() — get item number " + position);
In relation to the original question I'd like to add to the accepted answer by Mohamed Mansour that there is also a way to make this work the other way around:
You can access other extension pages (i.e. options page, popup page) from within the background page/script with the chrome.extension.getViews()
call. As described here.
// overwrite the console object with the right one.
var optionsPage = ( chrome.extension.getViews()
&& (chrome.extension.getViews().length > 1) )
? chrome.extension.getViews()[1] : null;
// safety precaution.
if (optionsPage) {
var console = optionsPage.console;
}
I got this message when I tried to git clone
a repo that was not mine. The fix was to fork and then clone.
Here is my version of the same task::
import os, glob, shutil
def make_dir(path):
if not os.path.isdir(path):
os.mkdir(path)
def copy_dir(source_item, destination_item):
if os.path.isdir(source_item):
make_dir(destination_item)
sub_items = glob.glob(source_item + '/*')
for sub_item in sub_items:
copy_dir(sub_item, destination_item + '/' + sub_item.split('/')[-1])
else:
shutil.copy(source_item, destination_item)
Here's the code I use on a regular basis.
from bs4 import BeautifulSoup
import urllib.request
def processText(webpage):
# EMPTY LIST TO STORE PROCESSED TEXT
proc_text = []
try:
news_open = urllib.request.urlopen(webpage.group())
news_soup = BeautifulSoup(news_open, "lxml")
news_para = news_soup.find_all("p", text = True)
for item in news_para:
# SPLIT WORDS, JOIN WORDS TO REMOVE EXTRA SPACES
para_text = (' ').join((item.text).split())
# COMBINE LINES/PARAGRAPHS INTO A LIST
proc_text.append(para_text)
except urllib.error.HTTPError:
pass
return proc_text
I hope that helps.
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
Originally, Unicode was intended to have a fixed-width 16-bit encoding (UCS-2). Early adopters of Unicode, like Java and Windows NT, built their libraries around 16-bit strings.
Later, the scope of Unicode was expanded to include historical characters, which would require more than the 65,536 code points a 16-bit encoding would support. To allow the additional characters to be represented on platforms that had used UCS-2, the UTF-16 encoding was introduced. It uses "surrogate pairs" to represent characters in the supplementary planes.
Meanwhile, a lot of older software and network protocols were using 8-bit strings. UTF-8 was made so these systems could support Unicode without having to use wide characters. It's backwards-compatible with 7-bit ASCII.
You can find the exe easily by these ways, just try it yourself.
ll /proc/<PID>/exe
pwdx <PID>
lsof -p <PID> | grep cwd
As others have said, @Transient
is used to mark fields which shouldn't be persisted. Consider this short example:
public enum Gender { MALE, FEMALE, UNKNOWN }
@Entity
public Person {
private Gender g;
private long id;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public Gender getGender() { return g; }
public void setGender(Gender g) { this.g = g; }
@Transient
public boolean isMale() {
return Gender.MALE.equals(g);
}
@Transient
public boolean isFemale() {
return Gender.FEMALE.equals(g);
}
}
When this class is fed to the JPA, it persists the gender
and id
but doesn't try to persist the helper boolean methods - without @Transient
the underlying system would complain that the Entity class Person
is missing setMale()
and setFemale()
methods and thus wouldn't persist Person
at all.
You can try the hashdiff gem, which allows deep comparison of hashes and arrays in the hash.
The following is an example:
a = {a:{x:2, y:3, z:4}, b:{x:3, z:45}}
b = {a:{y:3}, b:{y:3, z:30}}
diff = HashDiff.diff(a, b)
diff.should == [['-', 'a.x', 2], ['-', 'a.z', 4], ['-', 'b.x', 3], ['~', 'b.z', 45, 30], ['+', 'b.y', 3]]
npm install <packagename> --registry http://registry.npmjs.org/
Try specifying the registry with the install command. Solved my problem.
It can also happen if you don't properly supply your list of parameters. Here's what I was doing:
java -jar [email protected] testing_subject file.txt test_send_emails.jar
Instead of the correct version:
java -jar test_send_emails.jar [email protected] testing_subject file.txt
You can use Apache commons-lang
StringUtils.isEmpty(String str)
- Checks if a String is empty ("") or null.
or
StringUtils.isBlank(String str)
- Checks if a String is whitespace, empty ("") or null.
the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API
When I want to see a snapshot of a table(s), and/or view (in a read-only way)
The blog post you quoted overstates its claim a bit. FP doesn't eliminate the need for design patterns. The term "design patterns" just isn't widely used to describe the same thing in FP languages. But they exist. Functional languages have plenty of best practice rules of the form "when you encounter problem X, use code that looks like Y", which is basically what a design pattern is.
However, it's correct that most OOP-specific design patterns are pretty much irrelevant in functional languages.
I don't think it should be particularly controversial to say that design patterns in general only exist to patch up shortcomings in the language. And if another language can solve the same problem trivially, that other language won't have need of a design pattern for it. Users of that language may not even be aware that the problem exists, because, well, it's not a problem in that language.
Here is what the Gang of Four has to say about this issue:
The choice of programming language is important because it influences one's point of view. Our patterns assume Smalltalk/C++-level language features, and that choice determines what can and cannot be implemented easily. If we assumed procedural languages, we might have included design patterns called "Inheritance", "Encapsulation," and "Polymorphism". Similarly, some of our patterns are supported directly by the less common object-oriented languages. CLOS has multi-methods, for example, which lessen the need for a pattern such as Visitor. In fact, there are enough differences between Smalltalk and C++ to mean that some patterns can be expressed more easily in one language than the other. (See Iterator for example.)
(The above is a quote from the Introduction to the Design Patterns book, page 4, paragraph 3)
The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.
What is the command pattern, if not an approximation of first-class functions? :) In an FP language, you'd simply pass a function as the argument to another function. In an OOP language, you have to wrap up the function in a class, which you can instantiate and then pass that object to the other function. The effect is the same, but in OOP it's called a design pattern, and it takes a whole lot more code. And what is the abstract factory pattern, if not currying? Pass parameters to a function a bit at a time, to configure what kind of value it spits out when you finally call it.
So yes, several GoF design patterns are rendered redundant in FP languages, because more powerful and easier to use alternatives exist.
But of course there are still design patterns which are not solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use.)
And it works both ways too. As I said, FP has its design patterns too; people just don't usually think of them as such.
But you may have run across monads. What are they, if not a design pattern for "dealing with global state"? That's a problem that's so simple in OOP languages that no equivalent design pattern exists there.
We don't need a design pattern for "increment a static variable", or "read from that socket", because it's just what you do.
Saying a monad is a design pattern is as absurd as saying the Integers with their usual operations and zero element is a design pattern. No, a monad is a mathematical pattern, not a design pattern.
In (pure) functional languages, side effects and mutable state are impossible, unless you work around it with the monad "design pattern", or any of the other methods for allowing the same thing.
Additionally, in functional languages which support OOP (such as F# and OCaml), it seems obvious to me that programmers using these languages would use the same design patterns found available to every other OOP language. In fact, right now I use F# and OCaml everyday, and there are no striking differences between the patterns I use in these languages vs the patterns I use when I write in Java.
Perhaps because you're still thinking imperatively? A lot of people, after dealing with imperative languages all their lives, have a hard time giving up on that habit when they try a functional language. (I've seen some pretty funny attempts at F#, where literally every function was just a string of 'let' statements, basically as if you'd taken a C program, and replaced all semicolons with 'let'. :))
But another possibility might be that you just haven't realized that you're solving problems trivially which would require design patterns in an OOP language.
When you use currying, or pass a function as an argument to another, stop and think about how you'd do that in an OOP language.
Is there any truth to the claim that functional programming eliminates the need for OOP design patterns?
Yep. :) When you work in a FP language, you no longer need the OOP-specific design patterns. But you still need some general design patterns, like MVC or other non-OOP specific stuff, and you need a couple of new FP-specific "design patterns" instead. All languages have their shortcomings, and design patterns are usually how we work around them.
Anyway, you may find it interesting to try your hand at "cleaner" FP languages, like ML (my personal favorite, at least for learning purposes), or Haskell, where you don't have the OOP crutch to fall back on when you're faced with something new.
As expected, a few people objected to my definition of design patterns as "patching up shortcomings in a language", so here's my justification:
As already said, most design patterns are specific to one programming paradigm, or sometimes even one specific language. Often, they solve problems that only exist in that paradigm (see monads for FP, or abstract factories for OOP).
Why doesn't the abstract factory pattern exist in FP? Because the problem it tries to solve does not exist there.
So, if a problem exists in OOP languages, which does not exist in FP languages, then clearly that is a shortcoming of OOP languages. The problem can be solved, but your language does not do so, but requires a bunch of boilerplate code from you to work around it. Ideally, we'd like our programming language to magically make all problems go away. Any problem that is still there is in principle a shortcoming of the language. ;)
Here is a cookbook answer to supplement @Chris' answer, CPython has moved to GitHub and the Mercurial repository will no longer be updated:
git clone https://github.com/python/cpython.git
Code will checkout to a subdirectory called cpython
-> cd cpython
print()
...egrep --color=always -R 'print' | less -R
Python/bltinmodule.c
-> builtin_print()
Enjoy.
Early FORTRAN where whitespace was not significant. (The anti-Python!)
DO 20 I = 1, 10
Meaning: loop from here to line 20 varying I from 1 to 10.
DO 20 I = 1. 10
Meaning: Assign 1.10 to the variable named DO20I.
Rumors are that this bug crashed a space probe.
In my case the "settings.xml" solution didn't work so I use this command in order to download all the sources:
mvn dependency:sources
You also can use it with other maven commands, for example:
mvn clean install dependency:sources -Dmaven.test.skip=true
To download all documentation, use the following command:
mvn dependency:resolve -Dclassifier=javadoc
Any of the below three options works for you:
echo[
echo(
echo.
For example:
@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo(
echo The above line is also blank.
echo.
echo The above line is also blank.
Drop the hash - that's for identifying the id attribute.
If you know the values at compile time you can do :
float[] values = {0.1f, 0.2f, 0.3f};
There is no way to do that if values are variables in runtime.
import React from 'react'
import SvgUri from 'react-native-svg-uri';
export default function Splash() {
return (
<View style={styles.container}>
{/* provided the svg file is stored locally */}
<SvgUri
width="400"
height="200"
source={require('./logo.svg')}
/>
{/* if the svg is online */}
<SvgUri
width="200"
height="200"
source={{ uri: 'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg' }}
/>
<Text style={styles.logoText}>
Text
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
logoText: {
fontSize: 50
}
});
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
Add .done() to your function
var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
$.ajax({
url: 'api.php',
data: 'id1='+q+'',
dataType: 'json',
async:false,
success: function(data)
{
id = data[0];
vname = data[1];
}
}).done(function(){
printWithAjax();
});
}//end of the for statement
}//end of ajax call function
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
This will give you names and table count of all the databases in you mysql
SELECT TABLE_SCHEMA,COUNT(*) FROM information_schema.tables group by TABLE_SCHEMA;
Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:
obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.FlattenHierarchy)
viewStyle : {
backgroundColor: '#F8F8F8',
justifyContent: 'center',
alignItems: 'center',
height: 60,
paddingTop: 15,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
marginBottom: 10,
elevation: 2,
position: 'relative'
},
Use marginBottom: 10
class Node:
rChild,lChild,parent,data = None,None,None,0
def __init__(self,key):
self.rChild = None
self.lChild = None
self.parent = None
self.data = key
class Tree:
root,size = None,0
def __init__(self):
self.root = None
self.size = 0
def insert(self,someNumber):
self.size = self.size+1
if self.root is None:
self.root = Node(someNumber)
else:
self.insertWithNode(self.root, someNumber)
def insertWithNode(self,node,someNumber):
if node.lChild is None and node.rChild is None:#external node
if someNumber > node.data:
newNode = Node(someNumber)
node.rChild = newNode
newNode.parent = node
else:
newNode = Node(someNumber)
node.lChild = newNode
newNode.parent = node
else: #not external
if someNumber > node.data:
if node.rChild is not None:
self.insertWithNode(node.rChild, someNumber)
else: #if empty node
newNode = Node(someNumber)
node.rChild = newNode
newNode.parent = node
else:
if node.lChild is not None:
self.insertWithNode(node.lChild, someNumber)
else:
newNode = Node(someNumber)
node.lChild = newNode
newNode.parent = node
def printTree(self,someNode):
if someNode is None:
pass
else:
self.printTree(someNode.lChild)
print someNode.data
self.printTree(someNode.rChild)
def main():
t = Tree()
t.insert(5)
t.insert(3)
t.insert(7)
t.insert(4)
t.insert(2)
t.insert(1)
t.insert(6)
t.printTree(t.root)
if __name__ == '__main__':
main()
My solution.
If you need a function that behaves as a nop, try
nop = lambda *a, **k: None
nop()
Sometimes I do stuff like this when I'm making dependencies optional:
try:
import foo
bar=foo.bar
baz=foo.baz
except:
bar=nop
baz=nop
# Doesn't break when foo is missing:
bar()
baz()
When NeXT were defining the NextStep API (as opposed to the NEXTSTEP operating system), they used the prefix NX, as in NXConstantString. When they were writing the OpenStep specification with Sun (not to be confused with the OPENSTEP operating system) they used the NS prefix, as in NSObject.
scrollHeight
is a property of a DOM object, not a function:
Height of the scroll view of an element; it includes the element padding but not its margin.
Given this:
<div id="x" style="height: 100px; overflow: hidden;">
<div style="height: 200px;">
pancakes
</div>
</div>
This yields 200:
$('#x')[0].scrollHeight
For example: http://jsfiddle.net/ambiguous/u69kQ/2/ (run with the JavaScript console open).
I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).
We send email via the Gmail SMTP servers, and we get this exact error from PHPMailer sometimes when we hit our Gmail send limits.
You can check if it's the same thing happening to you by going into Gmail and trying to manually send an email. In our case that displays the more helpful error message about sending limits.
In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.
Update to angular 4.X.X, there is a new way to mark an option selected:
<select [compareWith]="byId" [(ngModel)]="selectedItem">
<option *ngFor="let item of items" [ngValue]="item">{{item.name}}
</option>
</select>
byId(item1: ItemModel, item2: ItemModel) {
return item1.id === item2.id;
}
Some tutorial here
bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example).
For the detailed rules for the SUN JVM check my old blog
Regards, Markus
If you are happy to use JavaScript then you can use Modernizr in your page. When the page loads, a non-touch screen browser will have the class '.no-touch' added to the html tag, but for a touch screen browser, the html tag will have the class '.touch' added to the html tag.
Then it is simply a case of checking to see if the html tag has the no-touch class before deciding to add your mouseenter and mouseleave listeners.
if($('html').hasClass('no-touch')){
$('.box').on("mouseenter", function(event){
$(this).css('background-color','#0000ff')
});
$('.box').on("mouseleave", function(event){
$(this).css('background-color','')
});
}
For a touchscreen device the events will have no listeners so you will get no hover effect when you tap.
I got this same error while installing mitmproxy
using pip3
. The below command fixed this:
pip3 install --upgrade setuptools
I successfully followed this answer, but since entitlements have changed, I simply removed the --entitlements "Payload/Application.app/Entitlements.plist"
part of the second to last statement, and it worked like a charm.
Depending on your use case, all the above solutions apply. This is how i usually do it however :
For server side code (e.g. a batch process) I usually load the entities and work with dynamic proxies. Usually in batch processes you need to load the data anyways at the time the service runs. I try to batch load the data instead of using the find method to save some time. Depending on the process I use optimistic or pessimistic concurrency control (I always use optimistic except for parallel execution scenarios where I need to lock some records with plain sql statements, this is rare though). Depending on the code and scenario the impact can be reduced to almost zero.
For client side scenarios, you have a few options
Use view models. The models should have a property UpdateStatus(unmodified-inserted-updated-deleted). It is the responsibility of the client to set the correct value to this column depending on the user actions (insert-update-delete). The server can either query the db for the original values or the client should send the original values to the server along with the changed rows. The server should attach the original values and use the UpdateStatus column for each row to decide how to handle the new values. In this scenario I always use optimistic concurrency. This will only do the insert - update - delete statements and not any selects, but it might need some clever code to walk the graph and update the entities (depends on your scenario - application). A mapper can help but does not handle the CRUD logic
Use a library like breeze.js that hides most of this complexity (as described in 1) and try to fit it to your use case.
Hope it helps
I had the same problem on my Eclipse Juno. These steps solved the problem :
Project -> Properties -> C/C++ General -> Path and Symbols -> Tab [Symbols]
. You can use Apache Commons Math:
Precision.round(double x, int scale)
I noted that, when executing joins, MSSQL
will throw "Invalid Column Name" if the table you are joining on is not next to the table you are joining to. I tried specifying table1.row1
and table3.row3
, but was still getting the error; it did not go away until I reordered the tables in the query. Apparently, the order of the tables in the statement matters.
+-------------+ +-------------+ +-------------+
| table1 | | table2 | | table3 |
+-------------+ +-------------+ +-------------+
| row1 | col1 | | row2 | col2 | | row3 | col3 |
+------+------+ +------+------+ +------+------+
| ... | ... | | ... | ... | | ... | ... |
+------+------+ +------+------+ +------+------+
SELECT * FROM table1, table2 LEFT JOIN table3 ON row1 = row3; --throws an error
SELECT * FROM table2, table1 LEFT JOIN table3 ON row1 = row3; --works as expected
In notepad++
Search
(<option value="\w\w">)\w+">(.+)
Replace with
\1\2
This article is rather long. If you want to know about both aggregates and PODs (Plain Old Data) take time and read it. If you are interested just in aggregates, read only the first part. If you are interested only in PODs then you must first read the definition, implications, and examples of aggregates and then you may jump to PODs but I would still recommend reading the first part in its entirety. The notion of aggregates is essential for defining PODs. If you find any errors (even minor, including grammar, stylistics, formatting, syntax, etc.) please leave a comment, I'll edit.
This answer applies to C++03. For other C++ standards see:
Formal definition from the C++ standard (C++03 8.5.1 §1):
An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).
So, OK, let's parse this definition. First of all, any array is an aggregate. A class can also be an aggregate if… wait! nothing is said about structs or unions, can't they be aggregates? Yes, they can. In C++, the term class
refers to all classes, structs, and unions. So, a class (or struct, or union) is an aggregate if and only if it satisfies the criteria from the above definitions. What do these criteria imply?
This does not mean an aggregate class cannot have constructors, in fact it can have a default constructor and/or a copy constructor as long as they are implicitly declared by the compiler, and not explicitly by the user
No private or protected non-static data members. You can have as many private and protected member functions (but not constructors) as well as as many private or protected static data members and member functions as you like and not violate the rules for aggregate classes
An aggregate class can have a user-declared/user-defined copy-assignment operator and/or destructor
An array is an aggregate even if it is an array of non-aggregate class type.
Now let's look at some examples:
class NotAggregate1
{
virtual void f() {} //remember? no virtual functions
};
class NotAggregate2
{
int x; //x is private by default and non-static
};
class NotAggregate3
{
public:
NotAggregate3(int) {} //oops, user-defined constructor
};
class Aggregate1
{
public:
NotAggregate1 member1; //ok, public member
Aggregate1& operator=(Aggregate1 const & rhs) {/* */} //ok, copy-assignment
private:
void f() {} // ok, just a private function
};
You get the idea. Now let's see how aggregates are special. They, unlike non-aggregate classes, can be initialized with curly braces {}
. This initialization syntax is commonly known for arrays, and we just learnt that these are aggregates. So, let's start with them.
Type array_name[n] = {a1, a2, …, am};
if(m == n)
the ith element of the array is initialized with ai
else if(m < n)
the first m elements of the array are initialized with a1, a2, …, am and the other n - m
elements are, if possible, value-initialized (see below for the explanation of the term)
else if(m > n)
the compiler will issue an error
else (this is the case when n isn't specified at all like int a[] = {1, 2, 3};
)
the size of the array (n) is assumed to be equal to m, so int a[] = {1, 2, 3};
is equivalent to int a[3] = {1, 2, 3};
When an object of scalar type (bool
, int
, char
, double
, pointers, etc.) is value-initialized it means it is initialized with 0
for that type (false
for bool
, 0.0
for double
, etc.). When an object of class type with a user-declared default constructor is value-initialized its default constructor is called. If the default constructor is implicitly defined then all nonstatic members are recursively value-initialized. This definition is imprecise and a bit incorrect but it should give you the basic idea. A reference cannot be value-initialized. Value-initialization for a non-aggregate class can fail if, for example, the class has no appropriate default constructor.
Examples of array initialization:
class A
{
public:
A(int) {} //no default constructor
};
class B
{
public:
B() {} //default constructor available
};
int main()
{
A a1[3] = {A(2), A(1), A(14)}; //OK n == m
A a2[3] = {A(2)}; //ERROR A has no default constructor. Unable to value-initialize a2[1] and a2[2]
B b1[3] = {B()}; //OK b1[1] and b1[2] are value initialized, in this case with the default-ctor
int Array1[1000] = {0}; //All elements are initialized with 0;
int Array2[1000] = {1}; //Attention: only the first element is 1, the rest are 0;
bool Array3[1000] = {}; //the braces can be empty too. All elements initialized with false
int Array4[1000]; //no initializer. This is different from an empty {} initializer in that
//the elements in this case are not value-initialized, but have indeterminate values
//(unless, of course, Array4 is a global array)
int array[2] = {1, 2, 3, 4}; //ERROR, too many initializers
}
Now let's see how aggregate classes can be initialized with braces. Pretty much the same way. Instead of the array elements we will initialize the non-static data members in the order of their appearance in the class definition (they are all public by definition). If there are fewer initializers than members, the rest are value-initialized. If it is impossible to value-initialize one of the members which were not explicitly initialized, we get a compile-time error. If there are more initializers than necessary, we get a compile-time error as well.
struct X
{
int i1;
int i2;
};
struct Y
{
char c;
X x;
int i[2];
float f;
protected:
static double d;
private:
void g(){}
};
Y y = {'a', {10, 20}, {20, 30}};
In the above example y.c
is initialized with 'a'
, y.x.i1
with 10
, y.x.i2
with 20
, y.i[0]
with 20
, y.i[1]
with 30
and y.f
is value-initialized, that is, initialized with 0.0
. The protected static member d
is not initialized at all, because it is static
.
Aggregate unions are different in that you may initialize only their first member with braces. I think that if you are advanced enough in C++ to even consider using unions (their use may be very dangerous and must be thought of carefully), you could look up the rules for unions in the standard yourself :).
Now that we know what's special about aggregates, let's try to understand the restrictions on classes; that is, why they are there. We should understand that memberwise initialization with braces implies that the class is nothing more than the sum of its members. If a user-defined constructor is present, it means that the user needs to do some extra work to initialize the members therefore brace initialization would be incorrect. If virtual functions are present, it means that the objects of this class have (on most implementations) a pointer to the so-called vtable of the class, which is set in the constructor, so brace-initialization would be insufficient. You could figure out the rest of the restrictions in a similar manner as an exercise :).
So enough about the aggregates. Now we can define a stricter set of types, to wit, PODs
Formal definition from the C++ standard (C++03 9 §4):
A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. Similarly, a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. A POD class is a class that is either a POD-struct or a POD-union.
Wow, this one's tougher to parse, isn't it? :) Let's leave unions out (on the same grounds as above) and rephrase in a bit clearer way:
An aggregate class is called a POD if it has no user-defined copy-assignment operator and destructor and none of its nonstatic members is a non-POD class, array of non-POD, or a reference.
What does this definition imply? (Did I mention POD stands for Plain Old Data?)
Examples:
struct POD
{
int x;
char y;
void f() {} //no harm if there's a function
static std::vector<char> v; //static members do not matter
};
struct AggregateButNotPOD1
{
int x;
~AggregateButNotPOD1() {} //user-defined destructor
};
struct AggregateButNotPOD2
{
AggregateButNotPOD1 arrOfNonPod[3]; //array of non-POD class
};
POD-classes, POD-unions, scalar types, and arrays of such types are collectively called POD-types.
PODs are special in many ways. I'll provide just some examples.
POD-classes are the closest to C structs. Unlike them, PODs can have member functions and arbitrary static members, but neither of these two change the memory layout of the object. So if you want to write a more or less portable dynamic library that can be used from C and even .NET, you should try to make all your exported functions take and return only parameters of POD-types.
The lifetime of objects of non-POD class type begins when the constructor has finished and ends when the destructor has finished. For POD classes, the lifetime begins when storage for the object is occupied and finishes when that storage is released or reused.
For objects of POD types it is guaranteed by the standard that when you memcpy
the contents of your object into an array of char or unsigned char, and then memcpy
the contents back into your object, the object will hold its original value. Do note that there is no such guarantee for objects of non-POD types. Also, you can safely copy POD objects with memcpy
. The following example assumes T is a POD-type:
#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
memcpy(buf, &obj, N); // between these two calls to memcpy,
// obj might be modified
memcpy(&obj, buf, N); // at this point, each subobject of obj of scalar type
// holds its original value
goto statement. As you may know, it is illegal (the compiler should issue an error) to make a jump via goto from a point where some variable was not yet in scope to a point where it is already in scope. This restriction applies only if the variable is of non-POD type. In the following example f()
is ill-formed whereas g()
is well-formed. Note that Microsoft's compiler is too liberal with this rule—it just issues a warning in both cases.
int f()
{
struct NonPOD {NonPOD() {}};
goto label;
NonPOD x;
label:
return 0;
}
int g()
{
struct POD {int i; char c;};
goto label;
POD x;
label:
return 0;
}
It is guaranteed that there will be no padding in the beginning of a POD object. In other words, if a POD-class A's first member is of type T, you can safely reinterpret_cast
from A*
to T*
and get the pointer to the first member and vice versa.
The list goes on and on…
It is important to understand what exactly a POD is because many language features, as you see, behave differently for them.
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
fieldlength
, which contains the number of components of the array.length
may be positive or zero.The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Resources:
If the build never occurred (perhaps you didn't get the Pull-Request build switch set to on in time), you can mark the Pull Request on Github as closed then mark it as opened and a new build will be triggered.
Simplified update query using JOIN-ing multiple tables.
UPDATE
first_table ft
JOIN second_table st ON st.some_id = ft.some_id
JOIN third_table tt ON tt.some_id = st.some_id
.....
SET
ft.some_column = some_value
WHERE ft.some_column = 123456 AND st.some_column = 123456
Note - first_table, second_table, third_table and some_column like 123456 are demo table names, column names and ids. Replace them with the valid names.
You might need to convert the decimal
to money
(or decimal(8,2)
) to get that exact formatting. The convert
method can take a third parameter that controls the formatting style:
convert(varchar, cast(price as money)) 12345.67
convert(varchar, cast(price as money), 0) 12345.67
convert(varchar, cast(price as money), 1) 12,345.67
There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic"
. Variables in Python can hold values of any type, and you can't restrict that.
Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__
method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.
So for example:
class Thing(object):
def __init__(self, magic):
self.magic = magic
Easy. Now instances of this class have a magic
attribute:
thingo = Thing("More magic")
# thingo.magic is now "More magic"
Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:
class Thing(object):
magic = "Magic"
def __init__(self):
pass
Now try:
thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1
Or:
class Thing(object):
magic = ["More", "magic"]
def __init__(self):
pass
thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]
This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.
The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__
method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.
There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:
The download is 282MB vs 3GB for Xcode.
I think this question needs an updated answer, because both PostgreSQL and SQLDeveloper have been updated several times since it was originally asked.
I've got a PostgreSQL instance running in Azure, with SSLMODE=Require. While I've been using DBeaverCE to access that instance and generate an ER Diagram, I've gotten really familiar with SQLDeveloper, which is now at v19.4.
The instructions about downloading the latest PostgreSQL JDBC driver and where to place it are correct. What has changed, though, is where to configure your DB access.
You'll find a file $HOME/.sqldeveloper/system19.4.0.354.1759/o.jdeveloper.db.connection.19.3.0.354.1759/connections.json
:
{
"connections": [
{
"name": "connection-name-goes-here",
"type": "jdbc",
"info": {
"customUrl": "jdbc:postgresql://your-postgresql-host:5432/DBNAME?sslmode=require",
"hostname": "your-postgresql-host",
"driver": "org.postgresql.Driver",
"subtype": "SDPostgreSQL",
"port": "5432",
"SavePassword": "false",
"RaptorConnectionType": "SDPostgreSQL",
"user": "your_admin_user",
"sslmode": "require"
}
}
]
}
You can use this connection with both Data Modeller and the admin functionality of SQLDeveloper. Specifying all the port, dbname and sslmode in the customUrl are required because SQLDeveloper isn't including the sslmode in what it sends via JDBC, so you have to construct it by hand.
Don't know others issue, Only this code worked for me.
$('select').val('').select2();
As khaos said, a destination unreachable could also mean that something is blocking the way from or to your destination. For example an ACL that filters bad IP addresses.
Modified version of divround :-)
def divround(value, step, barrage):
result, rest = divmod(value, step)
return result*step if rest < barrage else (result+1)*step
I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.
Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.
Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:
$('iframe_dl').src="/app?download=1&filename=" + the_filename
Server slurps the file, unlinks it, and sends the stream to the client, with these headers:
Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'
Works like a charm.
Try:
#!/bin/bash
# .... some previous code ...
# help set exec | less
set -- 1 2 3 4 5 # fake command line arguments
exec bash --login -c '
echo $0
echo $@
echo my script continues here
' arg0 "$@"
Supposing div is #div and button is #button:
#div {
display: table-cell;
width: 100%;
height: 100%;
text-align: center;
vertical-align: center;
}
#button {}
Then nest the button into div as usual.
Another example in Kotlin:
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil
.inflate< MartianDataBinding >(
inflater,
R.layout.bla,
container,
false
)
binding.modelName = // ..
return binding.root
}
Note that the name "MartianDataBinding" depends on the name of the layout file. If the file is named "martian_data" then the correct name would be MartianDataBinding.
A HANDLE
is a context-specific unique identifier. By context-specific, I mean that a handle obtained from one context cannot necessarily be used in any other aribtrary context that also works on HANDLE
s.
For example, GetModuleHandle
returns a unique identifier to a currently loaded module. The returned handle can be used in other functions that accept module handles. It cannot be given to functions that require other types of handles. For example, you couldn't give a handle returned from GetModuleHandle
to HeapDestroy
and expect it to do something sensible.
The HANDLE
itself is just an integral type. Usually, but not necessarily, it is a pointer to some underlying type or memory location. For example, the HANDLE
returned by GetModuleHandle
is actually a pointer to the base virtual memory address of the module. But there is no rule stating that handles must be pointers. A handle could also just be a simple integer (which could possibly be used by some Win32 API as an index into an array).
HANDLE
s are intentionally opaque representations that provide encapsulation and abstraction from internal Win32 resources. This way, the Win32 APIs could potentially change the underlying type behind a HANDLE, without it impacting user code in any way (at least that's the idea).
Consider these three different internal implementations of a Win32 API that I just made up, and assume that Widget
is a struct
.
Widget * GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return w;
}
void * GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return reinterpret_cast<void *>(w);
}
typedef void * HANDLE;
HANDLE GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return reinterpret_cast<HANDLE>(w);
}
The first example exposes the internal details about the API: it allows the user code to know that GetWidget
returns a pointer to a struct Widget
. This has a couple of consequences:
Widget
structWidget
struct Both of these consequences may be undesirable.
The second example hides this internal detail from the user code, by returning just void *
. The user code doesn't need access to the header that defines the Widget
struct.
The third example is exactly the same as the second, but we just call the void *
a HANDLE
instead. Perhaps this discourages user code from trying to figure out exactly what the void *
points to.
Why go through this trouble? Consider this fourth example of a newer version of this same API:
typedef void * HANDLE;
HANDLE GetWidget (std::string name)
{
NewImprovedWidget *w;
w = findImprovedWidget(name);
return reinterpret_cast<HANDLE>(w);
}
Notice that the function's interface is identical to the third example above. This means that user code can continue to use this new version of the API, without any changes, even though the "behind the scenes" implementation has changed to use the NewImprovedWidget
struct instead.
The handles in these example are really just a new, presumably friendlier, name for void *
, which is exactly what a HANDLE
is in the Win32 API (look it up at MSDN). It provides an opaque wall between the user code and the Win32 library's internal representations that increases portability, between versions of Windows, of code that uses the Win32 API.
for 32 characters:
for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)
string k = "This is my\r\nugly string. I want\r\nto change this. Please \r\n help!";
k = System.Text.RegularExpressions.Regex.Replace(k, @"\r\n+", " ");
67
Reserved.objects.filter(client=client_id).order_by('-check_in')
'-' is indicates Descending order and for Ascending order just give class attribute
In React + Chrome, it's better to import the video than give it as src to .
import React from 'react';
import styled from 'styled-components';
import video from './videos.mp4';
const StyledVideo = styled.video`
width: 100%;
height: 100vh;
object-fit: cover;
`
const BackgroundVideo = () => {
return (
<StyledVideo autoPlay loop muted>
<source src={video} type="video/mp4" />
</StyledVideo>
);
}
Remember
It sounds like you are on the right track with your directory structure. When you compile the dependent code, specify the -classpath
argument of javac
. Use the parent directory of the com
directory, where com
, in turn, contains company/thing/YourClass.class
So, when you do this:
javac -classpath <parent> client.java
The <parent>
should be referring to the parent of com
. If you are in com
, it would be ../
.
"Helvetica Neue Condensed Bold" get working with firefox:
.class {
font-family: "Helvetica Neue";
font-weight: bold;
font-stretch: condensed;
}
But it's fail with Opera.
The keyboard seems to pop up when the EditText gains focus. To prevent this, set focusable to false:
<EditText
...
android:focusable="false"
... />
This behavior can vary on different manufacturers' Android OS flavors, but on the devices I've tested I have found this to to be sufficient. If the keyboard still pops up, using hints instead of text seems to help as well:
myEditText.setText("My text"); // instead of this...
myEditText.setHint("My text"); // try this
Once you've done this, your on click listener should work as desired:
myEditText.setOnClickListener(new OnClickListener() {...});
If you just wanted to change the example and put the table at the top, then loc='top'
in the table declaration is what you need,
the_table = ax.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='top')
Then adjusting the plot with,
plt.subplots_adjust(left=0.2, top=0.8)
A more flexible option is to put the table in its own axis using subplots,
import numpy as np
import matplotlib.pyplot as plt
fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')
axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()
which looks like this,
You are then free to adjust the locations of the axis as required.
Try this -
select * from table where id in (3,4) or [name] in ('andy','paul');
A very simple way to do it is:
list1=['']
j=0
for i in com_list:
if j==0:
list1[0]=(i['value'])
else:
list1.append(i['value'])
j+=1
Output:
['apple', 'banana', 'cars']
I personally use the humanize
library for this:
>>> import datetime
>>> humanize.naturalday(datetime.datetime.now())
'today'
>>> humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1))
'yesterday'
>>> humanize.naturalday(datetime.date(2007, 6, 5))
'Jun 05'
>>> humanize.naturaldate(datetime.date(2007, 6, 5))
'Jun 05 2007'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))
'a second ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))
'an hour ago'
Of course, it doesn't give you exactly the answer you were looking for (which is, indeed, str(timeA - timeB)
, but I have found that once you go beyond a few hours, the display becomes quickly unreadable. humanize
has support for much larger values that are human-readable, and is also well localized.
It's inspired by Django's contrib.humanize
module, apparently, so since you are using Django, you should probably use that.
iPhone
KeyboardSizes:
2.6S,6,7,8:(375 × 667) : keyboardSize = (0.0, 407.0, 375.0, 260.
3.6+,6S+, 7+ , 8+ : (414 × 736) keyboardSize = (0.0, 465.0, 414.0, 271.0)
4.XS, X :(375 X 812) keyboardSize = (0.0, 477.0, 375.0, 335.0)
5.XR,XSMAX((414 x 896) keyboardSize = (0.0, 550.0, 414.0, 346.0)
You can roll back a migration the way it is in the guide:
http://guides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations
Generate a migration:
rails generate migration revert_create_tablename
Write the migration:
require_relative '20121212123456_create_tablename'
class RevertCreateTablename < ActiveRecord::Migration[5.0]
def change
revert CreateTablename
end
end
This way you can also rollback and can use to revert any migration
$ git push origin local_branch:remote_branch
I had the same error & spent hours trying to figure it out. Finally I found it.
What I didn't know is that pushing like this git push origin branch-x
will try to search for branch-x locally then push to remote branch-x.
In my case, I had two remote urls. I did a checkout from branch-x to branch-y when trying to push from y locally to x remote I had the message everything is up to date which is normal cause I was pushing to x of the second remote.
Long story short to not fall in this kind of trap you need to specify the source ref and the target ref:
$ git push origin local_branch:remote_branch
If you have to run this command every time you push your branch, you maybe need to set the upstream between your local & remote branch with the following :
$ git push --set-upstream origin local_branch:remote_branch
Or
$ git push -u origin local_branch:remote_branch
I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.
In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour
will have to be the end
, and once that happens the shortest path is found and program can return.
I would modify the the method as follow, pay close attention to the for loop
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
#No need to visit other neighbour. Return at once
if current_neighbour == end
return new_path;
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.
Math.ceil()
is the correct function to call. I'm guessing a
is an int
, which would make a / 100
perform integer arithmetic. Try Math.ceil(a / 100.0)
instead.
int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));
Outputs:
1
1.0
1.42
2.0
2
You could either delete your current branch and do:
git branch --track local_branch remote_branch
Or change change remote server to the current one in the config
As many already stated here you need to make the class static
.
Just small addition - if you want, there is a bit different way without static one.
Consider this. Implementing a builder by declaring something like withProperty(value)
type setters inside the class and make them return a reference to itself. In this approach, you have a single and an elegant class which is a thread safe and concise.
Consider this:
public class DataObject {
private String first;
private String second;
private String third;
public String getFirst(){
return first;
}
public void setFirst(String first){
this.first = first;
}
...
public DataObject withFirst(String first){
this.first = first;
return this;
}
public DataObject withSecond(String second){
this.second = second;
return this;
}
public DataObject withThird(String third){
this.third = third;
return this;
}
}
DataObject dataObject = new DataObject()
.withFirst("first data")
.withSecond("second data")
.withThird("third data");
Check it out for more Java Builder examples.
A simpler version of one of the above answers. Column A is the key.
Yes, it needs a helper column. That's column K.
1) Set first cell in table to TRUE (K8)
2) On second row at K9, and to end of table (K99), paste: =IF(A8=A9,K8,NOT(K8))
This gives a pattern of TRUE...TRUE, FALSE...FALSE,...
3) Select key column A1:A99, or whole table A1:K99
4) Set Home/Conditional/New Rule/Formula =K8
5) Format as you wish for the TRUE cells
6) Select the range from (3) and Right-click Format White (or whatever
background color you want) for the FALSE cells
Note that this solution (and the others) have a major flaw, in that this
highlighting doesn't work properly when you have filters active in your
table. I want that fix :)
If you only need the dictionary keys 1
, 2
, and 3
use: your_dict.keys()
.
If you only need the dictionary values -0.3246
, -0.9185
, and -3985
use: your_dict.values()
.
If you want both keys and values use: your_dict.items()
which returns a list of tuples [(key1, value1), (key2, value2), ...]
.
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
You may use Oracle pipelined functions
Basically, when you would like a PLSQL (or java or c) routine to be the «source» of data -- instead of a table -- you would use a pipelined function.
Simple Example - Generating Some Random Data
How could you create N unique random numbers depending on the input argument?
create type array
as table of number;
create function gen_numbers(n in number default null)
return array
PIPELINED
as
begin
for i in 1 .. nvl(n,999999999)
loop
pipe row(i);
end loop;
return;
end;
Suppose we needed three rows for something. We can now do that in one of two ways:
select * from TABLE(gen_numbers(3));
COLUMN_VALUE
1
2
3
or
select * from TABLE(gen_numbers)
where rownum <= 3;
COLUMN_VALUE
1
2
3
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
Another solution is:
>>> "".join(list(hex(255))[2:])
'ff'
Probably an archaic answer, but functional.
I know it's a YEARS old topic, but I got frustrated and built a role for myself to do exactly this for an arbitrary list of files. Extend as you see fit:
main.yml
- name: created destination directory
file:
path: /path/to/directory
state: directory
mode: '0750'
- include_tasks: move.yml
loop:
- file1
- file2
- file3
move.yml
- name: stat the file
stat:
path: {{ item }}
register: my_file
- name: hard link the file into directory
file:
src: /original/path/to/{{ item }}
dest: /path/to/directory/{{ item }}
state: hard
when: my_file.stat.exists
- name: Delete the original file
file:
path: /original/path/to/{{ item }}
state: absent
when: my_file.stat.exists
Note that hard linking is preferable to copying here, because it inherently preserves ownership and permissions (in addition to not consuming more disk space for a second copy of the file).
When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)
$.ajax({
type: "POST",
url: url,
data: '{"name" :"sheo"}',
contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).done(function (Response) {
//do something when get response })
.fail(function (Response) {
//do something when any error occurs.
});
Its because the gradle is not synced because of many reasons.
Go to project folder and remove .gradle folder and start sync. It will work
Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.
Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater
.
The code is the following, where this
is an Activity:
final LayoutInflater factory = getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);
landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);
You need to get the inflater for this
context, access the root view through the inflate method and finally call findViewById
on the root view of the layout.
Hope this is useful for someone! Bye
An alternative to using (!!)
is to use the
lens package and its element
function and associated operators. The
lens provides a uniform interface for accessing a wide variety of structures and nested structures above and beyond lists. Below I will focus on providing examples and will gloss over both the type signatures and the theory behind the
lens package. If you want to know more about the theory a good place to start is the readme file at the github repo.
At the command line:
$ cabal install lens
$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
> import Control.Lens
To access a list with the infix operator
> [1,2,3,4,5] ^? element 2 -- 0 based indexing
Just 3
Unlike the (!!)
this will not throw an exception when accessing an element out of bounds and will return Nothing
instead. It is often recommend to avoid partial functions like (!!)
or head
since they have more corner cases and are more likely to cause a run time error. You can read a little more about why to avoid partial functions at this wiki page.
> [1,2,3] !! 9
*** Exception: Prelude.(!!): index too large
> [1,2,3] ^? element 9
Nothing
You can force the lens technique to be a partial function and throw an exception when out of bounds by using the (^?!)
operator instead of the (^?)
operator.
> [1,2,3] ^?! element 1
2
> [1,2,3] ^?! element 9
*** Exception: (^?!): empty Fold
This is not just limited to lists however. For example the same technique works on trees from the standard containers package.
> import Data.Tree
> :{
let
tree = Node 1 [
Node 2 [Node 4[], Node 5 []]
, Node 3 [Node 6 [], Node 7 []]
]
:}
> putStrLn . drawTree . fmap show $tree
1
|
+- 2
| |
| +- 4
| |
| `- 5
|
`- 3
|
+- 6
|
`- 7
We can now access the elements of the tree in depth-first order:
> tree ^? element 0
Just 1
> tree ^? element 1
Just 2
> tree ^? element 2
Just 4
> tree ^? element 3
Just 5
> tree ^? element 4
Just 3
> tree ^? element 5
Just 6
> tree ^? element 6
Just 7
We can also access sequences from the containers package:
> import qualified Data.Sequence as Seq
> Seq.fromList [1,2,3,4] ^? element 3
Just 4
We can access the standard int indexed arrays from the vector package, text from the standard text package, bytestrings fro the standard bytestring package, and many other standard data structures. This standard method of access can be extended to your personal data structures by making them an instance of the typeclass Taversable, see a longer list of example Traversables in the Lens documentation..
Digging down into nested structures is simple with the lens hackage. For example accessing an element in a list of lists:
> [[1,2,3],[4,5,6]] ^? element 0 . element 1
Just 2
> [[1,2,3],[4,5,6]] ^? element 1 . element 2
Just 6
This composition works even when the nested data structures are of different types. So for example if I had a list of trees:
> :{
let
tree = Node 1 [
Node 2 []
, Node 3 []
]
:}
> putStrLn . drawTree . fmap show $ tree
1
|
+- 2
|
`- 3
> :{
let
listOfTrees = [ tree
, fmap (*2) tree -- All tree elements times 2
, fmap (*3) tree -- All tree elements times 3
]
:}
> listOfTrees ^? element 1 . element 0
Just 2
> listOfTrees ^? element 1 . element 1
Just 4
You can nest arbitrarily deeply with arbitrary types as long as they meet the Traversable
requirement. So accessing a list of trees of sequences of text is no sweat.
A common operation in many languages is to assign to an indexed position in an array. In python you might:
>>> a = [1,2,3,4,5]
>>> a[3] = 9
>>> a
[1, 2, 3, 9, 5]
The
lens package gives this functionality with the (.~)
operator. Though unlike in python the original list is not mutated, rather a new list is returned.
> let a = [1,2,3,4,5]
> a & element 3 .~ 9
[1,2,3,9,5]
> a
[1,2,3,4,5]
element 3 .~ 9
is just a function and the (&)
operator, part of the
lens package, is just reverse function application. Here it is with the more common function application.
> (element 3 .~ 9) [1,2,3,4,5]
[1,2,3,9,5]
Assignment again works perfectly fine with arbitrary nesting of Traversable
s.
> [[1,2,3],[4,5,6]] & element 0 . element 1 .~ 9
[[1,9,3],[4,5,6]]
jQuery has the contains method. Here's a snippet for you:
<script type="text/javascript">
$(function() {
var foundin = $('*:contains("I am a simple string")');
});
</script>
The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/
One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')
Unless you're trying to upload the file using ajax, just submit the form to /upload/image
.
<form enctype="multipart/form-data" action="/upload/image" method="post">
<input id="image-file" type="file" />
</form>
If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();
@Override
public void onBackPressed() {
}
You would have to call a Validator on the Entity if you want to validate it. Then you will get a set of ConstraintViolationException, which basically show for which field/s of your Entity there is a constraint violation and what exactly was it. Maybe you can also share some of the code you expect to validate your entity.
An often used technique is to do validation in @PrePersist and rollback transaction if using multiple data modifications during transaction or do other actions when you get a validation exception.
Your code should go like this:
@PrePersist
public void prePersist(SomeEntity someEntity){
Validator validator = Validation.buildDefaultValidatorFactory.getValidator();
Set<ConstraintViolation<SomeEntity>> = validator.validate(someEntity);
//do stuff with them, like notify client what was the wrong field, log them, or, if empty, be happy
}
Adding to @Patrick's answer, you can use the following to drop multiple columns
columns_to_drop = ['id', 'id_copy']
df = df.drop(*columns_to_drop)
You can specify the -t
option (--target
) to specify the destination directory. See pip install --help
for detailed information. This is the command you need:
pip install -t path_to_your_home package-name
for example, for installing say mxnet, in my $HOME
directory, I type:
pip install -t /home/foivos/ mxnet
if you want to change the text of "input",use:
`$("#inputId").val("what you want to put")`
and if you want to change the text in "label","span","div", you can use
`$("#containerId").text("what you want to put")`
Notifications appear to have changed again (October 2016).
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)
// Post notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)
Late to the game here, but I've mashed up two excellent responses from mantish and j-w. First, the modified regex:
const youtube_regex = /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/
Here's the test code (I've added mantish's original test cases to j-w's nastier ones):
var urls = [
'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
'http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
'http://www.youtube.com/watch?v=0zM3nApSvMg',
'http://youtu.be/0zM3nApSvMg',
'//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
'http://youtu.be/6dwqZw0j_jY',
'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
'http://youtu.be/afa-5HQHiAs',
'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
'http://www.youtube.com/watch?v=peFZbP64dsU',
'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
];
var failures = 0;
urls.forEach(url => {
const parsed = url.match(youtube_regex);
if (parsed && parsed[2]) {
console.log(parsed[2]);
} else {
failures++;
console.error(url, parsed);
}
});
if (failures) {
console.error(failures, 'failed');
}
Experimental version to handle the m.youtube urls mentioned in comments:
const youtube_regex = /^.*((m\.)?youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/
It requires parsed[2]
to be changed to parsed[3]
in two places in the tests (which it then passes with m.youtube
urls added to the tests). Let me know if you see problems.
I had to embed my $location.path()
statement like this because my digest was still running:
function routeMe(data) {
var waitForRender = function () {
if ($http.pendingRequests.length > 0) {
$timeout(waitForRender);
} else {
$location.path(data);
}
};
$timeout(waitForRender);
}
You will need to know if the REST API you are calling supports GET
or POST
, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET
and POST
methods, so the less sensitive info goes into the URL (GET)
, and the info like username and password is submitted as POST
variables. Also, everything goes over the HTTPS
connection.
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable
to make that json string availabe to the client.
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
This is how I connect to the API from the client side:
$processed = FALSE;
$ERROR_MESSAGE = '';
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass"); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);
if ($obj->{'code'} == '1')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{'data'};
}
...
if (!$processed && $ERROR_MESSAGE != '') {
echo $ERROR_MESSAGE;
}
BTW, I also tried to use file_get_contents()
method as some of the users here suggested, but that din't work well for me. I found out the curl
method to be faster and more reliable.
Happened to me with the directory utils
. I was trying to import this directory as:
from utils import somefile
utils
is already a package in python. Just change your directory name to something different and it should work just fine.
If all you want to do is display an iframe on a page, the simplest solution I was able to come up with doesn't require divs or flex stuff is:
html {
width: 100%;
height: 100%;
display: table;
}
body {
text-align: center;
vertical-align: middle;
display: table-cell;
}
And then the HTML is just:
<html>
<body>
<iframe ...></iframe>
</body>
</html>
If this is all you need you don't need wrapper divs to do it. This works for text content and stuff, too.
Also this looks even simpler.
in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver
instead of manage.py runserver
in my project directory.
just run these command
sudo apt-get install phpmyadmin php-mbstring php-gettext
sudo service apache2 restart
Or you can follow this post...
There is also the strncmp()
function and strncasecmp()
function which is perfect for this situation:
if (strncmp($string_n, "http", 4) === 0)
In general:
if (strncmp($string_n, $prefix, strlen($prefix)) === 0)
The advantage over the substr()
approach is that strncmp()
just does what needs to be done, without creating a temporary string.