https://fettblog.eu/gulp-4-parallel-and-series/
Because
gulp.task(name, deps, func)
was replaced by gulp.task(name, gulp.{series|parallel}(deps, func))
.
You are using the latest version of gulp but older code. Modify the code or downgrade.
updated
might be what you're looking for. https://vuejs.org/v2/api/#updated
I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.
The trick is to use --trustedhost
to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.
So in a nutshell, you should do:
pip install python-certifi-win32 -trustedhost pypi.org
and after that you should be good to go
select advanced options when Write a message, and choose sound activated
this is My solution
CGRect
Can be simply created using an instance of a CGPoint
or CGSize
, thats given below.
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))
// Or
let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
Or if we want to specify each value in CGFloat
or Double
or Int
, we can use this method.
let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // CGFloat, Double, Int
CGPoint
Can be created like this.
let point = CGPoint(x: 0,y :0) // CGFloat, Double, Int
CGSize
Can be created like this.
let size = CGSize(width: 100, height: 100) // CGFloat, Double, Int
Also size and point with 0 as the values, it can be done like this.
let size = CGSize.zero // width = 0, height = 0
let point = CGPoint.zero // x = 0, y = 0, equal to CGPointZero
let rect = CGRect.zero // equal to CGRectZero
CGRectZero
& CGPointZero
replaced with CGRect.zero
& CGPoint.zero
in Swift 3.0
.
Try using #selector to call the IBaction.In the cellforrowatindexpath
cell.editButton.tag = indexPath.row
cell.editButton.addTarget(self, action: #selector(editButtonPressed), for: .touchUpInside)
This way you can access the indexpath inside the method editButtonPressed
func editButtonPressed(_ sender: UIButton) {
print(sender.tag)//this value will be same as indexpath.row
}
sklearn.tree.export_graphviz
doesn't return anything, and so by default returns None
.
By doing dotfile = tree.export_graphviz(...)
you overwrite your open file object, which had been previously assigned to dotfile
, so you get an error when you try to close the file (as it's now None
).
To fix it change your code to
...
dotfile = open("D:/dtree2.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
...
ZBar
Pre-requisites:
choco install zbar
pip install pyzbar
To decode:
from PIL import Image
from pyzbar import pyzbar
img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)
Alternatively, you can also try using ZBarLight
by setting it up as mentioned here:
https://pypi.org/project/zbarlight/
It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS
version and any Simulator. You will have to use device for testing camera purpose.
Shimi_tap's answer is the right way to fix the problem. If you want to use old merger tool you can add this to build.gradle file
android { useOldManifestMerger true }
Update for iOS 10 / Swift 3.0
No longer a function, now a property...
override var prefersStatusBarHidden: Bool {
return true
}
What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry_page function:
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
title = request.form['blog_title']
post = request.form['blog_main']
post_entry = models.BlogPost(date = date, title = title, post = post)
db.session.add(post_entry)
db.session.commit()
return redirect(url_for('database'))
else:
return render_template('entry.html')
@app.route('/database', methods=['GET', 'POST'])
def database():
query = []
for i in session.query(models.BlogPost):
query.append((i.title, i.post, i.date))
return render_template('database.html', query = query)
I had the same problem when setting the center of the map with map.setCenter()
. Using Number()
solved for me. Had to use parseFloat
to truncate the data.
code snippet:
var centerLat = parseFloat(data.lat).toFixed(0);
var centerLng = parseFloat(data.long).toFixed(0);
map.setCenter({
lat: Number(centerLat),
lng: Number(centerLng)
});
Private Sub CommandButton1_Click()
Dim Data As Object, Employee As Object
Application.ScreenUpdating = False
Set Data = ThisWorkbook.Sheets("Data")
Set Employee = ThisWorkbook.Sheets("Employee Names")
Data.Range("AK1").Value = "Lookup"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"
Application.DisplayAlerts = False
Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
Data.Range("AK:AK").Delete
Data.AutoFilterMode = False
'Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"
Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")
Dr.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
'DrfeeRequested.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")
Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")
Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"
Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")
Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
TodayDT = Format(Now())
Weekdy = Weekday(Now())
If Weekdy = 2 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 3 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 4 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 5 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 6 Then
LastTwoDays = Now() - Weekday(Now(), 3)
Else
MsgBox "Today Satuarday OR Sunday Data is not Available"
End If
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"
Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")
Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"
Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")
Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.Range("A1").AutoFilter
End Sub
Private Sub CommandButton2_Click()
Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear
MsgBox "Please paste new data in data sheet"
End Sub
My code was out of void setup() or void loop() in Arduino.
I was able to build a library source code to compiled .jar
file, using approach from this solution:
https://stackoverflow.com/a/19037807/1002054
Here is the breakdown of what I did:
In may case it was a Volley library
I used Android Studio 0.3.7. I've encountered some issues during that step, namely I had to copy gradle
folder from new android project before I was able to import Volley library source code, this may vary depending on source code you use.
build.gradle
file// If your module is a library project, this is needed
//to properly recognize 'android-library' plugin
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.3'
}
}
apply plugin: 'android-library'
android {
compileSdkVersion 17
buildToolsVersion = 17
sourceSets {
main {
// Here is the path to your source code
java {
srcDir 'src'
}
}
}
}
// This is the actual solution, as in https://stackoverflow.com/a/19037807/1002054
task clearJar(type: Delete) {
delete 'build/libs/myCompiledLibrary.jar'
}
task makeJar(type: Copy) {
from('build/bundles/release/')
into('build/libs/')
include('classes.jar')
rename ('classes.jar', 'myCompiledLibrary.jar')
}
makeJar.dependsOn(clearJar, build)
gradlew makeJar
command from your project root.I my case I had to copy gradlew.bat
and gradle
files from new android project into my library project root.
You should find your compiled library file myCompiledLibrary.jar
in build\libs
directory.
I hope someone finds this useful.
Edit:
Althought this works, you will encounter duplicate library exception while compiling a project with multiple modules, where more than one module (including application module) depends on the same jar
file (eg. modules have own library directory, that is referenced in build.gradle
of given module).
In case where you need to use single library in more then one module, I would recommend using this approach: Android gradle build and the support library
You can pass values by using the below .
@Html.ActionLink("About", "About", "Home",new { name = ViewBag.Name }, htmlAttributes:null )
Controller:
public ActionResult About(string name)
{
ViewBag.Message = "Your application description page.";
ViewBag.NameTransfer = name;
return View();
}
And the URL looks like
http://localhost:50297/Home/About?name=My%20Name%20is%20Vijay
It simply wants the ASP control on your ASPX page. I usually place mine right under the tag, or inside first Content area in the master's body (if your using a master page)
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<div>
[Content]
</div>
</form>
</body>
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds()
at the wrong time may leave you with a result like in the Q.
The best way I found is to place the call in an idle handler like this:
google.maps.event.addListenerOnce(map, 'idle', function() {
map.fitBounds(markerBounds);
});
Your error is also shown when trying to access the sizeof()
of an non-initialized extern array:
extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'
Note that you would get an array size missing
error without the extern
keyword.
I am not sure, but might be what you want:
var c = 0;
function setBgPosition()
{
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run()
{
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<=numbers.length)
{
setTimeout(run, 200);
}
else
{
Ext.get('common-spinner').setStyle('background-position', numbers[0] + 'px 0px');
}
}
setTimeout(run, 200);
}
setBgPosition();
UIView's pointInside:withEvent: could be a good solution. Will return a boolean value indicating wether or not the given CGPoint is in the UIView instance you are using. Example:
UIView *aView = [UIView alloc]initWithFrame:CGRectMake(0,0,100,100);
CGPoint aPoint = CGPointMake(5,5);
BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil];
GNU linker, in my case companion of GCC 8.1.0, well detects not re-declared pure virtual methods, but above certain complexity of class design it fails to identify missing implementation of methods and answers with a flat "V-Table Missing",
or even tends to report missing implementation, in spite it is there.
The only solution then is to verify consistency of declaration of implementation manually, method by method.
swift 2 version of the @MS AppTech answer
func handlePan(panGest : UIPanGestureRecognizer) {
let velocity : CGPoint = panGest.velocityInView(self.view);
let magnitude : CGFloat = CGFloat(sqrtf((Float(velocity.x) * Float(velocity.x)) + (Float(velocity.y) * Float(velocity.y))));
let slideMult :CGFloat = magnitude / 200;
//NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
let slideFactor : CGFloat = 0.1 * slideMult; // Increase for more of a slide
var finalPoint : CGPoint = CGPointMake(panGest.view!.center.x + (velocity.x * slideFactor),
panGest.view!.center.y + (velocity.y * slideFactor));
finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height);
UIView.animateWithDuration(Double(slideFactor*2), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
panGest.view!.center = finalPoint;
}, completion: nil)
}
I use this - it never fails:
startingpoint = 'blah'
if sys.argv[1:]:
startingpoint = sys.argv[1]
"The list are variables/paramaters that is pre-defined as comma separated lists". Do you mean that your query is actually
UPDATE tab1 SET budgpost_gr1=
CASE WHEN (budgpost in ('1001,1012,50055')) THEN 'BP_GR_A'
WHEN (budgpost in ('5,10,98,0')) THEN 'BP_GR_B'
WHEN (budgpost in ('11,876,7976,67465'))
ELSE 'Missing' END`
If so, you need a function to take a string and parse it into a list of numbers.
create type tab_num is table of number;
create or replace function f_str_to_nums (i_str in varchar2) return tab_num is
v_tab_num tab_num := tab_num();
v_start number := 1;
v_end number;
v_delim VARCHAR2(1) := ',';
v_cnt number(1) := 1;
begin
v_end := instr(i_str||v_delim,v_delim,1, v_start);
WHILE v_end > 0 LOOP
v_cnt := v_cnt + 1;
v_tab_num.extend;
v_tab_num(v_tab_num.count) :=
substr(i_str,v_start,v_end-v_start);
v_start := v_end + 1;
v_end := instr(i_str||v_delim,v_delim,v_start);
END LOOP;
RETURN v_tab_num;
end;
/
Then you can use the function like so:
select column_id,
case when column_id in
(select column_value from table(f_str_to_nums('1,2,3,4'))) then 'red'
else 'blue' end
from user_tab_columns
where table_name = 'EMP'
I use Handler
with Looper.getMainLooper()
. It worked fine for me.
Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
// Any UI task, example
textView.setText("your text");
}
};
handler.sendEmptyMessage(1);
Toolbear74 is right log4j.XML is required.
In order to get the XML to validate the <param>
tags need to be BEFORE the <rollingPolicy>
I suggest setting a logging threshold <param name="threshold" value="info"/>
When Creating a Log4j.xml file don't forget to to copy the log4j.dtd into the same location.
Here is an example:
<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<!-- Daily Rolling File Appender that compresses old files -->
<appender name="file" class="org.apache.log4j.rolling.RollingFileAppender" >
<param name="threshold" value="info"/>
<rollingPolicy name="file"
class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern"
value="${catalina.base}/logs/myapp.log.%d{yyyy-MM-dd}.gz"/>
<param name="ActiveFileName" value="${catalina.base}/logs/myapp.log"/>
</rollingPolicy>
<layout class="org.apache.log4j.EnhancedPatternLayout" >
<param name="ConversionPattern"
value="%d{ISO8601} %-5p - %-26.26c{1} - %m%n" />
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="file" />
</root>
</log4j:configuration>
Considering that your setting a FileNamePattern
and an ActiveFileName
I think that setting a File
property is redundant and possibly even erroneous
Try renaming your log4j.properties and dropping in a log4j.xml similar to my example and see what happens.
Let's start with a quote from the virtual machine spec:
Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.
This may not occur - This is a hint, that there's something special about String
objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:
1: a := "one"
--> if(pool[hash("one")] == null) // true
pool[hash("one") --> "one"]
return pool[hash("one")]
2: b := "one"
--> if(pool[hash("one")] == null) // false, "one" already in pool
pool[hash("one") --> "one"]
return pool[hash("one")]
So in this case, variables a
and b
hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true
.
This is not the case if we use the constructor:
1: a := "one"
2: b := new String("one")
Again, "one"
is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false
So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).
As programmers we don't have to care much about the String pool, as long as we keep in mind:
(a == b) && (a.equals(b))
may be true
or false
(always use equals
to compare Strings)char[]
of a String (as you don't know who is actualling using that String)Nothing wrong with that implementation. You might give the yield
keyword a shot, see how you like it:
private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
{
foreach (DataRow row in dataTable.Rows)
{
yield return new TankReading
{
TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
TankID = Convert.ToInt32(row["TankID"]),
ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
ReadingInches = Convert.ToInt32(row["ReadingInches"]),
MaterialNumber = row["MaterialNumber"].ToString(),
EnteredBy = row["EnteredBy"].ToString(),
ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
MaterialID = Convert.ToInt32(row["MaterialID"]),
Submitted = Convert.ToBoolean(row["Submitted"]),
};
}
}
Also the AsEnumerable
isn't necessary, as List<T>
is already an IEnumerable<T>
Simply add "?callback=?" (or "&callback=?") to your url:
$.getJSON({
url:myUrl + "?callback=?",
data: myData,
success: function(data){
/*My function stuff*/
}
});
When doing the calls (with everything else set properly for cross-domain, as above) this will trigger the proper JSONP formatting.
More in-depth explanation can be found in the answer here.
vtable
?It might be useful to know what the error message is talking about before trying to fix it. I'll start at a high level, then work down to some more details. That way people can skip ahead once they are comfortable with their understanding of vtables. …and there goes a bunch of people skipping ahead right now. :) For those sticking around:
A vtable is basically the most common implementation of polymorphism in C++. When vtables are used, every polymorphic class has a vtable somewhere in the program; you can think of it as a (hidden) static
data member of the class. Every object of a polymorphic class is associated with the vtable for its most-derived class. By checking this association, the program can work its polymorphic magic. Important caveat: a vtable is an implementation detail. It is not mandated by the C++ standard, even though most (all?) C++ compilers use vtables to implement polymorphic behavior. The details I am presenting are either typical or reasonable approaches. Compilers are allowed to deviate from this!
Each polymorphic object has a (hidden) pointer to the vtable for the object's most-derived class (possibly multiple pointers, in the more complex cases). By looking at the pointer, the program can tell what the "real" type of an object is (except during construction, but let's skip that special case). For example, if an object of type A
does not point to the vtable of A
, then that object is actually a sub-object of something derived from A
.
The name "vtable" comes from "virtual function table". It is a table that stores pointers to (virtual) functions. A compiler chooses its convention for how the table is laid out; a simple approach is to go through the virtual functions in the order they are declared within class definitions. When a virtual function is called, the program follows the object's pointer to a vtable, goes to the entry associated with the desired function, then uses the stored function pointer to invoke the correct function. There are various tricks for making this work, but I won't go into those here.
vtable
generated?A vtable is automatically generated (sometimes called "emitted") by the compiler. A compiler could emit a vtable in every translation unit that sees a polymorphic class definition, but that would usually be unnecessary overkill. An alternative (used by gcc, and probably by others) is to pick a single translation unit in which to place the vtable, similar to how you would pick a single source file in which to put a class' static data members. If this selection process fails to pick any translation units, then the vtable becomes an undefined reference. Hence the error, whose message is admittedly not particularly clear.
Similarly, if the selection process does pick a translation unit, but that object file is not provided to the linker, then the vtable becomes an undefined reference. Unfortunately, the error message can be even less clear in this case than in the case where the selection process failed. (Thanks to the answerers who mentioned this possibility. I probably would have forgotten it otherwise.)
The selection process used by gcc makes sense if we start with the tradition of devoting a (single) source file to each class that needs one for its implementation. It would be nice to emit the vtable when compiling that source file. Let's call that our goal. However, the selection process needs to work even if this tradition is not followed. So instead of looking for the implementation of the entire class, let's look for the implementation of a specific member of the class. If tradition is followed – and if that member is in fact implemented – then this achieves the goal.
The member selected by gcc (and potentially by other compilers) is the first non-inline virtual function that is not pure virtual. If you are part of the crowd that declares constructors and destructors before other member functions, then that destructor has a good chance of being selected. (You did remember to make the destructor virtual, right?) There are exceptions; I'd expect that the most common exceptions are when an inline definition is provided for the destructor and when the default destructor is requested (using "= default
").
The astute might notice that a polymorphic class is allowed to provide inline definitions for all of its virtual functions. Doesn't that cause the selection process to fail? It does in older compilers. I've read that the latest compilers have addressed this situation, but I do not know relevant version numbers. I could try looking this up, but it's easier to either code around it or wait for the compiler to complain.
In summary, there are three key causes of the "undefined reference to vtable" error:
These causes are by themselves insufficient to cause the error on their own. Rather, these are what you would address to resolve the error. Do not expect that intentionally creating one of these situations will definitely produce this error; there are other requirements. Do expect that resolving these situations will resolve this error.
(OK, number 3 might have been sufficient when this question was asked.)
Welcome back people skipping ahead! :)
= 0
") and whose definition you provide (not "= default
").
Example
The details of what to do can vary, and sometimes branch off into separate questions (like What is an undefined reference/unresolved external symbol error and how do I fix it?). I will, though, provide an example of what to do in a specific case that might befuddle newer programmers.
Step 1 mentions modifying your class so that it has a function of a certain type. If the description of that function went over your head, you might be in the situation I intend to address. Keep in mind that this is a way to accomplish the goal; it is not the only way, and there easily could be better ways in your specific situation. Let's call your class A
. Is your destructor declared (in your class definition) as either
virtual ~A() = default;
or
virtual ~A() {}
? If so, two steps will change your destructor into the type of function we want. First, change that line to
virtual ~A();
Second, put the following line in a source file that is part of your project (preferably the file with the class implementation, if you have one):
A::~A() {}
That makes your (virtual) destructor non-inline and not generated by the compiler. (Feel free to modify things to better match your code formatting style, such as adding a header comment to the function definition.)
I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path
C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
returns
'C:\Documents' is not recognized as an internal or external command....
There's your whole problem. CMD doesn't understand spaces inside of filenames from the command line, so it thinks you're trying to pass
and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
as parameters to the
"C:\Documents"
program.
You need to quote it to run a batch file with spaces in the path:
> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"
would have worked.
'#'+Math.random().toString(16).slice(-3) // three-numbers format aka #f3c
'#'+Math.random().toString(16).slice(-6) // six-number format aka #abc123
With that code you load the file in memory (as a big string) and then you read that string line by line.
By using Mid$() and InStr() you actually read the "file" twice but since it's in memory, there is no problem.
I don't know if VB's String has a length limit (probably not) but if the text files are hundreds of megabyte in size it's likely to see a performance drop, due to virtual memory usage.
Please use
.FirstOrDefault()
because if in the first row of the result there is no info this instruction goes to the default info.
NSLog(@"%@", CGRectCreateDictionaryRepresentation(rect));
This is similar to Alex's but does it in log time instead of linear, and takes a maxHeight parameter.
jQuery.fn.ellipsis = function(text, maxHeight) {
var element = $(this);
var characters = text.length;
var step = text.length / 2;
var newText = text;
while (step > 0) {
element.html(newText);
if (element.outerHeight() <= maxHeight) {
if (text.length == newText.length) {
step = 0;
} else {
characters += step;
newText = text.substring(0, characters);
}
} else {
characters -= step;
newText = newText.substring(0, characters);
}
step = parseInt(step / 2);
}
if (text.length > newText.length) {
element.html(newText + "...");
while (element.outerHeight() > maxHeight && newText.length >= 1) {
newText = newText.substring(0, newText.length - 1);
element.html(newText + "...");
}
}
};
Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
And the handler to show the results in your UI:
private class GeocoderHandler extends Handler {
@Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}
Don't forget to put the following permission in your Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I think you'll have to import the project via the file->import wizard:
http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse
It's not the last step, but it will start you on your way.
I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).
Object refers to class and instance refers to an object.In other words instance is a copy of an object with particular values in it.
Using bash to look for a process with the current script's name. No extra file.
import commands
import os
import time
import sys
def stop_if_already_running():
script_name = os.path.basename(__file__)
l = commands.getstatusoutput("ps aux | grep -e '%s' | grep -v grep | awk '{print $2}'| awk '{print $2}'" % script_name)
if l[1]:
sys.exit(0);
To test, add
stop_if_already_running()
print "running normally"
while True:
time.sleep(3)
I wrote extension method
public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
var s = new StringBuilder();
for (var i = 0; i < matrix.GetLength(0); i++)
{
for (var j = 0; j < matrix.GetLength(1); j++)
{
s.Append(matrix[i, j]).Append(delimiter);
}
s.AppendLine();
}
return s.ToString();
}
To use just call the method
results.ToMatrixString();
I've used something like this with a Bash shell on Ubuntu 12.04 (LTS):
To append a new line with tab,second when first is matched:
sed -i '/first/a \\t second' filename
To replace first with tab,second:
sed -i 's/first/\\t second/g' filename
Here is the VB.
Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())
In my case because I assigned the post data to the header, this is how I get it:
protected void Page_Load(object sender, EventArgs e){
...
postValue = Request.Headers["Key"];
This is how I attached the value and key to the POST
:
var request = new NSMutableUrlRequest(url){
HttpMethod = "POST",
Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);
If you add the android:theme="@style/Theme.AppCompat.Light"
to <application>
in AndroidManifest.xml file, problem is solving.
If you use virtual environment, pip freeze > requirements.txt
just fine. IF NOT, pigar will be a good choice for you.
By the way, I do not ensure it will work with 2.6.
UPDATE:
Pipenv or other tools is recommended for improving your development flow.
For Python 3 use below
pip3 freeze > requirements.txt
Can you try this,
$ch = curl_init($url);
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo rm -rf /var/lib/mysql
I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!
For me, I just changed the selinux from enforcing to permissive and then I was able to start nginx without any error.
Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.
There is no difference ...
So principially you could use both (one at a time !-)
But for the sake of readability and for the cleanliness of the html-code I always prefer the window.onload !o]
If you don't want to download an archive you can use GitHub Pages to render this.
gh-pages
branch (if one already exists, remove it and create a new one based off master
).http://
username
.github.io/
repo
`In code:
git clone [email protected]:username/repo.git
cd repo
git branch gh-pages
# Might need to do this first: git branch -D gh-pages
git push -u origin gh-pages # Push the new branch back to github
Go to http://username.github.io/repo
I have had the same problem as noted above. I could not get Eclipse to install because of Java incompatibilities. The sequence I followed goes like this:
This took hours of my time. I hope this proves useful.
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
I successfully use the following method in one file,
But come up with exactly the same error again... Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
You can create a .htaccess file for the folder, wich should have denied access with
Deny from all
or you can redirect to a custom 404 page
Redirect /includes/ 404.html
I also had the same issue. I've fixed it by using the following code.
<Button Width="30" Margin="0,5" HorizontalAlignment="Stretch" Click="OnSearch" >
<DockPanel>
<Image Source="../Resources/Back.jpg"/>
</DockPanel>
</Button>
Note: Make sure the build action of the image in the property window, should be Resource
.
Using -replace
$string = '% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8.G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %'
$program = $string -replace '^%\sO\d{4}\((.+?)\).+$','$1'
$program
SUB RAD MSD 50R III
var params = { width:1680, height:1050 };_x000D_
var str = jQuery.param( params );_x000D_
_x000D_
console.log(str)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
it'matter of *unix permissions, gain root acces, for example by typing
sudo su
[then type your password]
and try to do what you have to do
Ask your DBA about auditing. He can start an audit with a simple command like :
AUDIT INSERT ON user.table
Then you can query the table USER_AUDIT_OBJECT to determine if there has been an insert on your table since the last export.
google for Oracle auditing for more info...
<activity
android:name="MyBookActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.ALTERNATIVE" />
</intent-filter>
</activity>
where is your dot before MyBookActivity?
For your case, you can directly use JPA methods. That code is like bellow :
Containing: select ... like %:place%
List<Registration> findByPlaceContainingIgnoreCase(String place);
here, IgnoreCase will help you to search item with ignoring the case.
Using @Query in JPQL :
@Query("Select registration from Registration registration where
registration.place LIKE %?1%")
List<Registration> findByPlaceContainingIgnoreCase(String place);
Here are some related methods:
Like findByPlaceLike
… where x.place like ?1
StartingWith findByPlaceStartingWith
… where x.place like ?1 (parameter bound with appended %)
EndingWith findByPlaceEndingWith
… where x.place like ?1 (parameter bound with prepended %)
Containing findByPlaceContaining
… where x.place like ?1 (parameter bound wrapped in %)
More info, view this link , this link and this
Hope this will help you :)
import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)
nx.draw(g,with_labels=True)
plt.draw()
plt.show()
This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.
Note: It's just a simple representation. Weighted Edges could be added like
g.add_edges_from([(1,2),(2,5)], weight=2)
and hence plotted again.
Do not use regular expressions to parse HTML.
But if you ever need to find all regexp matches in a string, use the findall
function.
import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)
# Output: ['Form 1', 'Form 2']
You would write a comparator class, for example:
struct CompareAge {
bool operator()(Person const & p1, Person const & p2) {
// return "true" if "p1" is ordered before "p2", for example:
return p1.age < p2.age;
}
};
and use that as the comparator argument:
priority_queue<Person, vector<Person>, CompareAge>
Using greater
gives the opposite ordering to the default less
, meaning that the queue will give you the lowest value rather than the highest.
Check the node version using node -v
.
Check the npm version using npm -v
. If these commands gave you version number you are good to go with NodeJs
development
Time to test node
Create a Directory using mkdir NodeJs
. Inside the NodeJs
folder create a file using touch index.js
. Open your index.js
either using vi
or in your favourite text editor. Type in console.log('Welcome to NodesJs.')
and save it. Navigate back to your saved file and type node index.js
. If you see Welcome to NodesJs.
you did a nice job and you are up with NodeJs.
void DisplayBinary(int n)
{
int arr[8];
int top =-1;
while (n)
{
if (n & 1)
arr[++top] = 1;
else
arr[++top] = 0;
n >>= 1;
}
for (int i = top ; i > -1;i--)
{
printf("%d",arr[i]);
}
printf("\n");
}
If the directory you wish to save to is a sub-directory of your working directory, simply specify the relative path before your file name:
fig.savefig('Sub Directory/graph.png')
If you wish to use an absolute path, import the os module:
import os
my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
...
fig.savefig(my_path + '/Sub Directory/graph.png')
If you don't want to worry about the leading slash in front of the sub-directory name, you can join paths intelligently as follows:
import os
my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
my_file = 'graph.png'
...
fig.savefig(os.path.join(my_path, my_file))
For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.
I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.
If you don't want to change to numeric you can try this.
> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6
The most of the above given examples create a problem when a year has 53 weeks (like 2020). So every fourth year you will experience a week difference. This code does not:
$thisYear = "2020";
$thisDate = "2020-04-24"; //or any other custom date
$weeknr = date("W", strtotime($thisDate)); //when you want the weeknumber of a specific week, or just enter the weeknumber yourself
$tempDatum = new DateTime();
$tempDatum->setISODate($thisYear, $weeknr);
$tempDatum_start = $tempDatum->format('Y-m-d');
$tempDatum->setISODate($thisYear, $weeknr, 7);
$tempDatum_end = $tempDatum->format('Y-m-d');
echo $tempDatum_start //will output the date of monday
echo $tempDatum_end // will output the date of sunday
Using ranking method.
SELECT @rn := CASE WHEN @prev_grp <> groupa THEN 1 ELSE @rn+1 END AS rn,
@prev_grp :=groupa,
person,age,groupa
FROM users,(SELECT @rn := 0) r
HAVING rn=1
ORDER BY groupa,age DESC,person
This sql can be explained as below,
select * from users, (select @rn := 0) r order by groupa, age desc, person
@prev_grp is null
@rn := CASE WHEN @prev_grp <> groupa THEN 1 ELSE @rn+1 END
this is a three operator expression
like this, rn = 1 if prev_grp != groupa else rn=rn+1
having rn=1 filter out the row you need
I wanted to match a string that ends with ".*" For this I had to use the following:
"^.*\\.\\*$"
Kinda silly if you think about it :D Heres what it means. At the start of the string there can be any character zero or more times followed by a dot "." followed by a star (*) at the end of the string.
I hope this comes in handy for someone. Thanks for the backslash thing to Fabian.
PYTHONPATH ends up in sys.path, which you can modify at runtime.
import sys
sys.path += ["whatever"]
I was facing same issue so I have reinstall MySQL 8 with different Authentication Method "Use Legacy Authentication Method (Retain MySQL 5.x compatibility)" then work properly.
Choose Second Method of Authentication while installing.
Try
switch($value) {
case 1:
case 2:
echo "the value is either 1 or 2";
break;
}
.py
: This is normally the input source code that you've written..pyc
: This is the compiled bytecode. If you import a module, python will build a *.pyc
file that contains the bytecode to make importing it again later easier (and faster)..pyo
: This was a file format used before Python 3.5 for *.pyc
files that were created with optimizations (-O
) flag. (see the note below).pyd
: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dllAlso for some further discussion on .pyc
vs .pyo
, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)
- When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
- Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only
__doc__
strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.- A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
- When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.
Note:
On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo
files.
This means that .pyc
files represent both unoptimized and optimized bytecode.
Use the String.split()
var array = string.split(',');
for centos6.3
ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | awk 'BEGIN {FS=":"} {print $2}'
I wanted to specify two points which kept causing me problems.
Another trick not yet mentioned is to have the class which implements a property (e.g. Foo
of type Bar
) also define a delegate delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);
and implement a method ActOnFoo<TX1>(ref Bar it, ActByRef<Bar,TX1> proc, ref TX1 extraParam1)
(and possibly versions for two and three "extra parameters" as well) which will pass its internal representation of Foo
to the supplied procedure as a ref
parameter. This has a couple of big advantages over other methods of working with the property:
Passing things be ref
is an excellent pattern; too bad it's not used more.
Short answer:
StandardOutput=file:/var/log1.log
StandardError=file:/var/log2.log
If you don't want the files to be cleared every time the service is run, use append instead:
StandardOutput=append:/var/log1.log
StandardError=append:/var/log2.log
There is no inbuilt support for the style change event in jQuery or in java script. But jQuery supports to create custom event and listen to it but every time there is a change, you should have a way to trigger it on yourself. So it will not be a complete solution.
You can use re.escape():
re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.
If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_
).
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
application
because .js
-Files aren't something a user wants to read but something that should get executed.
2021 Update...
Bootstrap 5 (beta)
For aligning within a flexbox div or row
...
ml-auto
is now ms-auto
mr-auto
is now me-auto
Bootstrap 4+
pull-right
is now float-right
text-right
is the same as 3.x, and works for inline elementsfloat-*
and text-*
are responsive for different alignment at different widths (ie: float-sm-right
)The flexbox utils (eg:justify-content-between
) can also be used for alignment:
<div class="d-flex justify-content-between">
<div>
left
</div>
<div>
right
</div>
</div>
or, auto-margins (eg:ml-auto
) in any flexbox container (row,navbar,card,d-flex,etc...)
<div class="d-flex">
<div>
left
</div>
<div class="ml-auto">
right
</div>
</div>
Bootstrap 4 Align Demo
Bootstrap 4 Right Align Examples(float, flexbox, text-right, etc...)
Bootstrap 3
Use the pull-right
class..
<div class="container">
<div class="row">
<div class="col-md-6">Total cost</div>
<div class="col-md-6"><span class="pull-right">$42</span></div>
</div>
</div>
You can also use the text-right
class like this:
<div class="row">
<div class="col-md-6">Total cost</div>
<div class="col-md-6 text-right">$42</div>
</div>
Instead of testing for an Array,
just convert whatever you get into a one-level Array,
so your code only needs to handle the one case.
t = [*something] # or...
t = Array(something) # or...
def f *x
...
end
Ruby has various ways to harmonize an API which can take an object or an Array of objects, so, taking a guess at why you want to know if something is an Array, I have a suggestion.
The splat operator contains lots of magic you can look up, or you can just call Array(something)
which will add an Array wrapper if needed. It's similar to [*something]
in this one case.
def f x
p Array(x).inspect
p [*x].inspect
end
f 1 # => "[1]"
f [1] # => "[1]"
f [1,2] # => "[1, 2]"
Or, you could use the splat in the parameter declaration and then .flatten
, giving you a different sort of collector. (For that matter, you could call .flatten
above, too.)
def f *x
p x.flatten.inspect
end # => nil
f 1 # => "[1]"
f 1,2 # => "[1, 2]"
f [1] # => "[1]"
f [1,2] # => "[1, 2]"
f [1,2],3,4 # => "[1, 2, 3, 4]"
And, thanks gregschlom, it's sometimes faster to just use Array(x)
because when it's already an Array
it doesn't need to create a new object.
I use jQuery param with AngularJS post requrest. Here is a example ... create AngularJS application module, where myapp
is defined with ng-app
in your HTML code.
var app = angular.module('myapp', []);
Now let us create a Login controller and POST email and password.
app.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
// default post header
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
// send login data
$http({
method: 'POST',
url: 'https://example.com/user/login',
data: $.param({
email: $scope.email,
password: $scope.password
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
// handle success things
}).error(function (data, status, headers, config) {
// handle error things
});
}]);
I don't like to exaplain the code, it is simple enough to understand :) Note that param
is from jQuery, so you must install both jQuery and AngularJS to make it working. Here is a screenshot.
Hope this is helpful. Thanks!
I suppose you could use a solution such as this one :
select name, length(name)
from users
where id = (
select id
from users
order by length(name) desc
limit 1
);
Might not be the optimal solution, though... But seems to work.
git --work-tree=/tmp/files_without_dot_git clone --depth=1 \
https://git.yourgit.your.com/myawesomerepo.git \
/tmp/deleteme_contents_of_dot_git
Both the directories in /tmp are created on the fly. No need to pre-create these.
I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.
My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.
This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.
The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.
#This is pseudo-code - within the application:
BEGIN TRANSACTION - get transaction lock
SELECT all current name value pairs where id = $id into a hash record
create a merge record from the current and update record
(set intersection where shared keys in new win, and empty values in new are deleted).
DELETE all name value pairs where id = $id
COPY/INSERT merged records
END TRANSACTION
Often enterprise databases have several users and I'm not aways on the right one :
SELECT * FROM ALL_CONSTRAINTS WHERE table_name = 'YOUR TABLE NAME' ;
Picked from Oracle documentation
Although accepted answer is right, but IMHO is just a workaround.
To be clear: it's a perfectly normal situation that a persistent connection may become stale. But unfortunately it's very bad when the HTTP client library cannot handle it properly.
Since this faulty behavior in Apache HttpClient was not fixed for many years, I definitely would prefer to switch to a library that can easily recover from a stale connection problem, e.g. OkHttp.
Why?
NoHttpResponseException
).When I switched to OkHttp, my problems with NoHttpResponseException
disappeared forever.
This is a common code adapted from another examples:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.google.com/")
#open tab
# ... take the code from the options below
# Load a page
driver.get('http://bings.com')
# Make the tests...
# close the tab
driver.quit()
the possible ways were:
Sending <CTRL> + <T>
to one element
#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
Sending <CTRL> + <T>
via Action chains
ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
Execute a javascript snippet
driver.execute_script('''window.open("http://bings.com","_blank");''')
In order to achieve this you need to ensure that the preferences browser.link.open_newwindow and browser.link.open_newwindow.restriction are properly set. The default values in the last versions are ok, otherwise you supposedly need:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.link.open_newwindow", 3)
fp.set_preference("browser.link.open_newwindow.restriction", 2)
driver = webdriver.Firefox(browser_profile=fp)
the problem is that those preferences preset to other values and are frozen at least selenium 3.4.0. When you use the profile to set them with the java binding there comes an exception and with the python binding the new values are ignored.
In Java there is a way to set those preferences without specifying a profile object when talking to geckodriver, but it seem to be not implemented yet in the python binding:
FirefoxOptions options = new FirefoxOptions().setProfile(fp);
options.addPreference("browser.link.open_newwindow", 3);
options.addPreference("browser.link.open_newwindow.restriction", 2);
FirefoxDriver driver = new FirefoxDriver(options);
The third option did stop working for python in selenium 3.4.0.
The first two options also did seem to stop working in selenium 3.4.0. They do depend on sending CTRL key event to an element. At first glance it seem that is a problem of the CTRL key, but it is failing because of the new multiprocess feature of Firefox. It might be that this new architecture impose new ways of doing that, or maybe is a temporary implementation problem. Anyway we can disable it via:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.tabs.remote.autostart", False)
fp.set_preference("browser.tabs.remote.autostart.1", False)
fp.set_preference("browser.tabs.remote.autostart.2", False)
driver = webdriver.Firefox(browser_profile=fp)
... and then you can use successfully the first way.
It would be interesting to have a csv serializer as it would take up the minimal space compared to other serializing method.
The closest support for java object to csv is stringutils provided by spring utils project
arrayToCommaDelimitedString(Object[] arr) but it is far from being a serializer.
Here is a simple utility which uses reflection to serialize value objects
public class CSVWriter
{
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
if(data.length==0)
{
return "";
}
Class classType = data[0].getClass();
StringBuilder builder = new StringBuilder();
Method[] methods = classType.getDeclaredMethods();
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get"))
{
builder.append(m.getName().substring(3)).append(',');
}
else if(m.getName().startsWith("is"))
{
builder.append(m.getName().substring(2)).append(',');
}
}
}
builder.deleteCharAt(builder.length()-1);
builder.append('\n');
for(Object d : data)
{
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get") || m.getName().startsWith("is"))
{
System.out.println(m.invoke(d).toString());
builder.append(m.invoke(d).toString()).append(',');
}
}
}
builder.append('\n');
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
public static boolean generateCSV(File csvFileName,Object[] data)
{
FileWriter fw = null;
try
{
fw = new FileWriter(csvFileName);
if(!csvFileName.exists())
csvFileName.createNewFile();
fw.write(produceCsvData(data));
fw.flush();
}
catch(Exception e)
{
System.out.println("Error while generating csv from data. Error message : " + e.getMessage());
e.printStackTrace();
return false;
}
finally
{
if(fw!=null)
{
try
{
fw.close();
}
catch(Exception e)
{
}
fw=null;
}
}
return true;
}
}
Here is an example value object
public class Product {
private String name;
private double price;
private int identifier;
private boolean isVatApplicable;
public Product(String name, double price, int identifier,
boolean isVatApplicable) {
super();
this.name = name;
this.price = price;
this.identifier = identifier;
this.isVatApplicable = isVatApplicable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public boolean isVatApplicable() {
return isVatApplicable;
}
public void setVatApplicable(boolean isVatApplicable) {
this.isVatApplicable = isVatApplicable;
}
}
and the code to run the util
public class TestCSV
{
public static void main(String... a)
{
Product[] list = new Product[5];
list[0] = new Product("dvd", 24.99, 967, true);
list[1] = new Product("pen", 4.99, 162, false);
list[2] = new Product("ipad", 624.99, 234, true);
list[3] = new Product("crayons", 4.99,127, false);
list[4] = new Product("laptop", 1444.99, 997, true);
CSVWriter.generateCSV(new File("C:\\products.csv"),list);
}
}
Output:
Name VatApplicable Price Identifier
dvd true 24.99 967
pen false 4.99 162
ipad true 624.99 234
crayons false 4.99 127
laptop true 1444.99 997
Try the following command:
mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]
@Inject
instead of Spring’s @Autowired
to inject a bean.
@Named
instead of Spring’s @Component
to declare a bean.
Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar
is in your classpath)
Alexandru Bantiuc's answer worked well for me to stop the build, but my executors were still showing up as busy. I was able clear the busy executor status using the following
server_name_pattern = /your-servers-[1-5]/
jenkins.model.Jenkins.instance.getComputers().each { computer ->
if (computer.getName().find(server_name_pattern)) {
println computer.getName()
execList = computer.getExecutors()
for( exec in execList ) {
busyState = exec.isBusy() ? ' busy' : ' idle'
println '--' + exec.getDisplayName() + busyState
if (exec.isBusy()) {
exec.interrupt()
}
}
}
}
If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...
Python 2.x
import json
import urllib2
data = {
'ids': [12, 3, 4, 5, 6]
}
req = urllib2.Request('http://example.com/api/posts/create')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
Python 3.x
https://stackoverflow.com/a/26876308/496445
If you don't specify the header, it will be the default application/x-www-form-urlencoded
type.
A hash function could be considered the same as baking a loaf of bread. You start out with inputs (flour, water, yeast, etc...) and after applying the hash function (mixing + baking), you end up with an output: a loaf of bread.
Going the other way is extraordinarily difficult - you can't really separate the bread back into flour, water, yeast - some of that was lost during the baking process, and you can never tell exactly how much water or flour or yeast was used for a particular loaf, because that information was destroyed by the hashing function (aka the oven).
Many different variants of inputs will theoretically produce identical loaves (e.g. 2 cups of water and 1 tsbp of yeast produce exactly the same loaf as 2.1 cups of water and 0.9tsbp of yeast), but given one of those loaves, you can't tell exactly what combo of inputs produced it.
Encryption, on the other hand, could be viewed as a safe deposit box. Whatever you put in there comes back out, as long as you possess the key with which it was locked up in the first place. It's a symmetric operation. Given a key and some input, you get a certain output. Given that output, and the same key, you'll get back the original input. It's a 1:1 mapping.
it's not true the clear()
function clear the Arraylist and start from index 0
You could store all the strings that you want to compare str
with into a collection and check if the collection contains str
. Store all strings in the collection as lowercase and convert str
to lowercase before querying the collection. For example:
Set<String> strings = new HashSet<String>();
strings.add("val1");
strings.add("val2");
String str = "Val1";
if (strings.contains(str.toLowerCase()))
{
}
For the new version of noCaptcha Recaptcha the following works for me:
<div class="g-recaptcha"
data-sitekey="6LcVkQsTAAAAALqSUcqN1zvzOE8sZkOq2GMBE-RK"
style="transform:scale(0.7);transform-origin:0;-webkit-transform:scale(0.7);
transform:scale(0.7);-webkit-transform-origin:0 0;transform-origin:0 0;"></div>
Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName
I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress
Do not forget check if SQL Server Browser service is running.
You need to open the file in binary mode i.e. wb
instead of w
. If you don't, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.
The public modifier should be omitted in Java interfaces (in my opinion).
Since it does not add any extra information, it just draws attention away from the important stuff.
Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:
public interface Foo{
public void MakeFoo();
void PerformBar();
}
To run tests with node/npm without installing Mocha globally, you can do this:
• Install Mocha locally to your project (npm install mocha --save-dev
)
• Optionally install an assertion library (npm install chai --save-dev
)
• In your package.json
, add a section for scripts
and target the mocha binary
"scripts": {
"test": "node ./node_modules/mocha/bin/mocha"
}
• Put your spec files in a directory named /test
in your root directory
• In your spec files, import the assertion library
var expect = require('chai').expect;
• You don't need to import mocha, run mocha.setup
, or call mocha.run()
• Then run the script from your project root:
npm test
You can use system() or %x[] depending what kind of result you need.
system() returning true if the command was found and ran successfully, false otherwise.
>> s = system 'uptime'
10:56 up 3 days, 23:10, 2 users, load averages: 0.17 0.17 0.14
=> true
>> s.class
=> TrueClass
>> $?.class
=> Process::Status
%x[..] on the other hand saves the results of the command as a string:
>> result = %x[uptime]
=> "13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> p result
"13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> result.class
=> String
Th blog post by Jay Fields explains in detail the differences between using system, exec and %x[..] .
The way a select box is rendered is determined by the browser itself. So every browser will show you the height of the option list box in another height. You can't influence that. The only way you can change that is to make an own select from the scratch.
The problem is described (among other) in this article.
#box
is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".
Page flow means that the positioning of an element effects other elements in the flow.
In other words, as #box
now sees the dom, .a and .b are no longer "inside" #box
.
To fix this, you would want to make everything relative, or everything absolute.
One way would be:
.a {
position:relative;
margin-top:10px;
margin-left:10px;
background-color:red;
width:210px;
padding: 5px;
}
It's usually the metacharacter .
when not inside a character class.
So use ^.{1,35}$
. However, dot does not include newlines unless the dot-all modifier is applied against it.
You can use ^[\S\s]{1,35}$
without any modifiers, and this includes newlines as well.
This solution will take a character vector of package names and attempt to load them, or install them if loading fails. It relies on the return behaviour of require
to do this because...
require
returns (invisibly) a logical indicating whether the required package is available
Therefore we can simply see if we were able to load the required package and if not, install it with dependencies. So given a character vector of packages you wish to load...
foo <- function(x){
for( i in x ){
# require returns TRUE invisibly if it was able to load package
if( ! require( i , character.only = TRUE ) ){
# If package was not able to be loaded then re-install
install.packages( i , dependencies = TRUE )
# Load package after installing
require( i , character.only = TRUE )
}
}
}
# Then try/install packages...
foo( c("ggplot2" , "reshape2" , "data.table" ) )
There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta commons-configuration and commons-digester.
You could always use the standard JDK method of getting a document :
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
[...]
File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
private void Foo(){
int @this = 2;
}
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
The way I did it is: I have thousands of files in s3. I saw the properties panel of one file in the list. You can see the URI of that file and I copy pasted that to the browser - it was a text file and it rendered nicely. Now I replaced the uuid in the url with the uuid that I had at hand and boom there the file is.
I wish AWS had a better way to search a file, but this worked for me.
I noticed that there is no selected feature in datalist. It only gives you choice but can't have a default option. You can't show the selected option on the next page either.
You could use ol' good easy_install zipline
instead.
easy_install
isn't pip but one good aspect of it is the ability to download and install binary packages too, which would free you for the need having VC++ ready. This of course relies of the assumption that the binaries were prepared for your Python version.
UPDATE:
Yes, Pip can install binaries now!
There's a new binary Python archive format (wheel) that is supposed to replace "eggs". Wheels are already supported by pip
. This means you'll be able to install zipline
with pip
without compiling it as soon as someone builds the wheel for your platform and uploads it to PyPI.
If you are using "n" library @ https://github.com/tj/n . Do the following
echo $NODE_PATH
If node path is empty, then
sudo n latest - sudo is optional depending on your system
After switching Node.js versions using n, npm may not work properly.
curl -0 -L https://npmjs.com/install.sh | sudo sh
echo NODE_PATH
You should see your Node Path now. Else, it might be something else
World of Warcraft's engine seems all right, and it uses Lua. :)
The most straightforward solution is to make the rows a single item by making them strings. Each row then can be compared as a whole for its uniqueness using numpy. This solution is generalize-able you just need to reshape and transpose your array for other combinations. Here is the solution for the problem provided.
import numpy as np
original = np.array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
uniques, index = np.unique([str(i) for i in original], return_index=True)
cleaned = original[index]
print(cleaned)
Will Give:
array([[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
Send my nobel prize in the mail
At the risk of getting yet another mysterious down-vote...the fact that many mention the stack and memory with respect to value types and primitive types is because they must fit into a register in the microprocessor. You cannot push or pop something to/from the stack if it takes more bits than a register has....the instructions are, for example "pop eax" -- because eax is 32 bits wide on a 32-bit system.
Floating-point primitive types are handled by the FPU, which is 80 bits wide.
This was all decided long before there was an OOP language to obfuscate the definition of primitive type and I assume that value type is a term that has been created specifically for OOP languages.
Whatever algebra you are doing in Excel to create the new column could probably be done more effectively in R.
Please try the following: Read the raw file (before any excel manipulation) into R using read.csv(... stringsAsFactors=FALSE)
. [If that does not work, please take a look at ?read.table
(which read.csv
wraps), however there may be some other underlying issue].
For example:
delim = "," # or is it "\t" ?
dec = "." # or is it "," ?
myDataFrame <- read.csv("path/to/file.csv", header=TRUE, sep=delim, dec=dec, stringsAsFactors=FALSE)
Then, let's say your numeric columns is column 4
myDataFrame[, 4] <- as.numeric(myDataFrame[, 4]) # you can also refer to the column by "itsName"
If you want to add a default value for the already created column, this works for me:
ALTER TABLE Persons
ALTER credit SET DEFAULT 0.0;
Bootstrap 5
<div class="input-group">
<input type="text" class="form-control">
<button class="btn btn-outline-secondary" type="button">Go</button>
</div>
Bootstrap 3 & 4
you may use the input-group button property to apply the button direct to the input-field.
<div class="input-group">
<input type="text" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div><!-- /input-group -->
Take a look at BS4 or BS5 Input-Group doc for many more examples.
Neither FileUtils.copyDirectory() nor Archimedes's answer copy directory attributes (file owner, permissions, modification times, etc).
https://stackoverflow.com/a/18691793/14731 provides a complete JDK7 solution that does precisely that.
Thanks all, I had the same issue. I have a task that runs via a generic user account not linked to a particular person. This user as somehow logged off the VM, when I was trying to fix it I was logged in as me and not that user.
Logging back in with that user fixed the issue!
MAKE IT SIMPLE
Far as I know we can't instantiate an abstract class
There's your error right there. Of course you can instantiate an abstract class.
abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();
There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.
Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.
Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.
Even if you do start the executable outside Visual Studio, you can still use the "Attach" command to connect Visual Studio to your already-running executable. This can be useful e.g. when your application is run as a plug-in within another application.
Actually in Python we can read from HTTP responses like from files, here is an example for reading JSON from an API.
import json
from urllib.request import urlopen
with urlopen(url) as f:
resp = json.load(f)
return resp['some_key']
This post lead me to do this:
ActiveControl = null;
This allows me to capture all the keyboard input at the top level without other controls going nuts.
basically same for VS2012e: TOOLS > Options > Environment > Fonts and Colors > Display Items: Plain Text > "Item background" dropdown selector
try this,it may help you
import java.util.Scanner;
public class MulTwoArray {
public static void main(String[] args) {
int i, j, k;
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] c = new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array a");
int rowa = sc.nextInt();
int cola = sc.nextInt();
System.out.println("Enter size of array b");
int rowb = sc.nextInt();
int colb = sc.nextInt();
//read and b
System.out.println("Enter elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
a[i][j] = sc.nextInt();
}
System.out.println();
}
System.out.println("Enter elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
b[i][j] = sc.nextInt();
}
System.out.println("\n");
}
//print a and b
System.out.println("the elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
System.out.print(a[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
System.out.println("the elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(b[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
//multiply a and b
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
c[i][j] = 0;
for (k = 0; k < cola; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
//print multi result
System.out.println("result of multiplication of array a and b is ");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(c[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
}
}
http://www.c-sharpcorner.com/UploadFile/psingh/PDFFileGenerator12062005235236PM/PDFFileGenerator.aspx is open source and may be a good starting point for you.
I had this problem and I just realized that if in the server you see the user in the menu SERVER -> USERS AND PRIVILEGES and find the user who has % as HOSTNAME, you can use it instead the root user.
That's all
TFS users: If you are using source control that requires you to warn it before your rename files/folders then look at this answer instead which covers the extra steps required.
To rename a project's folder, file (.*proj
) and display name in Visual Studio:
.sln
file directly in another editor such as Notepad++ and update the paths there instead. (You may need to check-out the solution first in TFS, etc.)Note: Other suggested solutions that involve removing and then re-adding the project to the solution will break project references.
If you perform these steps then you might also consider renaming the following to match:
Also consider modifying the values of the following assembly attributes:
AssemblyProductAttribute
AssemblyDescriptionAttribute
AssemblyTitleAttribute
I faced this issue with tomcat 7 + jdk 1.8
with java 1.7 and lower versions it's working fine.
window -> preferences -> java -> installed jre
in my case I changed jre1.8 to JDK 1.7
and accordingly modify project facet , select same java version as it's there in selected Installed JRE.
Since it was a successful comment, I am adding it as an answer:
with files:
find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
I'm a day late and a dollar short on this one. If you want to view the folder structure of the GAC in Windows Explorer, you can do this by using the registry:
For a temporary view, you can substitute a drive for the folder path, which strips away the special directory properties.
As for why you'd want to do something like this, I've used this trick to compare GAC'd DLLs between different machines to make sure they're truly the same.
I used BBEdit for years, but recently converted to Panic's Coda.
I love Coda. It does everything that I need and now that I've begun programming plug-ins for it, it's become a far more rich tool. The support team are responsive and the community that is growing around it is fantastic. There is still a lot of room for improvement, but that's the cool thing about being part of the kind of community that surrounds it; you have a say in what that improvement is.
Check out SproutCore.
http://www.appleinsider.com/articles/10/04/19/sproutcore_debuts_new_html5_web_development_tools.html
If you are interested in fast as well as safe integer to string conversion method and not limited to the standard library, I can recommend the format_int
method from the {fmt} library:
fmt::format_int(42).str(); // convert to std::string
fmt::format_int(42).c_str(); // convert and get as a C string
// (mind the lifetime, same as std::string::c_str())
According to the integer to string conversion benchmarks from Boost Karma, this method several times faster than glibc's sprintf
or std::stringstream
. It is even faster than Boost Karma's own int_generator
as was confirm by an independent benchmark.
Disclaimer: I'm the author of this library.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
While creating chrome driver, use option to disable it. Its working without any extensions.
Use following code snippet
ChromeOptions options = new ChromeOptions();
options.addArguments("chrome.switches","--disable-extensions");
System.setProperty("webdriver.chrome.driver",(System.getProperty("user.dir") + "//src//test//resources//chromedriver_new.exe"));
driver = new ChromeDriver(options);
If you want to play nice with Windows file paths (under Cygwin) you can also try this:
fname=${fullfile##*[/|\\]}
This will account for backslash separators when using BaSH on Windows.
cq.select(cb.construct(entityClazz.class, root.get("ID"), root.get("VERSION"))); // HERE IS NO ERROR
Control Panel > Administrative Tools > Services >
Start OracleOraDb11g_home1TNSListener
The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed
method in collaboration with the pygame.mouse.get_pos
(if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.
EDIT:
To perform pixel perfect collisions use pygame.sprite.collide_rect()
found on their docs for sprites.
Here is another option:
scala> val list = List(1,2,4,2,4,7,3,2,4)
list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
scala> list.groupBy(x => x) map { case (k,v) => k-> v.length }
res74: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)
If you only need to add one path per configuration (debug/release), you could set the debug command working directory:
Project | Properties | Select Configuration | Configuration Properties | Debugging | Working directory
Repeat for each project configuration.
This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.
To push all local branches to the remote repository, use --all
:
git push REMOTENAME --all
git push --all
or specify all branches you want to push:
git push REMOTENAME master exp-branch-a anotherbranch bugfix
In addition, it's useful to add -u
to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.
You can use bringToFront
:
View view=findViewById(R.id.btnStartGame);
view.bringToFront();
Use string append operator on the serial.read()
. It works better than string.concat()
char r;
string mystring = "";
while(serial.available()){
r = serial.read();
mystring = mystring + r;
}
After you are done saving the stream in a string(mystring, in this case), use SubString functions to extract what you are looking for.
This code accept #fff and #ffffff variants and opacity.
function hex2rgb(hex, opacity) {
var h=hex.replace('#', '');
h = h.match(new RegExp('(.{'+h.length/3+'})', 'g'));
for(var i=0; i<h.length; i++)
h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);
if (typeof opacity != 'undefined') h.push(opacity);
return 'rgba('+h.join(',')+')';
}
We can easily achieve this using flex
. no need for background-image
.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
#image-wrapper{_x000D_
width:500px;_x000D_
height:500px;_x000D_
border:1px solid #333;_x000D_
display:flex;_x000D_
justify-content:center;_x000D_
align-items:center;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="image-wrapper">_x000D_
<img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
get ID of ImageView as
ImageView imgFp = (ImageView) findViewById(R.id.imgFp);
then Use
imgFp.setImageResource(R.drawable.fpscan);
to set source image programatically instead from XML.
.getCellType() != Cell.CELL_TYPE_BLANK
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
Perhaps a nice idiom for declaring constants for a class in Swift is to just use a struct named MyClassConstants like the following.
struct MyClassConstants{
static let testStr = "test"
static let testStrLength = countElements(testStr)
static let arrayOfTests: [String] = ["foo", "bar", testStr]
}
In this way your constants will be scoped within a declared construct instead of floating around globally.
I've added a static array constant, in response to a comment asking about static array initialization. See Array Literals in "The Swift Programming Language".
Notice that both string literals and the string constant can be used to initialize the array. However, since the array type is known the integer constant testStrLength
cannot be used in the array initializer.
Try to replace all the " and ' with a \ before them. Do this just for the msget object(String, I guess). Don't forget that \ must be escaped too.
IE filters plus CSS transforms (Safari and Firefox).
IE's support is the oldest, Safari has [at least some?] support in 3.1.2, and Firefox won't have support until 3.1.
Alternatively, I would recommend a mix of Canvas/VML or SVG/VML. (Canvas has wider support.)
SQL Server uses the TCP port 1433. This is probably blocked either by the VPN tunnel or by a firewall on the server.
A list of values quickly? Or even a list of objects!
I am just a beginner at the C# language but I like using
etc.
There's just too many ways to store items
Try perl -MCPAN -e "upgrade /(.\*)/"
. It works fine for me.
git show
is more a plumbing command than git log
, and has the same formatting options:
git show -s --format=%B SHA1
I had a background image, not big in size, but with weird dimensions - therefore the stretching and bad performance. I made a method with parameters Context, a View and a drawable ID(int) that will match the device screen size. Use this in e.g a Fragments onCreateView to set the background.
public void setBackground(Context context, View view, int drawableId){
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId);
bitmap = Bitmap.createScaledBitmap(bitmap, Resources.getSystem().
getDisplayMetrics().widthPixels,
Resources.getSystem().getDisplayMetrics().heightPixels,
true);
BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(),
bitmap);
view.setBackground(bitmapDrawable);
}
To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 tr
from rule one and add it to rule two.
table.rule1 tr td {
background-color: #ff0000;
}
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.
I had the same problem and the only solution that worked was:
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
Response.BinaryWrite(myMemoryStream.ToArray());
// myMemoryStream.WriteTo(Response.OutputStream); //works too
Response.Flush();
Response.Close();
Response.End();
I have tended in the past to work on my functions in two stages. The first stage would be to treat them as fairly normal SQL queries and make sure that I am getting the right results out of it. After I am confident that it is performing as desired, then I would convert it into a UDF.
Thanks all who answered this question.
It seems this is indeed a tough nut to crack. I ended up giving up and creating a static array and getter in my baseclass.
public abstract class Animal{
private static Animal[] animals= null;
public static Animal[] getAnimals(){
if (animals==null){
animals = new Animal[]{
new Dog(),
new Cat(),
new Lion()
};
}
return animals;
}
}
It seems that Java just isn't set up for self-discoverability the way C# is. I suppose the problem is that since a Java app is just a collection of .class files out in a directory / jar file somewhere, the runtime doesn't know about a class until it's referenced. At that time the loader loads it -- what I'm trying to do is discover it before I reference it which is not possible without going out to the file system and looking.
I always like code that can discover itself instead of me having to tell it about itself, but alas this works too.
Thanks again!
You can use formControlName
only on directives which implement ControlValueAccessor
.
So, in order to do what you want, you have to create a component which implements ControlValueAccessor
, which means implementing the following three functions:
writeValue
(tells Angular how to write value from model into view)registerOnChange
(registers a handler function that is called when the view changes)registerOnTouched
(registers a handler to be called when the component receives a touch event, useful for knowing if the component has been focused).Then, you have to tell Angular that this directive is a ControlValueAccessor
(interface is not gonna cut it since it is stripped from the code when TypeScript is compiled to JavaScript). You do this by registering a provider.
The provider should provide NG_VALUE_ACCESSOR
and use an existing value. You'll also need a forwardRef
here. Note that NG_VALUE_ACCESSOR
should be a multi provider.
For example, if your custom directive is named MyControlComponent, you should add something along the following lines inside the object passed to @Component
decorator:
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => MyControlComponent),
}
]
Your component is ready to be used. With template-driven forms, ngModel
binding will now work properly.
With reactive forms, you can now properly use formControlName
and the form control will behave as expected.
Use ::ng-deep with caution. I used it throughout my app to set the material design toolbar color to different colors throughout my app only to find that when the app was in testing the toolbar colors step on each other. Come to find out it is because these styles becomes global, see this article Here is a working code solution that doesn't bleed into other components.
<mat-toolbar #subbar>
...
</mat-toolbar>
export class BypartSubBarComponent implements AfterViewInit {
@ViewChild('subbar', { static: false }) subbar: MatToolbar;
constructor(
private renderer: Renderer2) { }
ngAfterViewInit() {
this.renderer.setStyle(
this.subbar._elementRef.nativeElement, 'backgroundColor', 'red');
}
}
In iOS8 sizeWithFont has been deprecated, please refer to
CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];
You can add all the attributes you want in sizeWithAttributes. Other attributes you can set:
- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName
and so on. But probably you won't need the others
Just need to put condition to execute task for specific distribution
- name: Creates directory
file: path=/src/www state=directory
when: ansible_distribution == 'Debian'
This is the definitive answer for a teradata node admin.
Go to your /etc/hosts
file and create a list of IP's or node names in a text file.
SMP007-1
SMP007-2
SMP007-3
Put the following script in a file.
#set a password across all nodes
printf "User ID: "
read MYUSERID
printf "New Password: "
read MYPASS
while read -r i; do
echo changing password on "$i"
ssh root@"$i" sudo echo "$MYUSERID":"$MYPASS" | chpasswd
echo password changed on "$i"
done< /usr/bin/setpwd.srvrs
Okay I know I've broken a cardinal security rule with ssh and root but I'll let you security folks deal with it.
Now put this in your /usr/bin
subdir along with your setpwd.srvrs
config file.
When you run the command it prompts you one time for the User ID
then one time for the password. Then the script traverses all nodes
in the setpwd.srvrs
file and does a passwordless ssh to each node,
then sets the password without any user interaction or secondary
password validation.
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.
Use Moment.js (https://momentjs.com/)
moment().isDST();
will give you if Day light savings is observed.
Also it has helper function to calculate relative time for you. You don't need to do manual calculations
e.g moment("20200105", "YYYYMMDD").fromNow();
If you're using AppCompat
, declare your activity in AndroidManifest.xml
as follows:
<activity
android:name=".SomeActivity"
...
android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
A few snippets from the HTML5 spec: http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async
The defer and async attributes must not be specified if the src attribute is not present.
There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.
If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:
The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.
For anyone using entity framework core ending up here. This is how you do it.
# Powershell / Package manager console
Script-Migration
# Cli
dotnet ef migrations script
You can use the -From
and -To
parameter to generate an update script to update a database to a specific version.
Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2
https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts
There are several options to this command.
The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify
0
(this is the default).The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.
An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.
i'd like to start by understanding the problem
Browsers make HTTP requests to servers. The server then makes an HTTP response.
Both requests and responses consist of a bunch of headers and a (sometimes optional) body with some content in it.
If there is a body, then one of the headers is the Content-Type
which describes what the body is (is it an HTML document? An image? The contents of a form submission? etc).
When you ask for your stylesheet, your server is telling the browser that it is an HTML document (Content-Type: text/html
) instead of a stylesheet (Content-Type: text/css
).
I've already checked my myme.type and text/css is already on css.
Then something else about your server is making that stylesheet come with the wrong content type.
Use the Net tab of your browser's developer tools to examine the request and the response.
def trim(x):
if x.dtype == object:
x = x.str.split(' ').str[0]
return(x)
df = df.apply(trim)
Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.
So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.
UPDATE YourTable SET MyField = 0 WHERE MyField IS NULL
works in most SQL dialects. I don't use Access, but that should get you started.
For you people living on the edge:
There is now something called a RadioNodeList and accessing it's value property will return the value of the currently checked input. This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.
Example Form
<form id="test">
<label><input type="radio" name="test" value="A"> A</label>
<label><input type="radio" name="test" value="B" checked> B</label>
<label><input type="radio" name="test" value="C"> C</label>
</form>
To retrieve the checked value, you could do something like this:
var form = document.getElementById("test");
alert(form.elements["test"].value);
The JSFiddle to prove it: http://jsfiddle.net/vjop5xtq/
Please note this was implemented in Firefox 33 (All other major browser seems to support it). Older browsers will require a polfyill for RadioNodeList
for this to properly function
Short Extension Method:
public static TResult IfNotNull<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator)
where TResult : class where TInput : class
{
if (o == null) return null;
return evaluator(o);
}
Using
PropertyC value = ObjectA.IfNotNull(x => x.PropertyA).IfNotNull(x => x.PropertyB).IfNotNull(x => x.PropertyC);
This simple extension method and much more you can find on http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/
EDIT:
After using it for moment I think the proper name for this method should be IfNotNull() instead of original With().
Container(
color: Color.fromRGBO(224, 251, 253, 1.0),
child: ListTile(
dense: true,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
RichText(
textAlign: TextAlign.left,
softWrap: true,
text: TextSpan(children: <TextSpan>
[
TextSpan(text: "hello: ",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold)),
TextSpan(text: "I hope this helps",
style: TextStyle(color: Colors.black)),
]
),
),
],
),
),
),
A simple solution without pandas:
import numpy as np
def auto_corrcoef(x):
return np.corrcoef(x[1:-1], x[2:])[0,1]
If you have previous apk file with you(backup) then use jarSigner to extract certificate from that that apk, then use that key or use keytool to clone that certificate, may be that will help... Helpful links are jarsigner docs and keytool docs.
var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );
(ans == null).Dump(); // False
(ans.Count() == 0 ).Dump(); // True
(Dump is from LinqPad)
You can do that using type()
:
>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>
Here is another simpler way to slice last elements
var tags = [1, 2, 3, "foo", "bar", "foobar", "barfoo"];
var lastObj = tags.slice(-1);
lastObj
is now ["barfoo"]
.
Python does this the same way and when I tried using JS it worked out. I am guessing string manipulation in scripting languages work the same way.
Similarly, if you want the last two objects in a array,
var lastTwoObj = tags.slice(-2)
will give you ["foobar", "barfoo"]
and so on.
Breadth first search
Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
if (root == null)
return;
queue.clear();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.remove();
System.out.print(node.element + " ");
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();
I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate
I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080
to forward the appropiate requests to tomcat.
There is a default value for the nginx variable proxy_read_timeout
of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.
NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)
Follow the below steps:
Select body > form-data and do same as shown in the image.
Now in your Django view.py
def post(self, request, *args, **kwargs): image = request.FILES["image"] data = json.loads(request.data['data']) ... return Response(...)
The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)
Create this extension method...
public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
if(paramCollection != null)
{
var p = paramCollection.Add(parameterName, SqlDbType.Structured);
p.TypeName = "dbo.tvp_Int";
DataTable _dt = new DataTable() {Columns = {"Value"}};
data.ForEach(value => _dt.Rows.Add(value));
p.Value = _dt;
}
}
Now you can add a table valued parameter in one line anywhere simply by doing this:
cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);
Centos 7 with PHP7.2:
sudo yum --enablerepo=remi-php72 install php-pecl-zip
Clickatell is a popular SMS gateway. It works in 200+ countries.
Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.
The HTTP/S method is as simple as this:
http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here
The SMTP method consists of sending a plain-text e-mail to: [email protected]
, with the following body:
user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home
You can also test the gateway (incoming and outgoing) for free from your browser
Not possible.
You can only store, simple values in SharedPrefences SharePreferences.Editor
What particularly about the class do you need to save?
Easy and handy commands
To delete all images
docker rmi $(docker images -a)
To delete containers which are in exited state
docker rm $(docker ps -a -f status=exited -q)
To delete containers which are in created state
docker rm $(docker ps -a -f status=created -q)
NOTE: Remove all the containers then remove the images
Edit, 24 Nov 2016: this answer is apparently popular, so I am adding a note here. If you replace a tag on a central server, anyone who has the old tag—any clone of that central-server repository that already has the tag—could retain its old tag. So while this tells you how to do it, be really sure you want to do it. You'll need to get everyone who already has the "wrong" tag to delete their "wrong tag" and replace it with the new "right tag".
Testing in Git 2.10/2.11 shows that retaining the old tag is the default behavior for clients running git fetch
, and updating is the default behavior for clients running git fetch --tags
.
(Original answer follows.)
When you ask to push tags, git push --tags
sends (along with any commits and other objects needed and any other ref updates from the push settings) to the remote an update request of the form new-sha1 refs/tags/name
. (Well, it sends however many: one of those for each tag.)
The update request is modified by the remote to add an old-sha1
(or again, one for each tag), then delivered to the pre-receive and/or update hooks (whichever hooks exist on the remote). Those hooks can decide whether to allow or reject the tag create/delete/update.
The old-sha1
value is the all-zeros "null" SHA-1 if the tag is being created. The new-sha1
is the null SHA-1 if the tag is being deleted. Otherwise both SHA-1 values are real, valid values.
Even with no hooks, there's a sort of "built-in hook" that is also run: the remote will refuse to move a tag unless you use the "force" flag (though the "built-in hook" is always OK with both "add" and "delete"). The rejection message you're seeing is coming from this built-in hook. (Incidentally, this same built-in hook also rejects branch updates that are not fast-forwards.)1
But—here's one of the keys to understanding what's going on—the git push
step has no idea whether the remote has that tag now, and if so, what SHA-1 value it has. It only says "here's my complete list of tags, along with their SHA-1 values". The remote compares the values and if there are additions and/or changes, runs the hooks on those. (For tags that are the same, it does nothing at all. For tags you don't have that they do, it also does nothing!)
If you delete the tag locally, then push
, your push simply does not transfer the tag. The remote assumes no change should be made.
If you delete the tag locally, then create it pointing to a new place, then push
, your push transfers the tag, and the remote sees this as a tag-change and rejects the change, unless it's a force-push.
Thus, you have two options:
The latter is possible via git push
2 even though deleting the tag locally and push
ing has no effect. Assuming the name of the remote is origin
, and the tag you want it to delete is dev
:
git push origin :refs/tags/dev
This asks the remote to delete the tag. The presence or absence of the tag dev
in your local repository is irrelevant; this kind of push
, with :remoteref
as a refspec, is a pure-delete push.
The remote may or may not allow tag deletion (depending on any extra hooks added). If it allows the deletion, then the tag will be gone, and a second git push --tags
, when you have a local dev
tag pointing to some commit or annotated tag repo object, send your new dev
tag. On the remote, dev
will now be a newly created tag, so the remote will probably allow the push (again this depends on any extra hooks added).
The force-push is simpler. If you want to be sure not to update anything other than the tag, just tell git push
to push only that one refspec:
git push --force origin refs/tags/dev:refs/tags/dev
(note: you don't need --tags
if you're explicitly pushing just one tag ref-spec).
1Of course, the reason for this built-in hook is to help enforce the behavior that other users of that same remote-repo expect: that branches are not rewound, and tags do not move. If you force-push, you should let the other users know you are doing this, so that they can correct for it. Note that "tags don't move at all" is newly enforced by Git 1.8.2; previous versions would allow the tag to "move forward" in the commit graph, much like branch names. See the git 1.8.2 release notes.
2It's trivial if you can log in on the remote. Just go to the Git repository there and run git tag -d dev
. Note that either way—deleting the tag on the remote, or using git push
to delete it—there's a period of time when anyone who accesses the remote will find that the dev
tag is missing. (They will continue to have their own old tag, if they already have it, and they might even push their old tag back up before you can push the new one.)
xcopy "$(ProjectDir)Views\Home\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\Home"
and if you want to copy entire folders:
xcopy /E /Y "$(ProjectDir)Views" "$(SolutionDir)MEFMVCPOC\Views"
Update: here's the working version
xcopy "$(ProjectDir)Views\ModuleAHome\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\ModuleAHome\" /Y /I
Here are some commonly used switches with xcopy
:
- /I - treat as a directory if copying multiple files.
- /Q - Do not display the files being copied.
- /S - Copy subdirectories unless empty.
- /E - Copy empty subdirectories.
- /Y - Do not prompt for overwrite of existing files.
- /R - Overwrite read-only files.
What are the steps for that? where is AppCompat located?
Download the support library here:
http://developer.android.com/tools/support-library/setup.html
If you are using Eclipse:
Go to the tabs at the top and select ( Windows -> Android SDK Manager ). Under the 'extras' section, check 'Android Support Library' and check it for installation.
After that, the AppCompat library can be found at:
android-sdk/extras/android/support/v7/appcompat
You need to reference this AppCompat library in your Android project.
Import the library into Eclipse.
From oracle documentation:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.
RuntimeExceptions are like "exceptions by invalid use of an api" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException
With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...
Add this script to your .bashrc
. Then you can call coffee
or anyhting locally. This is handy for your laptop, but don't use it on your server.
DEFAULT_PATH=$PATH;
add_local_node_modules_to_path(){
NODE_MODULES='./node_modules/.bin';
if [ -d $NODE_MODULES ]; then
PATH=$DEFAULT_PATH:$NODE_MODULES;
else
PATH=$DEFAULT_PATH;
fi
}
cd () {
builtin cd "$@";
add_local_node_modules_to_path;
}
add_local_node_modules_to_path;
note: this script makes aliase of cd
command, and after each call of cd
it checks node_modules/.bin
and add it to your $PATH
.
note2: you can change the third line to NODE_MODULES=$(npm bin);
. But that would make cd
command too slow.
I had the same error. In my case, using Appium, I had two versions of ADB
$ /usr/local/bin/adb
version 36
and
$ /Users/user/Library/Android/sdk/platform-tools/adb
version 39
The solution was:
be sure that your $PATH in bash_profile is pointing to: /Users/user/Library/Android/sdk/platform-tools/
stop the adb server: adb kill-server
and check Appium is stopped.
delete the adb version 36 (or you can rename it to have a backup): rm /usr/local/bin/adb
start adb server: adb start-server
or just starting Appium
https://support.google.com/googleplay/android-developer/answer/1078870?hl=en&ref_topic=2897459
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:
$a = array(
"nice",
"car" => "fast",
"none"
);
Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0
which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search()
searches for the index it stops at the first one because apparently ("car" == 0)
is true.
Setting array_search()
to strict mode won't solve the problem because then array_search("0", array_keys($a))
would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys()
to strings and then compares them correctly:
echo array_search("car", array_map("strval", array_keys($a)));
Prints 1
, which is correct.
EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:
$a = array(
"foo" => "bar",
"nice",
"car" => "fast",
"none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));
You will always get 0
, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:
$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));
I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?
Forget the mouse. To remove 5 lines, either:
Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?
As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.
I suggest spending some time with the Vim Tutor (run vimtutor
) to get more familiar with Vim in a very didactic way.
Another approach to count number of list elements:
var num = $("#mylist").find("li").length;_x000D_
console.log(num);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul id="mylist">_x000D_
<li>Element 1</li>_x000D_
<li>Element 2</li>_x000D_
<li>Element 3</li>_x000D_
<li>Element 4</li>_x000D_
<li>Element 5</li>_x000D_
</ul>
_x000D_
Here's how you do it
private fun sendNotification() {
val notificationId = 100
val chanelid = "chanelid"
val intent = Intent(this, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
val name = "my channel"
val description = "channel description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(chanelid, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(this, chanelid)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Want to Open My App?")
.setContentText("Open my app and see good things")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true) // cancel the notification when clicked
.addAction(R.drawable.ic_check, "YES", pendingIntent) //add a btn to the Notification with a corresponding intent
val notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, mBuilder.build());
}
Read full tutorial at => https://developer.android.com/training/notify-user/build-notification
If you don't want to go down the VBA path, there is this trick from a previous question.
Excel 2010: how to use autocomplete in validation list
It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.
As the given tag to this question is CSS, I will provide the way I accomplished it.
Create a class in the .css file.
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}
Nav-bar will be like:
NOTE: If you are already setting the style for all Nav-Bar elements using a class, you can cascade the special-case class we created with a white-space after the generic class in the html-tag.
Example: Here, I was already importing my style from a class called 'navList' I created for all list-items . But the special-case styling-attributes are part of class 'activePage'
.CSS file:
a.navList{text-decoration: none; color: gray;}
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}
.HTML file:
<div id="sub-header">
<ul>
<li> <a href="index.php" class= "navList activePage" >Home</a> </li>
<li> <a href="contact.php" class= "navList">Contact Us</a> </li>
<li> <a href="about.php" class= "navList">About Us</a> </li>
</ul>
</div>
Look how I've cascaded one class-name behind other.
Seriously, question exists five years and no nice facade?
function is_dir(path) {
try {
var stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
mvn install "-Dsomeproperty=propety value"
In pom.xml:
<properties>
<someproperty> ${someproperty} </someproperty>
</properties>
Referred from this question
$restore = $this->createElement('submit', 'restore', array(
'label' => 'FILE_RESTORE',
'class' => 'restore btn btn-small btn-primary',
'attribs' => array(
'onClick' => 'restoreCheck();return false;'
)
));
// Facebook SDK v5 for PHP
// https://developers.facebook.com/docs/php/gettingstarted/5.0.0
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.4',
]);
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
$response = $fb->get('/me?locale=en_US&fields=name,email');
$userNode = $response->getGraphUser();
var_dump(
$userNode->getField('email'), $userNode['email']
);
This is similar to CommonsWare answer but with a minor tweak: android:gravity="top|start"
. Complete code example:
<EditText
android:id="@+id/EditText02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top|start"
android:inputType="textMultiLine"
android:scrollHorizontally="false"
/>
You can set the timeout value in the connection string, but after you've connected it's read-only. You can read more at http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx
As Anil implies, ConnectionTimeout may not be what you need; it controls how long the ADO driver will wait when establishing a new connection. Your usage seems to indicate a need to wait longer than normal for a particular SQL query to execute, and in that case Anil is exactly right; use CommandTimeout (which is R/W) to change the expected completion time for an individual SqlCommand.
So, you need to DELETE
related rows from conflicted tables or more logical to UPDATE
their FOREIGN KEY
column to reference other PRIMARY KEY
's from the parent table.
Also, you may want to read this article Don’t Delete – Just Don’t
For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.
protected void Application_BeginRequest()
{
//NOTE: Stopping IE from being a caching whore
HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.Now);
Response.Cache.SetValidUntilExpires(true);
}
1) Public Inheritance:
a. Private members of Base class are not accessible in Derived class.
b. Protected members of Base class remain protected in Derived class.
c. Public members of Base class remain public in Derived class.
So, other classes can use public members of Base class through Derived class object.
2) Protected Inheritance:
a. Private members of Base class are not accessible in Derived class.
b. Protected members of Base class remain protected in Derived class.
c. Public members of Base class too become protected members of Derived class.
So, other classes can't use public members of Base class through Derived class object; but they are available to subclass of Derived.
3) Private Inheritance:
a. Private members of Base class are not accessible in Derived class.
b. Protected & public members of Base class become private members of Derived class.
So, no members of Base class can be accessed by other classes through Derived class object as they are private in Derived class. So, even subclass of Derived class can't access them.
Just return any kind of list. ArrayList will be fine, its not static.
ArrayList<yourClass> list = new ArrayList<yourClass>();
for (yourClass item : yourArray)
{
list.add(item);
}
Did you just try
$('#datebox li a').on('click', function(){
//$('#datebox').val($(this).text());
alert($(this).text());
});
It works for me :)
you said:
my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.
what you're asking for is very dangerous and will lead to a race condition. if your code is run twice at the same time by different users, they will both get 6 and their updates or inserts will step all over each other.
i suggest that you instead INSERT
in to the table, get the auto_increment value using LAST_INSERT_ID()
, and then UPDATE
the row to set whatever value you have that depends on the auto_increment value.
You have to reset that file to the original state and commit it again using --amend
. This is done easiest using git checkout HEAD^
.
Prepare demo:
$ git init
$ date >file-a
$ date >file-b
$ git add .
$ git commit -m "Initial commit"
$ date >file-a
$ date >file-b
$ git commit -a -m "the change which should only be file-a"
State before:
$ git show --stat
commit 4aa38f84e04d40a1cb40a5207ccd1a3cb3a4a317 (HEAD -> master)
Date: Wed Feb 7 17:24:45 2018 +0100
the change which should only be file-a
file-a | 2 +-
file-b | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
Here it comes: restore the previous version
$ git checkout HEAD^ file-b
commit it:
$ git commit --amend file-b
[master 9ef8b8b] the change which should only be file-a
Date: Wed Feb 7 17:24:45 2018 +0100
1 file changed, 1 insertion(+), 1 deletion(-)
State after:
$ git show --stat
commit 9ef8b8bab224c4d117f515fc9537255941b75885 (HEAD -> master)
Date: Wed Feb 7 17:24:45 2018 +0100
the change which should only be file-a
file-a | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
I know this question has an accepted answer, but I feel that it doesn't work in all cases.
For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):
http://phpjs.org/functions/strip_tags:535
It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script />
tag above.
Using the sapply
patterns <- c("A1", "A9", "A6")
df <- data.frame(name=c("A","Ale","Al","lex","x"),Letters=c("A1","A2","A9","A1","A9"))
name Letters
1 A A1
2 Ale A2
3 Al A9
4 lex A1
5 x A9
df[unlist(sapply(patterns, grep, df$Letters, USE.NAMES = F)), ]
name Letters
1 A A1
4 lex A1
3 Al A9
5 x A9
For me the solution was cleaning and rebuilding the Test Project
Build > Clean
Build > Build
I haven't read that in the answers above, that's why I add it :)
It's pretty easy. First of all send to the view decoded variable (see Laravel Views):
view('your-view')->with('leads', json_decode($leads, true));
Then just use common blade constructions (see Laravel Templating):
@foreach($leads['member'] as $member)
Member ID: {{ $member['id'] }}
Firstname: {{ $member['firstName'] }}
Lastname: {{ $member['lastName'] }}
Phone: {{ $member['phoneNumber'] }}
Owner ID: {{ $member['owner']['id'] }}
Firstname: {{ $member['owner']['firstName'] }}
Lastname: {{ $member['owner']['lastName'] }}
@endforeach
Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.
I have an automatically updated last_modified field, defined as:
`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC
SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`
In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.
Run this twice, first without setting the time_zone.