If you have a "Win32 project" + defined a WinMain and your SubSystem linker setting is set to WINDOWS you can still get this linker error in case somebody set the "Additional Options" in the linker settings to "/SUBSYSTEM:CONSOLE" (looks like this additional setting is preferred over the actual SubSystem setting.
Another way you can get this linker error (as I was) is if you are exporting an instance of a class from a DLL file, but have not declared that class itself as import/export.
#ifdef MYDLL_EXPORTS
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT __declspec(dllimport)
#endif
class DLLEXPORT Book // <--- This class must also be declared as export/import
{
public:
Book();
~Book();
int WordCount();
};
DLLEXPORT extern Book book; // <-- This is what I really wanted, to export book object
So even though primarily I was exporting just an instance of the Book class called book
above, I had to declare the Book
class as export/import class as well otherwise calling book.WordCount()
in the other DLL file was causing a link error.
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
A one liner (doesnt work with hours):
function sectostr(time) {
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
}
Ok this is the solution I would have liked to find, instead here I write it:
First create the directory structure corresponding to the package defined for the .java file, if it is my.super.application create the directory "my" and inside it "super" and inside it the .java file "App.java"
then from command line:
javac -cp /path/to/lib1.jar:/path/to/lib2.jar path/to/my/super/App.java
Notice the above will include multiple libraries, if under windows use "," to separate multiple files otherwise under GNU/Linux use ":" To create a jar file
jar -cvfe App.jar App my/app/
the above will create the application with its corresponding Manifest indicating the App as the main class.
Including the required libraries inside the jar file is not possible using java or jar command line parameters.
You can instead:
<target name="-post-jar"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> <jar jarfile="${dist.jar}" update="true"> <zipfileset src="${dist.jar}" includes="**/*.class" /> <zipfileset src="${file.reference.iText-1.0.8.jar}" includes="**/*"/> <zipfileset src="${file.reference.itextpdf-3.2.1.jar}" includes="**/*"/> </jar> </target>
the file.reference names are found inside project.properties file after you added the libraries to the Netbeans IDE.
The typical solution is to define the shape and use it as background but as the number of digits varies it's no more a perfect circle, it looks like a rectangle with round edges or Oval. So I have developed this solution, it's working great. Hope it will help someone.
Here is the code of custom TextView
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
public class CircularTextView extends TextView
{
private float strokeWidth;
int strokeColor,solidColor;
public CircularTextView(Context context) {
super(context);
}
public CircularTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void draw(Canvas canvas) {
Paint circlePaint = new Paint();
circlePaint.setColor(solidColor);
circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
Paint strokePaint = new Paint();
strokePaint.setColor(strokeColor);
strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
int h = this.getHeight();
int w = this.getWidth();
int diameter = ((h > w) ? h : w);
int radius = diameter/2;
this.setHeight(diameter);
this.setWidth(diameter);
canvas.drawCircle(diameter / 2 , diameter / 2, radius, strokePaint);
canvas.drawCircle(diameter / 2, diameter / 2, radius-strokeWidth, circlePaint);
super.draw(canvas);
}
public void setStrokeWidth(int dp)
{
float scale = getContext().getResources().getDisplayMetrics().density;
strokeWidth = dp*scale;
}
public void setStrokeColor(String color)
{
strokeColor = Color.parseColor(color);
}
public void setSolidColor(String color)
{
solidColor = Color.parseColor(color);
}
}
Then in your XML, give some padding and make sure its gravity is center
<com.app.tot.customtextview.CircularTextView
android:id="@+id/circularTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11"
android:gravity="center"
android:padding="3dp"/>
And you can set the stroke width
circularTextView.setStrokeWidth(1);
circularTextView.setStrokeColor("#ffffff");
circularTextView.setSolidColor("#000000");
You need to install the Windows 10 SDK.
Visual Studio 2015 setup will start. Select "Modify".
In Visual Studio components list find "Universal Windows App Development Tools", open the list of sub-items and select "Windows 10 SDK (10.0.10240)".
Windows 10 SDK in VS 2015 Update 1 Setup
As josant already wrote - when the installation finishes you will find the SignTool.exe in the folders:
I had a similar problem. Based on Joshua's premise that excel was the problem I looked at it and found that the numbers were formatted with commas between every third digit. Reformatting without commas fixed the problem.
Is there some command to create this folder?
If smb face this issue again, you should know the most simple way to create .m2
folder.
If you unzipped maven and set up maven path variable - just try mvn clean
command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.
Of course, Insert
or AddFirst
will do the trick, but you could always do:
myList.Reverse();
myList.Add(item);
myList.Reverse();
Have you tried using double quotes?
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
Or just do:
int y = CGRectGetMaxY(((UIView*)[_scrollView.subviews lastObject]).frame); [_scrollView setContentSize:(CGSizeMake(CGRectGetWidth(_scrollView.frame), y))];
(This solution was added by me as a comment in this page. After getting 19 up-votes for this comment, I've decided to add this solution as a formal answer for the benefit of the community!)
OR
rm -rf `find /path/to/base/dir/* -type d -mtime +10`
Updated, faster version of it:
find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f
You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.
Prior to PHP 5.4:
$myArray = array();
PHP 5.4 and higher
$myArray = [];
If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.
If there are too few view-specific data and/or transformations, you can use the Model itself
D:\>javadoc *.java
If you want to create dock file of lang package then path should be same where your lang package is currently. For example, I created a folder name javaapi
and unzipped the src
zip file, then used the command below.
C:\Users\Techsupport1\Desktop\javaapi\java\lang> javadoc *.java
Think about what the code actually says!
>>> (1 or 2)
1
>>> (2 or 1)
2
That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:
def or(x, y):
if x: return x
if y: return y
return False
In the first example, x == 1
and y == 2
. In the second example, it's vice versa. That's why it returns different values depending on the order of them.
paxdiablo's answer is great, but there are a lot of common resolutions that have just a few more or less pixels in a given direction, and the greatest common divisor approach gives horrible results to them.
Take for example the well behaved resolution of 1360x765 which gives a nice 16:9 ratio using the gcd approach. According to Steam, this resolution is only used by 0.01% of it's users, while 1366x768 is used by a whoping 18.9%. Let's see what we get using the gcd approach:
1360x765 - 16:9 (0.01%)
1360x768 - 85:48 (2.41%)
1366x768 - 683:384 (18.9%)
We'd want to round up that 683:384 ratio to the closest, 16:9 ratio.
I wrote a python script that parses a text file with pasted numbers from the Steam Hardware survey page, and prints all resolutions and closest known ratios, as well as the prevalence of each ratio (which was my goal when I started this):
# Contents pasted from store.steampowered.com/hwsurvey, section 'Primary Display Resolution'
steam_file = './steam.txt'
# Taken from http://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Vector_Video_Standards4.svg/750px-Vector_Video_Standards4.svg.png
accepted_ratios = ['5:4', '4:3', '3:2', '8:5', '5:3', '16:9', '17:9']
#-------------------------------------------------------
def gcd(a, b):
if b == 0: return a
return gcd (b, a % b)
#-------------------------------------------------------
class ResData:
#-------------------------------------------------------
# Expected format: 1024 x 768 4.37% -0.21% (w x h prevalence% change%)
def __init__(self, steam_line):
tokens = steam_line.split(' ')
self.width = int(tokens[0])
self.height = int(tokens[2])
self.prevalence = float(tokens[3].replace('%', ''))
# This part based on pixdiablo's gcd answer - http://stackoverflow.com/a/1186465/828681
common = gcd(self.width, self.height)
self.ratio = str(self.width / common) + ':' + str(self.height / common)
self.ratio_error = 0
# Special case: ratio is not well behaved
if not self.ratio in accepted_ratios:
lesser_error = 999
lesser_index = -1
my_ratio_normalized = float(self.width) / float(self.height)
# Check how far from each known aspect this resolution is, and take one with the smaller error
for i in range(len(accepted_ratios)):
ratio = accepted_ratios[i].split(':')
w = float(ratio[0])
h = float(ratio[1])
known_ratio_normalized = w / h
distance = abs(my_ratio_normalized - known_ratio_normalized)
if (distance < lesser_error):
lesser_index = i
lesser_error = distance
self.ratio_error = distance
self.ratio = accepted_ratios[lesser_index]
#-------------------------------------------------------
def __str__(self):
descr = str(self.width) + 'x' + str(self.height) + ' - ' + self.ratio + ' - ' + str(self.prevalence) + '%'
if self.ratio_error > 0:
descr += ' error: %.2f' % (self.ratio_error * 100) + '%'
return descr
#-------------------------------------------------------
# Returns a list of ResData
def parse_steam_file(steam_file):
result = []
for line in file(steam_file):
result.append(ResData(line))
return result
#-------------------------------------------------------
ratios_prevalence = {}
data = parse_steam_file(steam_file)
print('Known Steam resolutions:')
for res in data:
print(res)
acc_prevalence = ratios_prevalence[res.ratio] if (res.ratio in ratios_prevalence) else 0
ratios_prevalence[res.ratio] = acc_prevalence + res.prevalence
# Hack to fix 8:5, more known as 16:10
ratios_prevalence['16:10'] = ratios_prevalence['8:5']
del ratios_prevalence['8:5']
print('\nSteam screen ratio prevalences:')
sorted_ratios = sorted(ratios_prevalence.items(), key=lambda x: x[1], reverse=True)
for value in sorted_ratios:
print(value[0] + ' -> ' + str(value[1]) + '%')
For the curious, these are the prevalence of screen ratios amongst Steam users (as of October 2012):
16:9 -> 58.9%
16:10 -> 24.0%
5:4 -> 9.57%
4:3 -> 6.38%
5:3 -> 0.84%
17:9 -> 0.11%
You can now use Object.assign(target, ...sources)
. Following your example, you could use it like this:
class Foo {
name: string;
getName(): string { return this.name };
}
let fooJson: string = '{"name": "John Doe"}';
let foo: Foo = Object.assign(new Foo(), JSON.parse(fooJson));
console.log(foo.getName()); //returns John Doe
Object.assign
is part of ECMAScript 2015 and is currently available in most modern browsers.
trim off everything after the last instance of ":"
cat fileListingPathsAndFiles.txt | grep -o '^.*:'
and if you wanted to drop that last ":"
cat file.txt | grep -o '^.*:' | sed 's/:$//'
@kp123: you'd want to replace :
with /
(where the sed colon should be \/
)
I also tried to update a component from a jsf backing bean/class
You need to do the following after manipulating the UI component:
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())
It is important to use the clientId instead of the (server-side) componentId!!
With Mongo 3.2 and higher just use your connection string as is:
mongo mongodb://username:[email protected]:10011/my_database
So, I'm used to use
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.
Static variable retains it's previous value until the program exit. Static is used by calling directly class_Name.Method() or class_Name.Property. No object reference is needed. The most popular use of static is C#'s Math class. Math.Sin(), Math.Cos(), Math.Sqrt().
If you try exec sp_rename
and receieve a LockMatchID error then it might help to add a use [database] statement first:
I tried
exec sp_rename '[database_name].[dbo].[table_name]', 'new_table_name';
-- Invalid EXECUTE statement using object "Object", method "LockMatchID".
What I had to do to fix it was to rewrite it to:
use database_name
exec sp_rename '[dbo].[table_name]', 'new_table_name';
MYSQL IS NOT NULL WITH JOINS AND SELECT, INSERT INTO, DELETE & LOGICAL OPERATOR LIKE OR , NOT
Using IS NOT NULL On Join Conditions
SELECT * FROM users
LEFT JOIN posts ON post.user_id = users.id
WHERE user_id IS NOT NULL;
Using IS NOT NULL With AND Logical Operator
SELECT * FROM users
WHERE email_address IS NOT NULL
AND mobile_number IS NOT NULL;
Using IS NOT NULL With OR Logical Operator
SELECT * FROM users
WHERE email_address IS NOT NULL
OR mobile_number IS NOT NULL;
Why not just do this?
double f = 359.01335;
printf("%g", round(f * 1000.0) / 1000.0);
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F
:
call userInput.bat
In my case, spring threw this because i forgot to make an inner class static.
When you found that it doesnt help even adding a no-arg constructor, please check your modifier.
This code let you fill the banner to the maximum width and keep the ratio. This will only work in portrait. You must recreate the ad when you rotate the device. In landscape you should just leave the ad as is because it will be quite big an blurred.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
double ratio = ((float) (width))/300.0;
int height = (int)(ratio*50);
AdView adView = new AdView(this,"ad_url","my_ad_key",true,true);
LinearLayout layout = (LinearLayout) findViewById(R.id.testing);
mAdView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,height));
adView.setAdListener(this);
layout.addView(adView);
I solved the problem with this code:
using System.IO;
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\\")))
On NetBeans : open your project explorer->Dependencies->[file.jar] rightclick->Download Javadoc
If the two hex strings are the same length and you want a hex string output then you might try this.
def hexxor(a, b): # xor two hex strings of the same length return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b)])
Try this, Its working:
mysql -h {hostname} -u{username} -p{password} -N -e "{query to execute}"
The ArrayList
class is a wrapper class for an array. It contains an inner array.
public ArrayList<T> {
private Object[] array;
private int size;
}
A LinkedList
is a wrapper class for a linked list, with an inner node for managing the data.
public LinkedList<T> {
class Node<T> {
T data;
Node next;
Node prev;
}
private Node<T> first;
private Node<T> last;
private int size;
}
Note, the present code is used to show how the class may be, not the actual implementation. Knowing how the implementation may be, we can do the further analysis:
ArrayList is faster than LinkedList if I randomly access its elements. I think random access means "give me the nth element". Why ArrayList is faster?
Access time for ArrayList: O(1). Access time for LinkedList: O(n).
In an array, you can access to any element by using array[index]
, while in a linked list you must navigate through all the list starting from first
until you get the element you need.
LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.
Deletion time for ArrayList: Access time + O(n). Deletion time for LinkedList: Access time + O(1).
The ArrayList must move all the elements from array[index]
to array[index-1]
starting by the item to delete index. The LinkedList should navigate until that item and then erase that node by decoupling it from the list.
LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.
Insertion time for ArrayList: O(n). Insertion time for LinkedList: O(1).
Why the ArrayList can take O(n)? Because when you insert a new element and the array is full, you need to create a new array with more size (you can calculate the new size with a formula like 2 * size or 3 * size / 2). The LinkedList just add a new node next to the last.
This analysis is not just in Java but in another programming languages like C, C++ and C#.
More info here:
You can use the following code to open a file location from vba.
Dim Foldername As String
Foldername = "\\server\Instructions\"
Shell "C:\WINDOWS\explorer.exe """ & Foldername & "", vbNormalFocus
You can use this code for both windows shares and local drives.
VbNormalFocus can be swapper for VbMaximizedFocus if you want a maximized view.
If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"
my 2¢ quick global fix:
// drop down in responsive table
(function () {
$('.table-responsive').on('shown.bs.dropdown', function (e) {
var $table = $(this),
$menu = $(e.target).find('.dropdown-menu'),
tableOffsetHeight = $table.offset().top + $table.height(),
menuOffsetHeight = $menu.offset().top + $menu.outerHeight(true);
if (menuOffsetHeight > tableOffsetHeight)
$table.css("padding-bottom", menuOffsetHeight - tableOffsetHeight);
});
$('.table-responsive').on('hide.bs.dropdown', function () {
$(this).css("padding-bottom", 0);
})
})();
Explications: When a dropdown-menu inside a '.table-responsive' is shown, it calculate the height of the table and expand it (with padding) to match the height required to display the menu. The menu can be any size.
In my case, this is not the table that has the '.table-responsive' class, it's a wrapping div:
<div class="table-responsive" style="overflow:auto;">
<table class="table table-hover table-bordered table-condensed server-sort">
So the $table var in the script is actually a div! (just to be clear... or not) :)
Note: I wrap it in a function so my IDE can collapse function ;) but it's not mandatory!
for similar type class.
List<targetlist> targetlst= JsonConvert.DeserializeObject<List<targetlist>>(JsonConvert.SerializeObject(<List<baselist>));
Try this snippet of code:
String timeSettings = android.provider.Settings.System.getString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME);
if (timeSettings.contentEquals("0")) {
android.provider.Settings.System.putString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME, "1");
}
Date now = new Date(System.currentTimeMillis());
Log.d("Date", now.toString());
Make sure to add permission in Manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
By value, what worked for me with jQuery 1.7 was the below code, try this:
$('#id option[value=theOptionValue]').prop('selected', 'selected').change();
Pixel is an absolute unit whereas rem/em are relative units. For more: https://drafts.csswg.org/css-values-3/
You should use the relative unit when you want the font-size to be adaptive according to the system's font size because the system provides the font-size value to the root element which is the HTML element.
In this case, where the webpage is open in google chrome, the font-size to the HTML element is set by chrome, try changing it to see the effect on webpages with fonts of rem/ em units.
If you use px
as the unit for fonts, the fonts will not resize whereas the fonts with rem
/ em
unit will resize when you change the system's font size.
So use px
when you want the size to be fixed and use rem
/ em
when you want the size to be adaptive/ dynamic to the size of the system.
You can get the key using values using following code..
ArrayList valuesList = new ArrayList();
Set keySet = initalMap.keySet();
ArrayList keyList = new ArrayList(keySet);
for(int i = 0 ; i < keyList.size() ; i++ ) {
valuesList.add(initalMap.get(keyList.get(i)));
}
Collections.sort(valuesList);
Map finalMap = new TreeMap();
for(int i = 0 ; i < valuesList.size() ; i++ ) {
String value = (String) valuesList.get(i);
for( int j = 0 ; j < keyList.size() ; j++ ) {
if(initalMap.get(keyList.get(j)).equals(value)) {
finalMap.put(keyList.get(j),value);
}
}
}
System.out.println("fianl map ----------------------> " + finalMap);
Try this way it will hide the calendar and show year only
$(function() {
$( "#datepicker" ).datepicker({dateFormat: 'yy'});
});?
CSS
.ui-datepicker-calendar {
display: none;
}
DEMO ?
Our approach is simple, but it works! :)
When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.
<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
function logOut() {
window.close = function () {
window.open('Default.aspx', '_blank');
};
}
</script>
hasOwnProperty
is a normal JavaScript function that takes a string argument.
When you call shape1.hasOwnProperty(name)
you are passing it the value of the name
variable (which doesn't exist), just as it would if you wrote alert(name)
.
You need to call hasOwnProperty
with a string containing name
, like this: shape1.hasOwnProperty("name")
.
It's indeed one of the biggest epic failures in the standard Java API. Have a bit of patience, then you'll get your solution in flavor of the new Date and Time API specified by JSR 310 / ThreeTen which is (most likely) going to be included in the upcoming Java 8.
Until then, you can get away with JodaTime.
DateTime dt1 = new DateTime(2000, 1, 1, 0, 0, 0, 0);
DateTime dt2 = new DateTime(2010, 1, 1, 0, 0, 0, 0);
int days = Days.daysBetween(dt1, dt2).getDays();
Its creator, Stephen Colebourne, is by the way the guy behind JSR 310, so it'll look much similar.
I know this is old, but a combination of these ideas leads to a very elegant solution:
Keep all the default property settings for the DropDownList (AppendDataBoundItems=false, Items empty). Then handle the DataBound event like this:
protected void dropdown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
list.Items.Insert(0, "--Select One--");
}
The icing on the cake is that this one handler can be shared by any number of DropDownList objects, or even put into a general-purpose utility library for all your projects.
If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index
CSS attribute. This should work (untested)
<div>
<div style='z-index: 1'>1</div>
<div style='z-index: 2'>2</div>
<div style='z-index: 3'>3</div>
<div style='z-index: 4'>4</div>
</div>
This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)
Here html helper for you
public static SelectList IndividualNamesOrAll(this SelectList Object)
{
MedicalVarianceViewsDataContext LinqCtx = new MedicalVarianceViewsDataContext();
//not correct need individual view!
var IndividualsListBoxRaw = ( from x in LinqCtx.ViewIndividualsNames
orderby x.FullName
select x);
List<SelectListItem> items = new SelectList (
IndividualsListBoxRaw,
"First_Hospital_Case_Nbr",
"FullName"
).ToList();
items.Insert(0, (new SelectListItem { Text = "All Individuals",
Value = "0.0",
Selected = true }));
Object = new SelectList (items,"Value","Text");
return Object;
}
Use the built in type cast functionality, simply type
$realArray = (array)$stdClass;
typeof(Controller).Assembly.GetName().Version
Gives the current version programmatically.
explode
has some very big problems in real life usage:
count(explode(',', null)); // 1 !!
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8
this is why i prefer preg_split
preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)
the entire boilerplate:
/** @brief wrapper for explode
* @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
* @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
* @param string $delimiter default ','
* @return array|mixed
*/
public static function explode($val, $as_is = false, $delimiter = ',')
{
// using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
return (is_string($val) || is_int($val)) ?
preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
:
($as_is ? $val : (is_array($val) ? $val : []));
}
Note that what you want is to know if stdin is connected to a terminal or not, not if it exists. It always exists but when you use the shell to pipe something into it or read a file, it is not connected to a terminal.
You can check that a file descriptor is connected to a terminal via the termios.h functions:
#include <termios.h>
#include <stdbool.h>
bool stdin_is_a_pipe(void)
{
struct termios t;
return (tcgetattr(STDIN_FILENO, &t) < 0);
}
This will try to fetch the terminal attributes of stdin. If it is not connected to a pipe, it is attached to a tty and the tcgetattr function call will succeed. In order to detect a pipe, we check for tcgetattr failure.
JAXB is simple to use and is included in Java 6 SE. With JAXB, or other XML data binding such as Simple, you don't have to handle the XML yourself, most of the work is done by the library. The basic usage is to add annotation to your existing POJO. These annotation are then used to generate an XML Schema for you data and also when reading/writing your data from/to a file.
Two suggestions:
Use a HashSet instead of an ArrayList. This will speed up the contains() checks considerably if you have a long list
Make sure Customer.equals() and Customer.hashCode() are implemented properly, i.e. they should be based on the combined values of the underlying fields in the customer object.
Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday
>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]
Or for integers:
>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]
Or for later versions of ruby (>= 1.9 - as pointed out by Alex):
>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]
time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).
>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777
In Java I used encoding "IBM850" to write the file. That solved the problem.
If attribute routing is being used, you can use the [FromUri] and [FromBody] attributes.
Example:
[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id, [FromBody()] Product product)
{
// Add product
}
check the name of the database in a file where you established a connection.
var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}]
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37)
apps.splice(removeIndex, 1);
I am adding more points to the solution by @Rushi Shah
mvn clean install -X
helps to identify the root cause.
Some of the important phases of Maven build lifecycle are:
clean
– the project is clean of all artifacts that came from previous compilations
compile
– the project is compiled into /target directory of project root
install
– packaged archive is copied into local maven repository (could in your user's home directory under /.m2)
test
– unit tests are run
package
– compiled sources are packaged into archive (JAR by default)
The 1.6 under tag refers to JDK version. We need to ensure that proper jdk version in our dev environment or change the value to 1.7 or 1.5 or whatever if the application can be supported in that JDK version.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
We can find the complete details on Maven build lifecycle in Maven site.
This solution is for usort() with an easy-to-remember notation for multidimensional sorting. The spaceship operator <=> is used, which is available from PHP 7.
usort($in,function($a,$b){
return $a['first'] <=> $b['first'] //first asc
?: $a['second'] <=> $b['second'] //second asc
?: $b['third'] <=> $a['third'] //third desc (a b swapped!)
//etc
;
});
Examples:
$in = [
['firstname' => 'Anton', 'surname' => 'Gruber', 'birthdate' => '03.08.1967', 'rank' => 3],
['firstname' => 'Anna', 'surname' => 'Egger', 'birthdate' => '04.01.1960', 'rank' => 1],
['firstname' => 'Paul', 'surname' => 'Mueller', 'birthdate' => '15.10.1971', 'rank' => 2],
['firstname' => 'Marie', 'surname' => 'Schmidt ', 'birthdate' => '24.12.1963', 'rank' => 2],
['firstname' => 'Emma', 'surname' => 'Mueller', 'birthdate' => '23.11.1969', 'rank' => 2],
];
first task: Order By rank asc, surname asc
usort($in,function($a,$b){
return $a['rank'] <=> $b['rank'] //first asc
?: $a['surname'] <=> $b['surname'] //second asc
;
});
second task: Order By rank desc, surname asc, firstmame asc
usort($in,function($a,$b){
return $b['rank'] <=> $a['rank'] //first desc
?: $a['surname'] <=> $b['surname'] //second asc
?: $a['firstname'] <=> $b['firstname'] //third asc
;
});
third task: Order By rank desc, birthdate asc
The date cannot be sorted in this notation. It is converted with strtotime.
usort($in,function($a,$b){
return $b['rank'] <=> $a['rank'] //first desc
?: strtotime($a['birthdate']) <=> strtotime($b['birthdate']) //second asc
;
});
var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;
Ctrl + Alt + L is format file (includes the two below)
Ctrl + Alt + O is optimize imports
Ctrl + Alt + I will fix indentation on a particular line
I usually run Ctrl + Alt + L a few times before committing my work. I'd rather it do the cleanup/reformatting at my command instead of automatically.
A step by step guide I found here.
To create a read-only database user account for MySQL
At a UNIX prompt, run the MySQL command-line program, and log in as an administrator by typing the following command:
mysql -u root -p
Type the password for the root account. At the mysql prompt, do one of the following steps:
To give the user access to the database from any host, type the following command:
grant select on database_name.* to 'read-only_user_name'@'%' identified by 'password';
If the collector will be installed on the same host as the database, type the following command:
grant select on database_name.* to 'read-only_user_name' identified by 'password';
This command gives the user read-only access to the database from the local host only. If you know the host name or IP address of the host that the collector is will be installed on, type the following command:
grant select on database_name.* to 'read-only_user_name'@'host_name or IP_address' identified by 'password';
The host name must be resolvable by DNS or by the local hosts file. At the mysql prompt, type the following command:
flush privileges;
Type quit
.
The following is a list of example commands and confirmation messages:
mysql> grant select on dbname.* to 'readonlyuser'@'%' identified
by 'pogo$23';
Query OK, 0 rows affected (0.11 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
A simple one would be
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
Recommend to use LINQPad related nuget
package, then you can use exceptionInstance.Dump()
.
LINQPad.Runtime
LINQPad
Sample code:
using System;
using LINQPad;
namespace csharp_Dump_test
{
public class Program
{
public static void Main()
{
try
{
dosome();
}
catch (Exception ex)
{
ex.Dump();
}
}
private static void dosome()
{
throw new Exception("Unable.");
}
}
}
LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.
On Ubuntu, after creating localhost and '%' versions of the user, and granting appropriate access to database.tables for both, I had to comment out the 'bind-address' in /etc/mysql/mysql.conf.d/mysql.cnf and restart mysql as sudo.
To view localhost website from mobile device you have to follow thoses steps :
Hope it helps
Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum
however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf
.
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
Therefore, before starting '$ sqlplus' on OS, run the followings:
On Windows
set NLS_LANG=AMERICAN_AMERICA.UTF8
On Unix (Solaris and Linux, centos etc)
export NLS_LANG=AMERICAN_AMERICA.UTF8
It would also be advisable to set env variable in your '.bash_profile' [on start up script]
This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.
just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.
Delete your existing workspace and then recreate the workspace and add your projects.
Below is the way to crop an image.
image_path: The path to the image to edit
coords: A tuple of x/y coordinates (x1, y1, x2, y2)[open the image in mspaint and check the "ruler" in view tab to see the coordinates]
saved_location: Path to save the cropped image
from PIL import Image
def crop(image_path, coords, saved_location:
image_obj = Image.open("Path of the image to be cropped")
cropped_image = image_obj.crop(coords)
cropped_image.save(saved_location)
cropped_image.show()
if __name__ == '__main__':
image = "image.jpg"
crop(image, (100, 210, 710,380 ), 'cropped.jpg')
if you are using Maven 2.0.8+, then it will be very simple, run mvndebug from the console, and connect to it via Remote Debug Java Application with port 8000.
and
operator and or
operator have lower precedence than assignment operator =
.
This means that $a = true and false;
is equivalent to ($a = true) and false
.
In most cases you will probably want to use &&
and ||
, which behave in a way known from languages like C, Java or JavaScript.
In my case, I fixed by the following:
* run git config --edit
* In the git config file:
[branch "master"]
remote = origin # <--- change the default origin here
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
This one seems to be a better fit:
<#if userName?has_content>
... do something
</#if>
http://freemarker.sourceforge.net/docs/ref_builtins_expert.html
Since November 2017, one can use tomcat8-maven-plugin:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat8-maven-plugin</artifactId>
<version>2.2</version>
</dependency>
Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:
<pluginRepositories>
<pluginRepository>
<id>icm</id>
<name>Spring Framework Milestone Repository</name>
<url>http://maven.icm.edu.pl/artifactory/repo</url>
</pluginRepository>
</pluginRepositories>
Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:
kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:
$ mysql &
$ echo $! > pid_stored
then in the script:
kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
You can do it like:
tvHide.setText(Html.fromHtml("<p><span style='text-decoration: underline'>Hide post</span></p>").toString());
Hope this helps
Try + (instancetype)appearance of UITableView:
Objective-C:
[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"
Swift 3.0:
UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"
Note: Change will reflect to all tables used in application.
What I found was that the nbconvert/utils/pandoc.py had a code bug that resulted in the error for my machine. The code checks if pandoc is in your environmental variables path. For my machine the answer is no. However pandoc.exe is!
Solution was to add '.exe' to the code on line 69
if __version is None:
if not which('pandoc.exe'):
raise PandocMissing()
The same goes for 'xelatex' is not installed. Add to the file nbconvert/exporters/pdf.py on line 94
cmd = which(command_list[0]+'.exe')
This is a very common misconception. There is no live HTML5 video support (except for HLS on iOS and Mac Safari). You may be able to 'hack' it using a webm container, but I would not expect that to be universally supported. What you are looking for is included in the Media Source Extensions, where you can feed the fragments to the browser one at a time. but you will need to write some client side javascript.
Brighams answer uses literal regexp
.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
Try:
select replace(convert(varchar, getdate(), 111),'/','-');
More on ms sql tips
well if you really need a curl equivalent you can try node-curl
npm install node-curl
you will probably need to add libcurl4-gnutls-dev
.
I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).
The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.
For me it was a "progaurd" build entry in my build.gradle. I removed the entire build section, then did a re-sync and problem solved.
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
Working code as below:
var array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];_x000D_
_x000D_
function closest(array, num) {_x000D_
var i = 0;_x000D_
var minDiff = 1000;_x000D_
var ans;_x000D_
for (i in array) {_x000D_
var m = Math.abs(num - array[i]);_x000D_
if (m < minDiff) {_x000D_
minDiff = m;_x000D_
ans = array[i];_x000D_
}_x000D_
}_x000D_
return ans;_x000D_
}_x000D_
console.log(closest(array, 88));
_x000D_
I do this quite often on results returned from a query..
e.g.
// $MyQueryResult is an array of results from a query
foreach ($MyQueryResult as $key=>$value)
{
${$key}=$value;
}
Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']
Yep, it's probably lazy, but I've never had any problems.
I was facing the same problem for a long time but I solved it by adjusting the settings in gradle.
Step 1:In Module app add dependency in BuildScript
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
}
}
Step 2: Add dexOption and give the following heapSize
dexOptions {
incremental = true;
preDexLibraries = false
javaMaxHeapSize "4g"
}
Step 3: Add productFlavors
productFlavors {
dev {
minSdkVersion 23
applicationId = "com.Reading.home"
}
prod {
minSdkVersion 15
applicationId = "com.Reading.home" // you don't need it, but can be useful
}
}
This should reduce your build time.
self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red
Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.
function doSomething(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
doSomething(foo);
That will call doSomething
, which will call foo
, which will alert "stuff goes here".
Note that it's very important to pass the function reference (foo
), rather than calling the function and passing its result (foo()
). In your question, you do it properly, but it's just worth pointing out because it's a common error.
Sometimes you want to call the callback so it sees a specific value for this
. You can easily do that with the JavaScript call
function:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}
function foo() {
alert(this.name);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`
You can also pass arguments:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
}
function foo(salutation) {
alert(salutation + " " + this.name);
}
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`
Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply
to do that:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
}
function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe - 3 2 1" via `foo`
You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-
Gson gson = new GsonBuilder().create();
Response r = gson.fromJson(jsonString, Response.class);
Here is an example- http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html
package com.v3mobi.userpersistdatetime;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class UserActivity extends AppCompatActivity {
Date startDate;
Date endDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
startDate = java.util.Calendar.getInstance().getTime(); //set your start time
}
@Override
protected void onStop() {
super.onStop();
endDate = java.util.Calendar.getInstance().getTime(); // set your end time
chekUserPersistence();
}
private void chekUserPersistence()
{
long duration = endDate.getTime() - startDate.getTime();
// long duration = 301000;
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration); // minutes ok
long secs = (duration/1000) % 60; // minutes ok
Toast.makeText(UserActivity.this, "Diff "
+ diffInMinutes + " : "+ secs , Toast.LENGTH_SHORT).show();
System.out.println("Diff " + diffInMinutes +" : "+ secs );
Log.e("keshav","diffInMinutes -->" +diffInMinutes);
Log.e("keshav","secs -->" +secs);
finish();
}
}
This is no longer up-to-date!
Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.
Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.
My best approach is:
var item = {...}
var items = [{id:2}, {id:2}, {id:2}];
items[items.findIndex(el => el.id === item.id)] = item;
Reference for findIndex
And in case you don't want to replace with new object, but instead to copy the fields of item
, you can use Object.assign
:
Object.assign(items[items.findIndex(el => el.id === item.id)], item)
as an alternative with .map()
:
Object.assign(items, items.map(el => el.id === item.id? item : el))
Don't modify the array, use a new one, so you don't generate side effects
const updatedItems = items.map(el => el.id === item.id ? item : el)
Order Collection Limit :
$orderCollection = Mage::getResourceModel('sales/order_collection');
$orderCollection->getSelect()->limit(10);
foreach ($orderCollection->getItems() as $order) :
$orderModel = Mage::getModel('sales/order');
$order = $orderModel->load($order['entity_id']);
echo $order->getId().'<br>';
endforeach;
//call Facebook onclick on your customized button on click by the following
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
}
@Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
setContentView(R.layout.activity_main);
Button mycustomizeedbutton=(Button)findViewById(R.id.mycustomizeedbutton);
mycustomizeedbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
}
});
}
I had this same problem. The session ID is sent in a cookie, but since the request is cross-domain, the browser's security settings will block the cookie from being sent.
Solution: Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.
I struggled a lot with this issue, and there weren't many good answers around. Here's an article detailing the solution: Javascript Cross-Domain Request With Session
The following solution assumes you are serving your dist/ folder using nodejs. Please use the following app.js in root level
const express = require('express'),http = require('http'),path = require('path'),compression = require('compression');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.use(compression()) //compressing dist folder
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
})
const port = process.env.PORT || '4201';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log('Running at port ' + port))
Make sure you install dependencies;
npm install compression --save
npm install express --save;
Now build the app
ng build --prod --build-optimizer
If you want to further compress the build say reduce 300kb(approx) from , then follow the below process;
Create a folder called vendor
inside the src
folder and inside vendor folder create a file rxjs.ts
and paste the below code in it;
export {Subject} from 'rxjs/Subject';
export {Observable} from 'rxjs/Observable';
export {Subscription} from 'rxjs/Subscription';
And then add the follwing in the tsconfig.json
file in your angular-cli application. Then in the compilerOptions
, add the following json;
"paths": {
"rxjs": [
"./vendor/rxjs.ts"
]
}
This will make your build size way too smaller. In my project I reduced the size from 11mb to 1mb. Hope it helps
Newer versions of svn support the --show-item
argument:
svn info --show-item revision
For the revision number of your local working copy, use:
svn info --show-item last-changed-revision
You can use os.system()
to execute a command line like this:
svn info | grep "Revision" | awk '{print $2}'
I do that in my nightly build scripts.
Also on some platforms there is a svnversion
command, but I think I had a reason not to use it. Ahh, right. You can't get the revision number from a remote repository to compare it to the local one using svnversion.
I needed to indent two rows to allow for a larger first word in a para. A cumbersome one-off solution is to place text in an SVG element and position this the same as an <img>. Using float and the SVG's height tag defines how many rows will be indented e.g.
<p style="color: blue; font-size: large; padding-top: 4px;">
<svg height="44" width="260" style="float:left;margin-top:-8px;"><text x="0" y="36" fill="blue" font-family="Verdana" font-size="36">Lorum Ipsum</text></svg>
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
Yes it is cumbersome but it is also independent of the width of the containing div.
The above answer was to my own query to allow the first word(s) of a para to be larger and positioned over two rows. To simply indent the first two lines of a para you could replace all the SVG tags with the following single pixel img:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" style="float:left;width:260px;height:44px;" />
I like Daniel Vérité's answer. But when you can't use a CREATE statement you can either use a bash solution or, if you're a windows user, a powershell one:
# You don't need this if you have pgpass.conf
$env:PGPASSWORD = "userpass"
# Get table list
$tables = & 'C:\Program Files\PostgreSQL\9.4\bin\psql.exe' -U user -w -d dbname -At -c "select table_name from information_schema.tables where table_type='BASE TABLE' AND table_schema='schema1'"
foreach ($table in $tables) {
& 'C:\path_to_postresql\bin\psql.exe' -U root -w -d dbname -At -c "select '$table', count(*) from $table"
}
Just create the folders, which is missing in your system..
/etc/pki/tls/certs/
and create the file using the following command,
sudo apt-get install ca-certificates
and then copy and paste the certificate to the destination folder, which is showing in your error.. mine was " with message 'error setting certificate verify locations: CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none' in
" make sure you paste the file to the exact location mentioned in the error. Use the following command to copy paste..
sudo cp /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt
Fixed.
Here is a solution I've used before that does not require you to use the UIWebView.
- (UIImage *)scaleAndRotateImage(UIImage *)image
{
int kMaxResolution = 320; // Or whatever
CGImageRef imgRef = image.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
if (width > kMaxResolution || height > kMaxResolution) {
CGFloat ratio = width/height;
if (ratio > 1) {
bounds.size.width = kMaxResolution;
bounds.size.height = bounds.size.width / ratio;
}
else {
bounds.size.height = kMaxResolution;
bounds.size.width = bounds.size.height * ratio;
}
}
CGFloat scaleRatio = bounds.size.width / width;
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = image.imageOrientation;
switch(orient) {
case UIImageOrientationUp: //EXIF = 1
transform = CGAffineTransformIdentity;
break;
case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;
case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;
case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
}
UIGraphicsBeginImageContext(bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
CGContextScaleCTM(context, -scaleRatio, scaleRatio);
CGContextTranslateCTM(context, -height, 0);
}
else {
CGContextScaleCTM(context, scaleRatio, -scaleRatio);
CGContextTranslateCTM(context, 0, -height);
}
CGContextConcatCTM(context, transform);
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageCopy;
}
The article can be found on Apple Support at: http://discussions.apple.com/message.jspa?messageID=7276709#7276709
Depends on your use case. There are applications where the runtime of a for loop needs to be constant (e.g. to satisfy some timing constraints, or to hide your data internals from timing based attacks).
In those cases it will even make sense to set a flag and only check the flag value AFTER all the for
loop iterations have actually run. Of course, all the for loop iterations need to run code that still takes about the same time.
If you do not care about the run time... use break;
and continue;
to make the code easier to read.
you can see the solution on http://jsfiddle.net/CBQCA/1/
OR
<table style="height:100%;width:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
<tr style="height: 25%;">
<td>Region</td>
</tr>
<tr style="height: 75%;">
<td>100.00%</td>
</tr>
</table>?
I removed the font size, to show that columns are expanded.
I added border:1px solid
just to make sure table is expanded. you can remove it.
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
If it's a server socket, you should call listen()
on your socket, and then getsockname()
to find the port number on which it is listening:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(sin.sin_port));
As for the IP address, if you use INADDR_ANY
then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname()
on the socket for a specific connection (which you get from accept()
) in order to find out which local IP address is being used on that connection.
For any wordpress site, you can go to http://example.com/feed and check the following tag in the xml file to see the version number:
<generator>http://wordpress.org/?v=3.7</generator>
Here, 3.7 is the version installed.
I don't know if it is possible in XAML-only but try the following:
Give your ComboBox a name so you can access it in the codebehind: "typesComboBox1"
Now try the following
typesComboBox1.ItemsSource = Enum.GetValues(typeof(ExampleEnum));
If you are using web api then you should make a http POST
call to URL : https://www.googleapis.com/oauth2/v4/token
with following request body
client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token
refresh token never expires so you can use it any number of times. The response will be a JSON like this:
{
"access_token": "your refreshed access token",
"expires_in": 3599,
"scope": "Set of scope which you have given",
"token_type": "Bearer"
}
You can use this code for copy input value in page in Clipboard by click a button
This is Html
<input type="text" value="xxx" id="link" class="span12" />
<button type="button" class="btn btn-info btn-sm" onclick="copyToClipboard('#link')">
Copy Input Value
</button>
Then for this html , we must use this JQuery Code
function copyToClipboard(element) {
$(element).select();
document.execCommand("copy");
}
This is the simplest solution for this question
dplyr
definitely does things that data.table
can not.Your point #3
dplyr abstracts (or will) potential DB interactions
is a direct answer to your own question but isn't elevated to a high enough level. dplyr
is truly an extendable front-end to multiple data storage mechanisms where as data.table
is an extension to a single one.
Look at dplyr
as a back-end agnostic interface, with all of the targets using the same grammer, where you can extend the targets and handlers at will. data.table
is, from the dplyr
perspective, one of those targets.
You will never (I hope) see a day that data.table
attempts to translate your queries to create SQL statements that operate with on-disk or networked data stores.
dplyr
can possibly do things data.table
will not or might not do as well.Based on the design of working in-memory, data.table
could have a much more difficult time extending itself into parallel processing of queries than dplyr
.
Are there analytical tasks that are a lot easier to code with one or the other package for people familiar with the packages (i.e. some combination of keystrokes required vs. required level of esotericism, where less of each is a good thing).
This may seem like a punt but the real answer is no. People familiar with tools seem to use the either the one most familiar to them or the one that is actually the right one for the job at hand. With that being said, sometimes you want to present a particular readability, sometimes a level of performance, and when you have need for a high enough level of both you may just need another tool to go along with what you already have to make clearer abstractions.
Are there analytical tasks that are performed substantially (i.e. more than 2x) more efficiently in one package vs. another.
Again, no. data.table
excels at being efficient in everything it does where dplyr
gets the burden of being limited in some respects to the underlying data store and registered handlers.
This means when you run into a performance issue with data.table
you can be pretty sure it is in your query function and if it is actually a bottleneck with data.table
then you've won yourself the joy of filing a report. This is also true when dplyr
is using data.table
as the back-end; you may see some overhead from dplyr
but odds are it is your query.
When dplyr
has performance issues with back-ends you can get around them by registering a function for hybrid evaluation or (in the case of databases) manipulating the generated query prior to execution.
Also see the accepted answer to when is plyr better than data.table?
Java has a feature called "checked exceptions". That means that there are certain kinds of exceptions, namely those that subclass Exception but not RuntimeException, such that if a method may throw them, it must list them in its throws declaration, say: void readData() throws IOException. IOException is one of those.
Thus, when you are calling a method that lists IOException in its throws declaration, you must either list it in your own throws declaration or catch it.
The rationale for the presence of checked exceptions is that for some kinds of exceptions, you must not ignore the fact that they may happen, because their happening is quite a regular situation, not a program error. So, the compiler helps you not to forget about the possibility of such an exception being raised and requires you to handle it in some way.
However, not all checked exception classes in Java standard library fit under this rationale, but that's a totally different topic.
Check the available tests with module platform and print the answer out for your system:
import platform
print dir(platform)
for x in dir(platform):
if x[0].isalnum():
try:
result = getattr(platform, x)()
print "platform."+x+": "+result
except TypeError:
continue
Why don't you simply use JavaScript's trim():
str.trim() //Will work everywhere irrespective of any framework.
For compatibility with <IE9
use:
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
Found it Here
Personally I use this, which is similar to tarek11011's:
// Use a less-common namespace than just 'log'
function myLog(msg)
{
// Attempt to send a message to the console
try
{
console.log(msg);
}
// Fail gracefully if it does not exist
catch(e){}
}
The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log()
right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.
You can just use top
It will display everything running on your OSX
Just find the program in Program Files directory (or in other location). Right click on the EXE file, on the second tab at the bottom check the checkbox of forcing running that program with administration privileges. From now all shortcuts of the exe file will be fired with administration privileges :)
Create a comparator which accepts the compare mode in its constructor and pass different modes for different scenarios based on your requirement
public class RecipeComparator implements Comparator<Recipe> {
public static final int COMPARE_BY_ID = 0;
public static final int COMPARE_BY_NAME = 1;
private int compare_mode = COMPARE_BY_NAME;
public RecipeComparator() {
}
public RecipeComparator(int compare_mode) {
this.compare_mode = compare_mode;
}
@Override
public int compare(Recipe o1, Recipe o2) {
switch (compare_mode) {
case COMPARE_BY_ID:
return o1.getId().compareTo(o2.getId());
default:
return o1.getInputRecipeName().compareTo(o2.getInputRecipeName());
}
}
}
Actually for numbers you need to handle them separately check below
public static void main(String[] args) {
String string1 = "1";
String string2 = "2";
String string11 = "11";
System.out.println(string1.compareTo(string2));
System.out.println(string2.compareTo(string11));// expected -1 returns 1
// to compare numbers you actually need to do something like this
int number2 = Integer.valueOf(string1);
int number11 = Integer.valueOf(string11);
int compareTo = number2 > number11 ? 1 : (number2 < number11 ? -1 : 0) ;
System.out.println(compareTo);// prints -1
}
Change your Google Services version from your build.gradle
:
dependencies {
classpath 'com.google.gms:google-services:4.2.0'
}
Merge - HEAD branch will generate a new commit, preserving the ancestry of each commit history. History can become polluted if merge commits are made by multiple people who work on the same branch in parallel.
Rebase - Re-writes the changes of one branch onto another without creating a new commit. The code history is simplified, linear and readable but it doesn't work with pull requests, because you can't see what minor changes someone made.
I would use git merge
when dealing with feature-based workflow or if I am not familiar with rebase. But, if I want a more a clean, linear history then git rebase
is more appropriate. For more details be sure to check out this merge or rebase article.
Try this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
</androidx.constraintlayout.widget.ConstraintLayout>
/>
_x000D_
Since 2011a, the recommended way is:
booleanIndex = strcmp('KU', strs)
If you want to get the integer index (which you often don't need), you can use:
integerIndex = find(booleanIndex);
strfind
is deprecated, so try not to use it.
This is actually more simple than you'd think: "Just" copy the HTML table (that is: The HTML code for the table) into the clipboard. Excel knows how to decode HTML tables; it'll even try to preserve the attributes.
The hard part is "copy the table into the clipboard" since there is no standard way to access the clipboard from JavaScript. See this blog post: Accessing the System Clipboard with JavaScript – A Holy Grail?
Now all you need is the table as HTML. I suggest jQuery and the html() method.
It moves table down because there is no much space, try to decrease/increase width of certain elements so that it finds some space and does not push the table down. Also you may want to use absolute
positioning to position the div at exactly the place you want, for example:
<style>
#div_id
{
position:absolute;
top:100px; /* set top value */
left:100px; /* set left value */
width:100px; /* set width value */
}
</style>
If you want to appear it over something, you also need to give it z-index
, so it might look like this:
<style>
#div_id
{
position:absolute;
z-index:999;
top:100px; /* set top value */
left:100px; /* set left value */
width:100px; /* set width value */
}
</style>
Start by registering your custom browser/uploader when you instantiate CKEditor. You can designate different URLs for an image browser vs. a general file browser.
<script type="text/javascript">
CKEDITOR.replace('content', {
filebrowserBrowseUrl : '/browser/browse/type/all',
filebrowserUploadUrl : '/browser/upload/type/all',
filebrowserImageBrowseUrl : '/browser/browse/type/image',
filebrowserImageUploadUrl : '/browser/upload/type/image',
filebrowserWindowWidth : 800,
filebrowserWindowHeight : 500
});
</script>
Your custom code will receive a GET parameter called CKEditorFuncNum. Save it - that's your callback function. Let's say you put it into $callback
.
When someone selects a file, run this JavaScript to inform CKEditor which file was selected:
window.opener.CKEDITOR.tools.callFunction(<?php echo $callback; ?>,url)
Where "url" is the URL of the file they picked. An optional third parameter can be text that you want displayed in a standard alert dialog, such as "illegal file" or something. Set url to an empty string if the third parameter is an error message.
CKEditor's "upload" tab will submit a file in the field "upload" - in PHP, that goes to $_FILES['upload']. What CKEditor wants your server to output is a complete JavaScript block:
$output = '<html><body><script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$url.'","'.$msg.'");</script></body></html>';
echo $output;
Again, you need to give it that callback parameter, the URL of the file, and optionally a message. If the message is an empty string, nothing will display; if the message is an error, then url should be an empty string.
The official CKEditor documentation is incomplete on all this, but if you follow the above it'll work like a champ.
How about using numpy.vectorize
.
import numpy as np
x = np.array([1, 2, 3, 4, 5])
squarer = lambda t: t ** 2
vfunc = np.vectorize(squarer)
vfunc(x)
# Output : array([ 1, 4, 9, 16, 25])
Define an extension:
extension Ex on double {
double toPrecision(int n) => double.parse(toStringAsFixed(n));
}
Usage:
void main() {
double d = 2.3456789;
double d1 = d.toPrecision(1); // 2.3
double d2 = d.toPrecision(2); // 2.35
double d3 = d.toPrecision(3); // 2.345
}
You can use DateFormat
(java.text.*) to parse the date:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date d = df.parse("Mon May 27 11:46:15 IST 2013")
You will have to change the locale to match your own (with this you will get 10:46:15). Then you can use the same code you have to convert it to a timestamp.
>>> x = 'foo'
>>> x
'foo'
So the name x
is attached to 'foo'
string. When you call for example repr(x)
the interpreter puts 'foo'
instead of x
and then calls repr('foo')
.
>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"
repr
actually calls a magic method __repr__
of x
, which gives the string containing the representation of the value 'foo'
assigned to x
. So it returns 'foo'
inside the string ""
resulting in "'foo'"
. The idea of repr
is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr
.
>>> eval("'foo'")
'foo'
When we call eval("'foo'")
, it's the same as we type 'foo'
in the interpreter. It's as we directly type the contents of the outer string ""
in the interpreter.
>>> eval('foo')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eval('foo')
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
If we call eval('foo')
, it's the same as we type foo
in the interpreter. But there is no foo
variable available and an exception is raised.
>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>>
str
is just the string representation of the object (remember, x
variable refers to 'foo'
), so this function returns string.
>>> str(5)
'5'
String representation of integer 5
is '5'
.
>>> str('foo')
'foo'
And string representation of string 'foo'
is the same string 'foo'
.
Add the following style to your h3
elements:
word-wrap: break-word;
This will cause the long URLs in them to wrap. The default setting for word-wrap is normal
, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.
Nope, ThreadAbortException
is thrown by a simple Response.Redirect
<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
<input id="fileupload" name="myfile" type="file" />
<input type="submit" value="submit" id="submit" />
</form>
To upload a file, it is essential to set enctype="multipart/form-data"
on your form
You need that form type and then some php to process the file :)
You should probably check out Uploadify if you want something very customisable out of the box.
I did that once. Ultimately I found my simplified basicconfig.py adequate for my needs. You can pass in a namespace with other objects for it to reference if you need to. You can also pass in additional defaults from your code. It also maps attribute and mapping style syntax to the same configuration object.
You can install any current version of Anaconda. You can then make a conda environment with your particular needs from the documentation
conda create -n tensorflowproject python=3.5 tensorflow ipython
This command has a specific version for python and when this tensorflowproject environment gets updated it will upgrade to Python 3.5999999999 but never go to 3.6 . Then you switch to your environment using either
source activate tensorflowproject
for linux/mac or
activate tensorflowproject
on windows
Reusable method for intiCap:
public class YarlagaddaSireeshTest{
public static void main(String[] args) {
String FinalStringIs = "";
String testNames = "sireesh yarlagadda test";
String[] name = testNames.split("\\s");
for(String nameIs :name){
FinalStringIs += getIntiCapString(nameIs) + ",";
}
System.out.println("Final Result "+ FinalStringIs);
}
public static String getIntiCapString(String param) {
if(param != null && param.length()>0){
char[] charArray = param.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
return new String(charArray);
}
else {
return "";
}
}
}
phihag's answer puts each row in a single cell, while you are asking for each value to be in a separate cell. This seems to do it:
<?php
// Create a table from a csv file
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
$row = $line[0]; // We need to get the actual row (it is the first element in a 1-element array)
$cells = explode(";",$row);
echo "<tr>";
foreach ($cells as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>
The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization
header with the Bearer
authentication scheme.
This scheme is described by the RFC6750.
Example:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ
If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.
Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.
Unlike the custom JWT
scheme you mention in your question, the Bearer
one is registered at the IANA.
Concerning the Basic
and Digest
authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.
In my case it was python path issue.
django-admin dbshell
)
(venv) shakeel@workstation:~/project_path$ export PYTHONPATH=/home/shakeel/project_path
(venv) shakeel@workstation:~/project_path$ export DJANGO_SETTINGS_MODULE=my_project.settings
(venv) shakeel@workstation:~/project_path$ django-admin dbshell
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite>
otherwise python manage.py shell
works like charm.
I've recently fixed this issue and in my instance it was a file that was compressed that I was trying to read. Check the file format first. Then check that the contents are what the extension refers to.
EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?
Original Answer:
If you want to do this to run on port 80 (or want to set the env variable more permanently),
vim ~/.bash_profile
export PORT=80
sudo visudo
Defaults env_keep +="PORT"
Now when you run sudo node app.js
it should work as desired.
You can put this code to make your code work with just single line of code
<input type="file" onchange="javascript:this.form.submit()">
This will upload the file on server without clicking on submit button
I really do not see any way to really get to the number of values in an enumeration in C++. Any of the before mention solution work as long as you do not define the value of your enumerations if you define you value that you might run into situations where you either create arrays too big or too small
enum example{ test1 = -2, test2 = -1, test3 = 0, test4 = 1, test5 = 2 }
in this about examples the result would create a array of 3 items when you need an array of 5 items
enum example2{ test1 , test2 , test3 , test4 , test5 = 301 }
in this about examples the result would create a array of 301 items when you need an array of 5 items
The best way to solve this problem in the general case would be to iterate through your enumerations but that is not in the standard yet as far as I know
Use this:
SELECT * FROM Table WHERE Column LIKE '%[0-9]%'
I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.
On the Button:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
On the Server Event
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];
You can use the bind function to set the context of this
within a function.
function myFunc() {
console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"
If you are writing to a file, using a BufferedWriter
instance, use the newLine()
method of that instance. It provides a platform-independent way to write the new line in a file.
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){ }
YES. This is how you check if object is null
.
2.) I need to know if the ID contains an Int.
if(person.getId()==null){}
NO Since id
is defined as primitive int
, it will be default initialized with 0
and it will never be null
. There is no need to check primitive types, if they are null. They will never be null. If you want, you can compare against the default value 0
as if(person.getId()==0){}
.
If you're only replacing single characters, you should use strtr()
I think the root for this confusion is well explained in this wikipedia article.
While the IANA-registered MIME type for ICO files is image/vnd.microsoft.icon, it was submitted to IANA in 2003 by a third party and is not recognised by Microsoft software, which uses image/x-icon instead.
If even the inventor of the ICO format does not use the official MIME type, I will use image/x-icon
, too.
JQuery can't append elements to <svg>
(it does seem to add them in the DOM explorer, but not on the screen).
One workaround is to append an <svg>
with all of the elements that you need to the page, and then modify the attributes of the elements using .attr()
.
$('body')
.append($('<svg><circle id="c" cx="10" cy="10" r="10" fill="green" /></svg>'))
.mousemove( function (e) {
$("#c").attr({
cx: e.pageX,
cy: e.pageY
});
});
If you're using spring >= 3.0, try using Springs @Configuration
annotation to define part of the application context
@Configuration
@ImportResource("com/blah/blurk/rest-of-config.xml")
public class DaoTestConfiguration {
@Bean
public ApplicationService applicationService() {
return mock(ApplicationService.class);
}
}
If you don't want to use the @ImportResource, it can be done the other way around too:
<beans>
<!-- rest of your config -->
<!-- the container recognize this as a Configuration and adds it's beans
to the container -->
<bean class="com.package.DaoTestConfiguration"/>
</beans>
For more information, have a look at spring-framework-reference : Java-based container configuration
For some odd reason this DID NOT work (using Pandas: '0.25.1')
df[['col1', 'col2']].fillna(value=0, inplace=True)
Another solution:
subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]
Example:
df = pd.DataFrame(data={'col1':[1,2,np.nan,], 'col2':[1,np.nan,3], 'col3':[np.nan,2,3]})
output:
col1 col2 col3
0 1.00 1.00 nan
1 2.00 nan 2.00
2 nan 3.00 3.00
Apply list comp. to fillna values:
subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]
Output:
col1 col2 col3
0 1.00 1.00 nan
1 2.00 0.00 2.00
2 0.00 3.00 3.00
An Int-based pow function that computes the value directly via bit shift for base 2 in Swift 5:
func pow(base: Int, power: UInt) -> Int {
if power == 0 { return 1 }
// for base 2, use a bit shift to compute the value directly
if base == 2 { return 2 << Int(power - 1) }
// otherwise multiply base repeatedly to compute the value
return repeatElement(base, count: Int(power)).reduce(1, *)
}
(Make sure the result is within the range of Int - this does not check for the out of bounds case)
history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;
Brute but functional
Also iftop:
display bandwidth usage on an interface
iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...
All of the code above was really helpful, but none of it quite answered my own need: grep
all *.tar.gz
files in the current directory to find a pattern that is specified as an argument in a reusable script to output:
It's what I was really hoping that zgrep
could do for me and it just can't.
Here's my solution:
pattern=$1
for f in *.tar.gz; do
echo "$f:"
tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true";
done
You can also replace the tar
line with the following if you'd like to test that all variables are expanding properly with a basic echo
statement:
tar -xzf "$f" --to-command 'echo "f:`basename $TAR_FILENAME` s:'"$pattern\""
Let me explain what's going on. Hopefully, the for
loop and the echo
of the archive filename in question is obvious.
tar -xzf
: x
extract, z
filter through gzip, f
based on the following archive file...
"$f"
: The archive file provided by the for loop (such as what you'd get by doing an ls
) in double-quotes to allow the variable to expand and ensure that the script is not broken by any file names with spaces, etc.
--to-command
: Pass the output of the tar command to another command rather than actually extracting files to the filesystem. Everything after this specifies what the command is (grep
) and what arguments we're passing to that command.
Let's break that part down by itself, since it's the "secret sauce" here.
'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
First, we use a single-quote to start this chunk so that the executed sub-command (basename $TAR_FILENAME
) is not immediately expanded/resolved. More on that in a moment.
grep
: The command to be run on the (not actually) extracted files
--label=
: The label to prepend the results, the value of which is enclosed in double-quotes because we do want to have the grep
command resolve the $TAR_FILENAME
environment variable passed in by the tar
command.
basename $TAR_FILENAME
: Runs as a command (surrounded by backticks) and removes directory path and outputs only the name of the file
-Hin
: H
Display filename (provided by the label), i
Case insensitive search, n
Display line number of match
Then we "end" the first part of the command string with a single quote and start up the next part with a double quote so that the $pattern
, passed in as the first argument, can be resolved.
Realizing which quotes I needed to use where was the part that tripped me up the longest. Hopefully, this all makes sense to you and helps someone else out. Also, I hope I can find this in a year when I need it again (and I've forgotten about the script I made for it already!)
And it's been a bit a couple of weeks since I wrote the above and it's still super useful... but it wasn't quite good enough as files have piled up and searching for things has gotten more messy. I needed a way to limit what I looked at by the date of the file (only looking at more recent files). So here's that code. Hopefully it's fairly self-explanatory.
if [ -z "$1" ]; then
echo "Look within all tar.gz files for a string pattern, optionally only in recent files"
echo "Usage: targrep <string to search for> [start date]"
fi
pattern=$1
startdatein=$2
startdate=$(date -d "$startdatein" +%s)
for f in *.tar.gz; do
filedate=$(date -r "$f" +%s)
if [[ -z "$startdatein" ]] || [[ $filedate -ge $startdate ]]; then
echo "$f:"
tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
fi
done
And I can't stop tweaking this thing. I added an argument to filter by the name of the output files in the tar file. Wildcards work, too.
Usage:
targrep.sh [-d <start date>] [-f <filename to include>] <string to search for>
Example:
targrep.sh -d "1/1/2019" -f "*vehicle_models.csv" ford
while getopts "d:f:" opt; do
case $opt in
d) startdatein=$OPTARG;;
f) targetfile=$OPTARG;;
esac
done
shift "$((OPTIND-1))" # Discard options and bring forward remaining arguments
pattern=$1
echo "Searching for: $pattern"
if [[ -n $targetfile ]]; then
echo "in filenames: $targetfile"
fi
startdate=$(date -d "$startdatein" +%s)
for f in *.tar.gz; do
filedate=$(date -r "$f" +%s)
if [[ -z "$startdatein" ]] || [[ $filedate -ge $startdate ]]; then
echo "$f:"
if [[ -z "$targetfile" ]]; then
tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
else
tar -xzf "$f" --no-anchored "$targetfile" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
fi
fi
done
One option that is available is fooTable. Works great on a Responsive website and allows you to set multiple breakpoints... fooTable Link
Exits the loop if the line is empty(Improving code).
#include <stdio.h>
#include <string.h>
// The value BUFFERSIZE can be changed to customer's taste . Changes the
// size of the base array (string buffer )
#define BUFFERSIZE 10
int main(void)
{
char buffer[BUFFERSIZE];
char cChar;
printf("Enter a message: \n");
while(*(fgets(buffer, BUFFERSIZE, stdin)) != '\n')
{
// For concatenation
// fgets reads and adds '\n' in the string , replace '\n' by '\0' to
// remove the line break .
/* if(buffer[strlen(buffer) - 1] == '\n')
buffer[strlen(buffer) - 1] = '\0'; */
printf("%s", buffer);
// Corrects the error mentioned by Alain BECKER.
// Checks if the string buffer is full to check and prevent the
// next character read by fgets is '\n' .
if(strlen(buffer) == (BUFFERSIZE - 1) && (buffer[strlen(buffer) - 1] != '\n'))
{
// Prevents end of the line '\n' to be read in the first
// character (Loop Exit) in the next loop. Reads
// the next char in stdin buffer , if '\n' is read and removed, if
// different is returned to stdin
cChar = fgetc(stdin);
if(cChar != '\n')
ungetc(cChar, stdin);
// To print correctly if '\n' is removed.
else
printf("\n");
}
}
return 0;
}
Exit when Enter is pressed.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#define BUFFERSIZE 16
int main(void)
{
char buffer[BUFFERSIZE];
printf("Enter a message: \n");
while(true)
{
assert(fgets(buffer, BUFFERSIZE, stdin) != NULL);
// Verifies that the previous character to the last character in the
// buffer array is '\n' (The last character is '\0') if the
// character is '\n' leaves loop.
if(buffer[strlen(buffer) - 1] == '\n')
{
// fgets reads and adds '\n' in the string, replace '\n' by '\0' to
// remove the line break .
buffer[strlen(buffer) - 1] = '\0';
printf("%s", buffer);
break;
}
printf("%s", buffer);
}
return 0;
}
Concatenation and dinamic allocation(linked list) to a single string.
/* Autor : Tiago Portela
Email : [email protected]
Sobre : Compilado com TDM-GCC 5.10 64-bit e LCC-Win32 64-bit;
Obs : Apenas tentando aprender algoritimos, sozinho, por hobby. */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#define BUFFERSIZE 8
typedef struct _Node {
char *lpBuffer;
struct _Node *LpProxNode;
} Node_t, *LpNode_t;
int main(void)
{
char acBuffer[BUFFERSIZE] = {0};
LpNode_t lpNode = (LpNode_t)malloc(sizeof(Node_t));
assert(lpNode!=NULL);
LpNode_t lpHeadNode = lpNode;
char* lpBuffer = (char*)calloc(1,sizeof(char));
assert(lpBuffer!=NULL);
char cChar;
printf("Enter a message: \n");
// Exit when Enter is pressed
/* while(true)
{
assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
assert(lpNode->lpBuffer!=NULL);
strcpy(lpNode->lpBuffer, acBuffer);
if(lpNode->lpBuffer[strlen(acBuffer) - 1] == '\n')
{
lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
lpNode->LpProxNode = NULL;
break;
}
lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
lpNode = lpNode->LpProxNode;
assert(lpNode!=NULL);
}*/
// Exits the loop if the line is empty(Improving code).
while(true)
{
assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
assert(lpNode->lpBuffer!=NULL);
strcpy(lpNode->lpBuffer, acBuffer);
if(acBuffer[strlen(acBuffer) - 1] == '\n')
lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
if(strlen(acBuffer) == (BUFFERSIZE - 1) && (acBuffer[strlen(acBuffer) - 1] != '\n'))
{
cChar = fgetc(stdin);
if(cChar != '\n')
ungetc(cChar, stdin);
}
if(acBuffer[0] == '\n')
{
lpNode->LpProxNode = NULL;
break;
}
lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
lpNode = lpNode->LpProxNode;
assert(lpNode!=NULL);
}
printf("\nPseudo String :\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
printf("%s", lpNode->lpBuffer);
lpNode = lpNode->LpProxNode;
}
printf("\n\nMemory blocks:\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
printf("Block \"%7s\" size = %lu\n", lpNode->lpBuffer, (long unsigned)(strlen(lpNode->lpBuffer) + 1));
lpNode = lpNode->LpProxNode;
}
printf("\nConcatenated string:\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
lpBuffer = (char*)realloc(lpBuffer, (strlen(lpBuffer) + strlen(lpNode->lpBuffer)) + 1);
strcat(lpBuffer, lpNode->lpBuffer);
lpNode = lpNode->LpProxNode;
}
printf("%s", lpBuffer);
printf("\n\n");
// Deallocate memory
lpNode = lpHeadNode;
while(lpNode != NULL)
{
lpHeadNode = lpNode->LpProxNode;
free(lpNode->lpBuffer);
free(lpNode);
lpNode = lpHeadNode;
}
lpBuffer = (char*)realloc(lpBuffer, 0);
lpBuffer = NULL;
if((lpNode == NULL) && (lpBuffer == NULL))
{
printf("Deallocate memory = %s", (char*)lpNode);
}
printf("\n\n");
return 0;
}
The plugin vim-autoformat lets you format your buffer (or buffer selections) with a single command: https://github.com/Chiel92/vim-autoformat. It uses external format programs for that, with a fallback to vim's indentation functionality.
Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)
My $.02
In my case I remembered that a hole in the firewall was created for this address some time ago, so I had to set useDefaultWebProxy="false" on the binding in the config file, as if the default was to use the proxy if useDefaultWebProxy is not specified.
No, it's not possible.
Passing by reference implies that the function might change the value of the parameter. If the parameter is not provided by the caller and comes from the default constant, what is the function supposed to change?
There is no show
event in js - you need to bind your button either to the click
event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form
, you may prefer to bind the whole form to the submit
event.
Modulo arithmetic with negative operands is defined by the language designer, who might leave it to the language implementation, who might defer the definition to the CPU architecture.
I wasn't able to find a Java language definition.
Thanks Ishtar, Java Language Specification for the Remainder Operator % says that the sign of the result is the same as the sign of the numerator.
your thinking about this program below
#include <stdio.h>
#include <string.h>
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6
when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below
#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];
for(int j=0; j<=Projects-1; j++){
for(int i=0; i<=Students; i++) {
cout <<"Please give grade of student "<< j <<"in project "<< i << ":";
cin >> Grades[j][i];
}
Sum2 = Sum2 + Grades[i][j];
Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}
change to string except it only reads 1 input and throws the rest out maybe need two for loops and two pointers
#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;
char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}
int length = 0;
while(name[length] != '\0')
{
length++;
}
for(n=0; n<4; n++)
{
if (strncmp(ptr, "snit", 4) == 0)
{
cout << "you found the snitch " << ptr[i];
}
}
cout<<name <<"is"<<length<<"chars long";
}
Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:
uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)
For complete removal old Xcode 7 you should remove
/Applications/Xcode.app
/Library/Preferences/com.apple.dt.Xcode.plist
~/Library/Preferences/com.apple.dt.Xcode.plist
~/Library/Caches/com.apple.dt.Xcode
~/Library/Application Support/Xcode
~/Library/Developer/Xcode
~/Library/Developer/CoreSimulator
If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:
$('#container').text(xmlString);
Here's how you'd do it with standard DOM methods:
document.getElementById('container')
.appendChild(document.createTextNode(xmlString));
If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).
You can always do
git fetch && git merge --ff-only origin/master
and you will either get (a) no change if you have uncommitted changes that conflict with upstream changes or (b) the same effect as stash/pull/apply: a rebase to put you on the latest changes from HEAD and your uncommitted changes left as is.
You can use .indexOf()
and .substr()
like this:
var val = $("input").val();
var myString = val.substr(val.indexOf("?") + 1)
You can test it out here. If you're sure of the format and there's only one question mark, you can just do this:
var myString = $("input").val().split("?").pop();
Works fine for me
See example here. http://jsfiddle.net/blowsie/c6VAy/
Make sure your jquery is inside $(document).ready
function or similar.
Also you can improve your code by using jquery data
$('#amount').data('min','1000');
<div id="amount" data-min=""></div>
Update,
A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/
You can do this conversion with the OpenSSL library
Windows binaries can be found here:
http://www.slproweb.com/products/Win32OpenSSL.html
Once you have the library installed, the command you need to issue is:
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
Change the backend to automatic:
Tools > preferences > IPython console > Graphics > Graphics backend > Backend: Automatic
Then close and open Spyder.
Here is a solution to get the max value in about 99% of runs (change the 0.01 to get a better result):
public static double getMax(double[] vals){
final double[] max = {Double.NEGATIVE_INFINITY};
IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
.forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);
return max[0];
}
(Not completely serious)
You could use @> operator to do this something like
SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';
You can also use Chocolatey.
Having it installed, just run:
choco install make
When it finishes, it is installed and available in Git for Bash / MinGW.
Three ways you can do that:-
Approach 1:-
// using spread ...
let obj1 = {
...obj2
};
Approach2:-
// using Object.assign() method
let obj1 = Object.assign({}, obj2);
Approach3:-
// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));
Quite old topic. But I want to give my 2 cents...
I've slightly modified tomasz86 solution, to look in the old style "Shell Folders" instead of "User Shell Folders", so i don't need to expand the envvar %userprofile%
Also there is no dependency from powershell/vbscript/etc....
for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"`) do if %%A==REG_SZ set desktopdir=%%B
echo %desktopdir%
Hope it helps.
Since no one mentioned I am adding on it, When you pass a object to a function in c++ the default copy constructor of the object is called if you dont have one which creates a clone of the object and then pass it to the method, so when you change the object values that will reflect on the copy of the object instead of the original object, that is the problem in c++, So if you make all the class attributes to be pointers, then the copy constructors will copy the addresses of the pointer attributes , so when the method invocations on the object which manipulates the values stored in pointer attributes addresses, the changes also reflect in the original object which is passed as a parameter, so this can behave same a Java but dont forget that all your class attributes must be pointers, also you should change the values of pointers, will be much clear with code explanation.
Class CPlusPlusJavaFunctionality {
public:
CPlusPlusJavaFunctionality(){
attribute = new int;
*attribute = value;
}
void setValue(int value){
*attribute = value;
}
void getValue(){
return *attribute;
}
~ CPlusPlusJavaFuncitonality(){
delete(attribute);
}
private:
int *attribute;
}
void changeObjectAttribute(CPlusPlusJavaFunctionality obj, int value){
int* prt = obj.attribute;
*ptr = value;
}
int main(){
CPlusPlusJavaFunctionality obj;
obj.setValue(10);
cout<< obj.getValue(); //output: 10
changeObjectAttribute(obj, 15);
cout<< obj.getValue(); //output: 15
}
But this is not good idea as you will be ending up writing lot of code involving with pointers, which are prone for memory leaks and do not forget to call destructors. And to avoid this c++ have copy constructors where you will create new memory when the objects containing pointers are passed to function arguments which will stop manipulating other objects data, Java does pass by value and value is reference, so it do not require copy constructors.
If you only need to look at the cells that are in use you can use:
sub IterateCells()
For Each Cell in ActiveSheet.UsedRange.Cells
'do some stuff
Next
End Sub
that will hit everything in the range from A1 to the last cell with data (the bottom right-most cell)
Try this:
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = 'dodge', stat='identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)
You can use something like this.
var {height, width} = Dimensions.get('window'); var textFontSize = width * 0.03;
inputText: {
color : TEXT_COLOR_PRIMARY,
width: '80%',
fontSize: textFontSize
}
Hope this helps without installing any third party libraries.
With the help of ceztko's answer I wrote this little helper function to make my life easier:
function gpu()
{
if git rev-parse --abbrev-ref --symbolic-full-name @{u} > /dev/null 2>&1; then
git push origin HEAD
else
git push -u origin HEAD
fi
}
It pushes the current branch to origin and also sets the remote tracking branch if it hasn't been setup yet.
If you want to keep the row with the lowest id
value:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MIN(n.id)
FROM NAMES n
GROUP BY n.name) x)
If you want the id
value that is the highest:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MAX(n.id)
FROM NAMES n
GROUP BY n.name) x)
The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.
You can use DateValue
to convert your string to a date in this instance
Dim c As Range
For Each c In ActiveSheet.UsedRange.columns("A").Cells
c.Value = DateValue(c.Value)
Next c
It can convert yyyy-mm-dd
format string directly into a native Excel date value.
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
It's quite easy and efficient to use Excel as a reporting tool for Access data.
A quick "non programming" approach is to set a List or a Pivot Table, linked to your External Data source. But that's out of scope for Stackoverflow.
A programmatic approach can be very simple:
strProv = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SourceFile & ";"
Set cnn = New ADODB.Connection
cnn.Open strProv
Set rst = New ADODB.Recordset
rst.Open strSql, cnn
myDestRange.CopyFromRecordset rst
That's it !
It's a simple and short example of using es6 without jQuery.
import React, { Component } from 'react';
export default class CreateContact extends Component {
state = {
windowHeight: undefined,
windowWidth: undefined
}
handleResize = () => this.setState({
windowHeight: window.innerHeight,
windowWidth: window.innerWidth
});
componentDidMount() {
this.handleResize();
window.addEventListener('resize', this.handleResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize)
}
render() {
return (
<span>
{this.state.windowWidth} x {this.state.windowHeight}
</span>
);
}
}
hooks
import React, { useEffect, useState } from "react";
let App = () => {
const [windowWidth, setWindowWidth] = useState(0);
const [windowHeight, setWindowHeight] = useState(0);
let resizeWindow = () => {
setWindowWidth(window.innerWidth);
setWindowHeight(window.innerHeight);
};
useEffect(() => {
resizeWindow();
window.addEventListener("resize", resizeWindow);
return () => window.removeEventListener("resize", resizeWindow);
}, []);
return (
<div>
<span>
{windowWidth} x {windowHeight}
</span>
</div>
);
};
In this scenario, since you are working with inline
-level elements, you could add vertical-align: middle
to the span
elements for vertical centering:
.nav-text {
vertical-align: middle;
}
Alternatively, you could set the display
of the parent element to flex
and set align-items
to center
for vertical centering:
.menu {
display: flex;
align-items: center;
}