if not exists (select dist_id from tbl_stock where dist_id= @cust_id and item_id=@item_id)
insert into tbl_stock(dist_id,item_id,qty)values(@cust_id, @item_id, @qty);
else
update tbl_stock set qty=(qty + @qty) where dist_id= @cust_id and item_id= @item_id;
Can you try this?
SELECT [Title], [Firstname], [Surname], [Company_name], [Interest]
FROM [dbo].[EXTRANET_users]
WHERE CAST(Submission_date AS DATE) = CAST(GETDATE() AS DATE)
T-SQL doesn't really have the "implied" casting like C# does - you need to explicitly use CAST
(or CONVERT
).
Also, use GETDATE()
or CURRENT_TIMESTAMP
to get the "now" date and time.
Update: since you're working against SQL Server 2000 - none of those approaches so far work. Try this instead:
SELECT [Title], [Firstname], [Surname], [Company_name], [Interest]
FROM [dbo].[EXTRANET_users]
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, submission_date)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Default web site need to manage as well:
1 .On Default web site -> basicSettings -> connect as, change it to the right user.
2.change the Identiy of the applicationPool that related to the defaultWebSite
g.luck
if you are using Glide and Kotlin,
Glide.with(this)
.asBitmap()
.load("https://...")
.addListener(object : RequestListener<Bitmap> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean {
Toast.makeText(this@MainActivity, "failed: " + e?.printStackTrace(), Toast.LENGTH_SHORT).show()
return false
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
//image is ready, you can get bitmap here
var bitmap = resource
return false
}
})
.into(imageView)
SET STATISTICS TIME ON
SELECT *
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
SET STATISTICS TIME OFF;
And see the message tab it will look like this:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 10 ms.
(778 row(s) affected)
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
Change the line endings in the view:
:e ++ff=dos
:e ++ff=mac
:e ++ff=unix
This can also be used as saving operation (:w alone will not save using the line endings you see on screen):
:w ++ff=dos
:w ++ff=mac
:w ++ff=unix
And you can use it from the command-line:
for file in *.cpp
do
vi +':w ++ff=unix' +':q' "$file"
done
You cat use setVisible ()
method of JFrame (and set visibility to false
) or dispose ()
method which is more similar to close
operation.
GlobalStrings.AddRange(localStrings);
Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>)
.
If you want to automatically escape all JSP variables without having to explicitly wrap each variable, you can use an EL resolver as detailed here with full source and an example (JSP 2.0 or newer), and discussed in more detail here:
For example, by using the above mentioned EL resolver, your JSP code will remain like so, but each variable will be automatically escaped by the resolver
...
<c:forEach items="${orders}" var="item">
<p>${item.name}</p>
<p>${item.price}</p>
<p>${item.description}</p>
</c:forEach>
...
If you want to force escaping by default in Spring, you could consider this as well, but it doesn't escape EL expressions, just tag output, I think:
http://forum.springsource.org/showthread.php?61418-Spring-cross-site-scripting&p=205646#post205646
Note: Another approach to EL escaping that uses XSL transformations to preprocess JSP files can be found here:
http://therning.org/niklas/2007/09/preprocessing-jsp-files-to-automatically-escape-el-expressions/
Thing I like to do is to wrap addition columns in aggregate function, like max()
.
It works very good when you don't expect duplicate values.
Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, MAX(cpe.fmgcms_claimid) As fmgcms_claimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid
Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:
$output = preg_replace( '/[^0-9]/', '', $string );
This answer may be late but I hope it helps someone.
For me, these 2 lines of code worked:
textView.isScrollEnabled = false
textView.sizeToFit()
But don't set height constraint for your Textview
step 1 : create layout with name activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#c6cabd"
>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textColor="#ff0e13"
/>
<EditText
android:id="@+id/et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv"
android:hint="Input your country"
/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get EditText Text"
android:layout_below="@id/et"
/>
</RelativeLayout>
Step 2 : Create class Main.class
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
final TextView tv = (TextView) findViewById(R.id.tv);
final EditText et = (EditText) findViewById(R.id.et);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String country = et.getText().toString();
tv.setText("Your inputted country is : " + country);
}
});
}
}
PostgreSQL since version 9.5 has UPSERT syntax, with ON CONFLICT clause. with the following syntax (similar to MySQL)
INSERT INTO the_table (id, column_1, column_2)
VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z')
ON CONFLICT (id) DO UPDATE
SET column_1 = excluded.column_1,
column_2 = excluded.column_2;
Searching postgresql's email group archives for "upsert" leads to finding an example of doing what you possibly want to do, in the manual:
Example 38-2. Exceptions with UPDATE/INSERT
This example uses exception handling to perform either UPDATE or INSERT, as appropriate:
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
-- note that "a" must be unique
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing, and loop to try the UPDATE again
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');
There's possibly an example of how to do this in bulk, using CTEs in 9.1 and above, in the hackers mailing list:
WITH foos AS (SELECT (UNNEST(%foo[])).*)
updated as (UPDATE foo SET foo.a = foos.a ... RETURNING foo.id)
INSERT INTO foo SELECT foos.* FROM foos LEFT JOIN updated USING(id)
WHERE updated.id IS NULL;
See a_horse_with_no_name's answer for a clearer example.
Sometimes it happens when you duplicate files typically README sort of.
Use following class which implement fast method described in this article and contains all you need: readPixel
, putPixel
, get width/height
. Class update canvas after calling refresh()
method. Example solve simple case of 2d wave equation
class Screen{
constructor(canvasSelector) {
this.canvas = document.querySelector(canvasSelector);
this.width = this.canvas.width;
this.height = this.canvas.height;
this.ctx = this.canvas.getContext('2d');
this.imageData = this.ctx.getImageData(0, 0, this.width, this.height);
this.buf = new ArrayBuffer(this.imageData.data.length);
this.buf8 = new Uint8ClampedArray(this.buf);
this.data = new Uint32Array(this.buf);
}
// r,g,b,a - red, gren, blue, alpha components in range 0-255
putPixel(x,y,r,g,b,a=255) {
this.data[y * this.width + x] = (a << 24) | (b << 16) | (g << 8) | r;
}
readPixel(x,y) {
let p= this.data[y * this.width + x]
return [p&0xff, p>>8&0xff, p>>16&0xff, p>>>24];
}
refresh() {
this.imageData.data.set(this.buf8);
this.ctx.putImageData(this.imageData, 0, 0);
}
}
// --------
// TEST
// --------
let s=new Screen('#canvas');
function draw() {
for (var y = 1; y < s.height-1; ++y) {
for (var x = 1; x < s.width-1; ++x) {
let a = [[1,0],[-1,0],[0,1],[0,-1]].reduce((a,[xp,yp])=>
a+= s.readPixel(x+xp,y+yp)[0]
,0);
let v=a/2-tmp[x][y];
tmp[x][y]=v<0 ? 0:v;
}
}
for (var y = 1; y < s.height-1; ++y) {
for (var x = 1; x < s.width-1; ++x) {
let v=tmp[x][y];
tmp[x][y]= s.readPixel(x,y)[0];
s.putPixel(x,y, v,v,v);
}
}
s.refresh();
window.requestAnimationFrame(draw)
}
// temporary 2d buffer ()for solving wave equation)
let tmp = [...Array(s.width)].map(x => Array(s.height).fill(0));
function move(e) { s.putPixel(e.x-10, e.y-10, 255,255,255);}
draw();
_x000D_
<canvas id="canvas" height="150" width="512" onmousemove="move(event)"></canvas>
<div>Move mouse on black box</div>
_x000D_
Resolve is also more straightforward
from django.urls import resolve
resolve('edit_project', project_id=4)
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
You have to select the option in ArrayAdapter
:
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_single_choice, countries);
Your first variable declartion must start with a ?
while any additional must be concatenated with a &
single variable URL
multiple variable URL
In later versions of JQuery they have changed the function from select to activate. http://api.jqueryui.com/tabs/#event-activate
PyCharm 2017.3
Preference -> Tools -> Python integrated Tools
- Choose py.test
as Default test runner
.Preference -> Languages&Frameworks -> Django
- Set tick on Do not use Django Test runner
Run/Debug configuration
, otherwise tests will be run with those older configurations. Run/Debug Configuration -> Defaults -> Python tests -> py.test -> Additional Arguments
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.
I have actually found the proper solution and posted it under almost the same question here. For more details head there.
Solution:
# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo
Any one looking for a swift solution
let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)
A good example of understanding an idempotent operation might be locking a car with remote key.
log(Car.state) // unlocked
Remote.lock();
log(Car.state) // locked
Remote.lock();
Remote.lock();
Remote.lock();
log(Car.state) // locked
lock
is an idempotent operation. Even if there are some side effect each time you run lock
, like blinking, the car is still in the same locked state, no matter how many times you run lock operation.
If you use sass in your own project, you can override the default bootstrap gutter size by copy pasting the sass variables from bootstrap's _variables.scss file into your own projects sass file somewhere, like:
// Grid columns
//
// Set the number of columns and specify the width of the gutters.
$grid-gutter-width-base: 50px !default;
$grid-gutter-widths: (
xs: $grid-gutter-width-base,
sm: $grid-gutter-width-base,
md: $grid-gutter-width-base,
lg: $grid-gutter-width-base,
xl: $grid-gutter-width-base
) !default;
Now your gutters will be 50px instead of 30px. I find this to be the cleanest method to adjust the gutter size.
Include input type="file"
element on your HTML page and on the click event of your button trigger the click event of input type file element using trigger function of jQuery
The code will look like:
<input type="file" id="imgupload" style="display:none"/>
<button id="OpenImgUpload">Image Upload</button>
And on the button's click event write the jQuery code like :
$('#OpenImgUpload').click(function(){ $('#imgupload').trigger('click'); });
This will open File Upload Dialog box on your button click event..
Getting list of installed non-system apps
public static void installedApps()
{
List<PackageInfo> packList = getPackageManager().getInstalledPackages(0);
for (int i=0; i < packList.size(); i++)
{
PackageInfo packInfo = packList.get(i);
if ( (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
{
String appName = packInfo.applicationInfo.loadLabel(getPackageManager()).toString();
Log.e("App ? " + Integer.toString(i), appName);
}
}
}
function timeConversion(s) {
let hour = parseInt(s.substring(0,2));
hour = s.indexOf('AM') > - 1 && hour === 12 ? '00' : hour;
hour = s.indexOf('PM') > - 1 && hour !== 12 ? hour + 12 : hour;
hour = hour < 10 && hour > 0 ? '0'+hour : hour;
return hour + s.substring(2,8);
}
Simple way to switch wifi on non-rooted devices is to use simple app:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
try {
wfm.setWifiEnabled(Boolean.parseBoolean(getIntent().getStringExtra("wifi")));
} catch (Exception e) {
}
System.exit(0);
}
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
ADB commands:
$ adb shell am start -n org.mytools.config/.MainActivity -e wifi true
$ adb shell am start -n org.mytools.config/.MainActivity -e wifi false
This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.
The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.
Example: http://jsbin.com/ipawe/edit
Basic CSS:
#mydiv {
position: absolute;
top: 50%;
left: 50%;
height: 400px;
width: 700px;
margin-top: -200px; /* -(1/2 height) */
margin-left: -350px; /* -(1/2 width) */
}
You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.
To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white"))
to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL)
would set the background to null for the legend, but it did not. Perhaps worth another question.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
To get rid of the black background in the legend, you need to use the override.aes
argument to the guide_legend
. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
You can use termcolor for this:
sudo pip install termcolor
To print a colored bold:
from termcolor import colored
print(colored('Hello', 'green', attrs=['bold']))
For more information, see termcolor on PyPi.
simple-colors is another package with similar syntax:
from simple_colors import *
print(green('Hello', ['bold'])
The equivalent in colorama may be Style.BRIGHT
.
Shouldn't it simply be:
<button ng-click="clickingCallback()">Click me<button>
Why do you want to write a new directive just to map your click event to a callback on your scope ? ng-click already does that for you.
Setting the DB to single-user mode didn't work for me, but taking it offline, and then bringing it back online did work. It's in the right-click menu of the DB, under Tasks.
Be sure to check the 'Drop All Active Connections' option in the dialog.
Use generic types !
class DataExtraction<T>
{
DateRangeReport dateRange;
List<Predicate> predicates;
List<string> cids;
public DataExtraction( DateRangeReport dateRange,
List<Predicate> predicates,
List<string> cids)
{
this.dateRange = dateRange;
this.predicates = predicates;
this.cids = cids;
}
}
And call it like this :
DataExtraction<AdPerformanceRow> extractor = new DataExtraction<AdPerformanceRow>(dates, predicates , cids);
Use an control flow library like after
after.map(array, function (value, done) {
// do something async
setTimeout(function () {
// do something with the value
done(null, value * 2)
}, 10)
}, function (err, mappedArray) {
// all done, continue here
console.log(mappedArray)
})
Youtube doesn't provide any option for an end time, but there alternative sites that provide this, like Tubechop. Otherwise try writing a function that either pauses video/skips to next when your when your video has played its desired duration.
OR: using the Youtube Javascript player API, you could do something like this:
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
Simple, silent and deadly:
mkdir -p /my/new/dir >/dev/null 2>$1
Best way to add schema to your existing table: Right click on the specific table-->Design --> Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.
You can see the results in MB format, with the division of 1024 x 1024 which is equal to 1 MB.
int dataSize = 1024 * 1024;
System.out.println("Used Memory : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/dataSize + " MB");
System.out.println("Free Memory : " + Runtime.getRuntime().freeMemory()/dataSize + " MB");
System.out.println("Total Memory : " + Runtime.getRuntime().totalMemory()/dataSize + " MB");
System.out.println("Max Memory : " + Runtime.getRuntime().maxMemory()/dataSize + " MB");
CHECK YOUR ANTI-VIRUS FIREWALL SETTINGS.
I have a NodeJS server working on Windows 10 PC, but when I put the IP address and port (example http://102.168.1.123:5000) into another computer's browser on my local network nothing happened, although it worked OK on the host computer.
(To find your windows IP address run CMD, then IPCONFIG)
Bar Horing Amir's answer points to the Windows firewall settings. On My PC the Windows Firewall was turned off - as McAfee anti-virus has added its own Firewall.
My system started to work on other computers after I added port 5000 to 'Ports and Systems Services' under the McAfee Firewall settings on the computer with NodeJS on it. Other anti-virus software will have similar settings.
I would seriously suggest trying this solution first with Windows.
Old topic, but never clearly answered. I've been working on similar as well, and found the solution:
The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:
Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)
The same problem and I solved putting the table between the code
<div class = "table-responsive"> </ div>
For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.
Try doing:
SHOW TABLE STATUS FROM credentialing1;
The foreign key constraints are listed in the Comment column of the output.
Expanding on the answers provided here.
You can just do set idx = 1
to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1
would not be valid.
This means that you should prefer the syntax: set variable idx = 1
or set var idx = 1
.
Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.
(gdb) p idx = 1
$1 = 1
You can read more about gdb here.
I had similar issue, the problem i faced was i added the selenium-server-standalone-3.141.59.jar under modulepath instead it should be under classpath
so select classpath via (project -> Properties -> Java Bbuild Path -> Libraries) add the downloaded latest jar
After adding it must be something like this
And appropriate driver for browser has to be downloaded for me i checked and downloaded the same version of chrom for chrome driver and added in the C:\Program Files\Java
And following is the code that worked fine for me
public class TestuiAautomation {
public static void main(String[] args) {
System.out.println("Jai Ganesha");
try {
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Java\\chromedriver.exe");
System.out.println(System.getProperty("webdriver.chrome.driver"));
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("no-sandbox");
chromeOptions.addArguments("--test-type");
chromeOptions.addArguments("disable-extensions");
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.google.com");
System.out.println("Google is selected");
} catch (Exception e) {
System.err.println(e);
}
}
}
My edit got rejected, so I'm attaching how to handle merging changes from a remote branch here.
If you have to do this after an incorrect merge, you can do something like this:
# If you did a git pull and it broke something, do this first
# Find the one before the merge, copy the SHA1
git reflog
git reset --hard <sha1>
# Get remote updates but DONT auto merge it
git fetch github
# Checkout to your mainline so your branch is correct.
git checkout develop
# Make a new branch where you'll be applying matches
git checkout -b manual-merge-github-develop
# Apply your patches
git checkout --patch github/develop path/to/file
...
# Merge changes back in
git checkout develop
git merge manual-merge-github-develop # optionally add --no-ff
# You'll probably have to
git push -f # make sure you know what you're doing.
Cast the operands to floats:
float ans = (float)a / (float)b;
OPTION 1: if you want to make a common utility function then you can use this
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
and use it by just importing it as
import {getCurrentDate} from './utils'
console.log(getCurrentDate())
OPTION 2: or define and use in a class directly
getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
A very portable version (even to legacy bourne shell):
if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then do-something
fi
This has the additional quality of running only one subprocess at most (which is the process [
), whatever the shell flavor.
Replace =
with -eq
if variables contain numeric values, e.g.
3 -eq 03
is true, but3 = 03
is false. (string comparison).vscode/launch.json file is only used by Visual Studio as well as /Properties/launchSettings.json file. Don't use these files in production.
The launchSettings.json file:
contains profile settings.
To use a file 'appSettings.QA.json' for example. You can use 'ASPNETCORE_ENVIRONMENT'. Follow the steps below.
So the issue is actually that you are not waiting for the init to complete. This will cause random results. Here is what I use.
window.fbAsyncInit = function () {
FB.init({ appId: 'your-app-id', cookie: true, xfbml: true, oauth: true });
// *** here is my code ***
if (typeof facebookInit == 'function') {
facebookInit();
}
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
This will ensure that once everything is loaded, the function facebookInit is available and executed. That way you don't have to duplicate the init code every time you want to use it.
function facebookInit() {
// do what you would like here
}
If you need to handle newlines in diferent systems you can simply use the PHP predefined constant PHP_EOL (http://php.net/manual/en/reserved.constants.php) and simply use explode to avoid the overhead of the regular expression engine.
$lines = explode(PHP_EOL, $subject);
COLLATE UTF8_GENERAL_CI
will work as ignore-case.
USE:
SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';
or
SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
Another way is by making it readonly:
<input type="text" id="txtDis" readonly />
A "duplicate" question asked how to do this for a two-dimensional array, so this is a simple adaptation to answer that question. (The difference is only the six characters [2], 0
, which finds the third item in each subarray and passes an initial value of zero):
const twoDimensionalArray = [_x000D_
[10, 10, 1],_x000D_
[10, 10, 2],_x000D_
[10, 10, 3],_x000D_
];_x000D_
const sum = twoDimensionalArray.reduce( (partial_sum, a) => partial_sum + a[2], 0 ) ; _x000D_
console.log(sum); // 6
_x000D_
Try this: My.Application.Info.DirectoryPath
[MSDN]
This is using the My
feature of VB.NET. This particular property is available for all non-web project types, since .NET Framework 2.0, including Console Apps as you require.
As long as you trust Microsoft to continue to keep this working correctly for all the above project types, this is simpler to use than accessing the other "more direct" solutions.
Dim appPath As String = My.Application.Info.DirectoryPath
There are at least three ways to disable the use of unobtrusive JavaScript for client-side validation:
<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
System.Web.UI.ValidationSettings.UnobtrusiveValidationMode
static property to System.Web.UI.UnobtrusiveValidationMode.None
System.Web.UI.Page.UnobtrusiveValidationMode
instance property to System.Web.UI.UnobtrusiveValidationMode.None
To disable the functionality on a per page basis, I prefer to set the Page.UnobtrusiveValidationMode
property using the page directive:
<%@ Page Language="C#" UnobtrusiveValidationMode="None" %>
This might be useful when you want to work in parallel and read only chunks of data but keep it clean with new lines.
def readInChunks(fileObj, chunkSize=1024):
while True:
data = fileObj.read(chunkSize)
if not data:
break
while data[-1:] != '\n':
data+=fileObj.read(1)
yield data
I developed a new plugin called JavaScript Enhancements, that you can find on Package Control. It uses Flow (javascript static type checker from Facebook) under the hood.
Furthermore, it offers smart javascript autocomplete (compared to my other plugin JavaScript Completions), real-time errors, code refactoring and also a lot of features about creating, developing and managing javascript projects.
See the Wiki to know all the features that it offers!
An introduction to this plugin could be found in this css-tricks.com article: Turn Sublime Text 3 into a JavaScript IDE
Just some quick screenshots:
You need to install this
https://pypi.python.org/pypi/six
If you still don't know what pip is , then please also google for pip install
Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/
SELECT SocialSecurity_Number, Count(*) no_of_rows
FROM SocialSecurity
GROUP BY SocialSecurity_Number
HAVING Count(*) > 1
Order by Count(*) desc
Here's an example of code which uses the UTL_FILE.PUT and UTL_FILE.PUT_LINE calls:
declare
fHandle UTL_FILE.FILE_TYPE;
begin
fHandle := UTL_FILE.FOPEN('my_directory', 'test_file', 'w');
UTL_FILE.PUT(fHandle, 'This is the first line');
UTL_FILE.PUT(fHandle, 'This is the second line');
UTL_FILE.PUT_LINE(fHandle, 'This is the third line');
UTL_FILE.FCLOSE(fHandle);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Exception: SQLCODE=' || SQLCODE || ' SQLERRM=' || SQLERRM);
RAISE;
end;
The output from this looks like:
This is the first lineThis is the second lineThis is the third line
Share and enjoy.
I have found a good work-around for continue (love the break sample above). Here I do not want to list "agency". In PHP I'd "continue" but in twig, I came up with alternative:
{% for basename, perms in permsByBasenames %}
{% if basename == 'agency' %}
{# do nothing #}
{% else %}
<a class="scrollLink" onclick='scrollToSpot("#{{ basename }}")'>{{ basename }}</a>
{% endif %}
{% endfor %}
OR I simply skip it if it doesn't meet my criteria:
{% for tr in time_reports %}
{% if not tr.isApproved %}
.....
{% endif %}
{% endfor %}
Netty also provides a nice query string parser called QueryStringDecoder
.
In one line of code, it can parse the URL in the question.
I like because it doesn't require catching or throwing java.net.MalformedURLException
.
In one line:
Map<String, List<String>> parameters = new QueryStringDecoder(url).parameters();
See javadocs here: https://netty.io/4.1/api/io/netty/handler/codec/http/QueryStringDecoder.html
Here is a short, self contained, correct example:
import io.netty.handler.codec.http.QueryStringDecoder;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
public class UrlParse {
public static void main(String... args) {
String url = "https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback";
QueryStringDecoder decoder = new QueryStringDecoder(url);
Map<String, List<String>> parameters = decoder.parameters();
print(parameters);
}
private static void print(final Map<String, List<String>> parameters) {
System.out.println("NAME VALUE");
System.out.println("------------------------");
parameters.forEach((key, values) ->
values.forEach(val ->
System.out.println(StringUtils.rightPad(key, 19) + val)));
}
}
which generates
NAME VALUE
------------------------
client_id SS
response_type code
scope N_FULL
access_type offline
redirect_uri http://localhost/Callback
It is because your context class is being inherited from DbContext. I guess your ctor is like this:
public MyEntities()
: base("name=MyEntities")
name=...
should be changed to your connectionString's name
friend operator = equal rights as class
friend std::ostream& operator<<(std::ostream& os, const Object& object) {
os << object._atribute1 << " " << object._atribute2 << " " << atribute._atribute3 << std::endl;
return os;
}
The use of Swift 3 @objc inference in Swift 4 mode is deprecated?
use func call @objc
func call(){
foo()
}
@objc func foo() {
}
I need to test against a string of any character (including white space, marks, numbers, unicode characters...). Because white space, numbers, marks... will be the same in both upper case and lower case, and I want to find real upper case letters, I do this:
let countUpperCase = 0;
let i = 0;
while (i <= string.length) {
const character = string.charAt(i);
if (character === character.toUpperCase() && character !== character.toLowerCase()) {
countUpperCase++;
}
i++;
}
You would use the os module system method.
You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC
For example:
os.system('python') opens up the windows command prompt and runs the python interpreter
We can use the get_locale
function:
if (get_locale() == 'en_GB') {
// drink tea
}
Might be a hanging gpg-agent.
Try gpgconf --kill gpg-agent
as discussed here
Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16)
comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413
does not allow.
Its not the gcc version alone, I has got something to with the distros
If you are looking for a one-size-fits-all, I'd suggest DECIMAL(19, 4)
is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; Decimal
only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0.
The rule of thumb for storage of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old Currency
type in the front end to DECIMAL(19, 4)
type in the back end was that Currency
exhibited bankers' rounding by nature, whereas DECIMAL(p, s)
rounded by truncation.
An extra decimal place in storage for DECIMAL
allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero).
Yes, DECIMAL(24, 8)
sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) is required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :)
However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using DECIMAL(p, 6)
for storage. Accountants generally seem to favour four decimal places.
PS Avoid SQL Server's MONEY
data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See Aaron Bertrand's blog.
Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See Wikipedia; to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).
See mine.
func actioncall () {
let loginPageView = self.storyboard?.instantiateViewControllerWithIdentifier("LoginPageID") as! ViewController
self.navigationController?.pushViewController(loginPageView, animated: true)
}
If you use presenting style, you might lose the page's navigation bar with preset pushnavigation.
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
I've also been successful with this URL structure:
Base URL:
https://calendar.google.com/calendar/r/eventedit?
And let's say this is my event details:
Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)
I'd convert my details into these parameters (URL encoded):
text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York
Example link:
Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:
dates=20200222T150000Z/20200222T163000Z
Example link:
If the user-agent stylesheet's style is causing problems for the browser it's supposed to fix, then you could try removing the offending style and testing that to ensure it doesn't have any unexpected adverse effects elsewhere.
If it doesn't, use the modified stylesheet. Fixing browser quirks is what these sheets are for - they fix issues, they aren't supposed to introduce new ones.
If you're unable to edit the stylesheet that contains the offending line, you may consider using the !important
keyword.
An example:
.override {
border: 1px solid #000 !important;
}
.a_class {
border: 2px solid red;
}
And the HTML:
<p class="a_class">content will have 2px red border</p>
<p class="override a_class">content will have 1px black border</p>
Try to use !important
only where you really have to - if you can reorganize your styles such that you don't need it, this would be preferable.
A full training pass over the entire dataset such that each example has been seen once. Thus, an epoch represents N/batch size training iterations, where N is the total number of examples.
A single update of a model's weights during training. An iteration consists of computing the gradients of the parameters with respect to the loss on a single batch of data.
as bonus:
The set of examples used in one iteration (that is, one gradient update) of model training.
See also batch size.
source: https://developers.google.com/machine-learning/glossary/
As soon as you call contains
, containsAll
, equals
, hashCode
, remove
, retainAll
, size
or toArray
, you'd have to traverse the elements anyway.
If you're occasionally only calling methods such as isEmpty
or clear
I suppose you'd be better of by creating the collection lazily. You could for instance have a backing ArrayList
for storing previously iterated elements.
I don't know of any such class in any library, but it should be a fairly simple exercise to write up.
Using the Date object's methods will could come in handy.
e.g.:
myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));
I had issues with trying to delete a returned JSON object and found that it was actually a string. If you JSON.parse() before deleting you can be sure your key will get deleted.
let obj;
console.log(this.getBody()); // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = this.getBody();
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = JSON.parse(this.getBody());
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805}
If you want to get source map file different version, you can use this link http://code.jquery.com/jquery-x.xx.x.min.map
Instead x.xx.x put your version number.
Note: Some links, which you get on this method, may be broken :)
You can use the function file_get_contents();
if(file_get_contents('https://example.com/example.txt')) {
//File exists
}
Assuming that all your inputs are lists and that the double quotes in the input actually don't matter, this can be done with a simple regexp replace. It is a bit perl-y but works like a charm. Note also that the output is now a list of unicode strings, you didn't specify that you needed that, but it seems to make sense given unicode input.
import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" \]]')
result = junkers.sub('', x).split(',')
print result
---> [u'A', u'B', u'C', u'D']
The junkers variable contains a compiled regexp (for speed) of all characters we don't want, using ] as a character required some backslash trickery. The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.
Note that this also removes spaces from inside entries u'["oh no"]' ---> [u'ohno']. If this is not what you wanted, the regexp needs to be souped up a bit.
Whatever is specified in the command
in docker-compose.yml should get appended to the entrypoint
defined in the Dockerfile, provided entrypoint
is defined in exec form in the Dockerfile.
If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.
If you need
then you can use this CircularArrayList for Java in this way (for example):
CircularArrayList<String> buf = new CircularArrayList<String>(4);
buf.add("A");
buf.add("B");
buf.add("C");
buf.add("D"); // ABCD
String pop = buf.remove(0); // A <- BCD
buf.add("E"); // BCDE
String interiorElement = buf.get(i);
All these methods run in O(1).
To collect more useful resources here:
As mentioned before D3.js is definitely the best visualization library for charts. To use it in AngularJS I developed angular-chart. It is an easy to use directive which connects D3.js with the AngularJS 2-Way-DataBinding. This way the chart gets automatically updated whenever you change the configuration options and at the same time the charts saves its state (zoom level, ...) to make it available in the AngularJS world.
Check out the examples to get convinced.
The idea of programmatically setting constraints can be tiresome. This solution below will work for any layout whether constraint, linear, etc. Best way would be to set a placeholder i.e. a FrameLayout with proper constraints (or proper placing in other layout such as linear) at position where you would expect the programmatically created view to have.
All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild()
method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout [link].
Here is what your code would look like, supposing you wish to create TextView programmatically at a particular position:
Step 1:
In your layout which would contain the view to be inflated, place a FrameLayout at the correct position and give it an id, say, "container".
Step 2 Create a layout with root element as the view you want to inflate during runtime, call the layout file as "textview.xml" :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
</TextView>
BTW, set the layout-params of your frameLayout to wrap_content always else the frame layout will become as big as the parent i.e. the activity i.e the phone screen.
android:layout_width="wrap_content"
android:layout_height="wrap_content"
If not set, because a child view of the frame, by default, goes to left-top of the frame layout, hence your view will simply fly to left top of the screen.
Step 3
In your onCreate
method, do this :
FrameLayout frameLayout = findViewById(R.id.container);
TextView textView = (TextView) View.inflate(this, R.layout.textview, null);
frameLayout.addView(textView);
(Note that setting last parameter of findViewById
to null
and adding view by calling addView()
on container view (frameLayout) is same as simply attaching the inflated view by passing true
in 3rd parameter of findViewById()
. For more, see this.)
I don't like and understand things, which can be explained visually, by words.
In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
If you're interested in the minutiae, then examine Promises/A+.
So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from @jfriend00:
Rather than directly passing callbacks to functions, something which can lead to tightly coupled interfaces, using promises allows one to separate concerns for code that is synchronous or asynchronous.
Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.
Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):
/* assume getScript has signature like: function (path, callback, context)
and listens to onload && onreadystatechange */
$(function () {
getScript('path/to/CodeMirror', getJSMode);
// onreadystate is not reliable for callback args.
function getJSMode() {
getScript('path/to/CodeMirror/mode/javascript/javascript.js',
ourAwesomeScript);
};
function ourAwesomeScript() {
console.log("CodeMirror is awesome, but I'm too impatient.");
};
});
To the promises formulated version (again, apologies, I'm not up to date on jQuery):
/* Assume getScript returns a promise object */
$(function () {
$.when(
getScript('path/to/CodeMirror'),
getScript('path/to/CodeMirror/mode/javascript/javascript.js')
).then(function () {
console.log("CodeMirror is awesome, but I'm too impatient.");
});
});
Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.
This will do the trick :-
new Date().valueOf()
This can be done using driver.execute_script():-
driver.execute_script("document.getElementById('myelementid').scrollIntoView();")
Another thing to mention is that atan2
is more stable when computing tangents using an expression like atan(y / x)
and x
is 0 or close to 0.
Best practice I think is to set the font to the body:
body {
font: normal 10px Verdana, Arial, sans-serif;
}
and if you decide to change it for some element it could be easily overwrited:
h2, h3 {
font-size: 14px;
}
Answering this old question (for others which may help)
Configuring your httpd conf correctly will make the problem solved. Install any httpd server, if you don't have one.
Listing my config here.
[smilyface@box002 ~]$ cat /etc/httpd/conf/httpd.conf | grep shirts | grep -v "#"
ProxyPass /shirts-service http://local.box002.com:16743/shirts-service
ProxyPassReverse /shirts-service http://local.box002.com:16743/shirts-service
ProxyPass /shirts http://local.box002.com:16443/shirts
ProxyPassReverse /shirts http://local.box002.com:16443/shirts
...
...
...
edit the file as above and then restart httpd as below
[smilyface@box002 ~]$ sudo service httpd restart
And then request with with https
will work without exception.
Also request with http
will forward to https
! No worries.
You need to swap all the back slashes to forward slashes so change
docker -v C:\my\folder:/mountlocation ...
to
docker -v C:/my/folder:/mountlocation ...
I normally call docker from a cmd script where I want the folder to mount to be relative to the script i'm calling so in that script I do this...
SETLOCAL
REM capture the path to this file so we can call on relative scrips
REM without having to be in this dir to do it.
REM capture the path to $0 ie this script
set mypath=%~dp0
REM strip last char
set PREFIXPATH=%mypath:~0,-1%
echo "PREFIXPATH=%PREFIXPATH%"
mkdir -p %PREFIXPATH%\my\folder\to\mount
REM swap \ for / in the path
REM because docker likes it that way in volume mounting
set PPATH=%PREFIXPATH:\=/%
echo "PPATH=%PPATH%"
REM pass all args to this script to the docker command line with %*
docker run --name mycontainername --rm -v %PPATH%/my/folder/to/mount:/some/mountpoint myimage %*
ENDLOCAL
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
After testing all answers without success. Some times input take alpha character also.
Here is the last full working code with only numbers input also keeping in mind backspace button key event for user if something number is incorrect.
$("#phone").keydown(function(event) {_x000D_
k = event.which;_x000D_
if ((k >= 96 && k <= 105) || k == 8) {_x000D_
if ($(this).val().length == 10) {_x000D_
if (k == 8) {_x000D_
return true;_x000D_
} else {_x000D_
event.preventDefault();_x000D_
return false;_x000D_
_x000D_
}_x000D_
}_x000D_
} else {_x000D_
event.preventDefault();_x000D_
return false;_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input name="phone" id="phone" placeholder="Mobile Number" class="form-control" type="number" required>
_x000D_
I didn't check all the code but my guess is that the error is in the malloc call. You have to replace
double *ptr = malloc(sizeof(double*) * TIME);
for
double *ptr = malloc(sizeof(double) * TIME);
since you want to allocate size for a double (not the size of a pointer to a double).
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
From MSDN:
To maximize productivity, the Windows Forms Designer shadows the
AutoSize
property for theForm
class. At design time, the form behaves as though theAutoSize
property is set to false, regardless of its actual setting. At runtime, no special accommodation is made, and theAutoSize
property is applied as specified by the property setting.
for(int i=1;i<=5;i++)
{
for(int j=5;j>=i;j--)
{
System.out.print(" ");
}
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
for(int j=1;j<=i-1;j++)
{
System.out.print("*");
}
System.out.println("");
}
*
***
You can use html5 video player which has full screen playback option.
This is a very good html5 player to have a look.
http://sublimevideo.net/
Ensure skip-networking is commented out in my.cnf/my.ini
In case if you using Intellij https://www.jetbrains.com/datagrip/features/importexport.html
The exec function executes a system command and never returns-- use system instead of exec if you want it to return
Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.
In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.
A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.
In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.
Example:
use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;
Finally, IPC::Run from the CPAN is also worth looking at…
Print the list of running processes and try to find the one that says spring
in it. Once you find the appropriate process ID (PID
), stop the given process.
ps aux | grep spring
kill -9 INSERT_PID_HERE
After that, try and run the application again. If you killed the correct process your port should be freed up and you can start the server again.
add anaconda installation path to .bashrc
export PATH="$PATH:/home/username/anaconda3/bin"
load in terminal
$ source ~/.bashrc
run from terminal
$ anaconda-navigator
You should declare the variable in a header file:
extern int x;
and then define it in one C file:
int x;
In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).
ok , i've solved it by creating a handler on the onCreate of the service , and calling the gps functions through there .
The code is as simple as this:
final handler=new Handler(Looper.getMainLooper());
And then to force running things on the UI, I call post
on it.
Each directive's pre-link
function is called whenever a new related element is instantiated.
As seen previously in the compilation order section, pre-link
functions are called parent-then-child, whereas post-link
functions are called child-then-parent
.
The pre-link
function is rarely used, but can be useful in special scenarios; for example, when a child controller registers itself with the parent controller, but the registration has to be in a parent-then-child
fashion (ngModelController
does things this way).
Try this:
INSERT INTO MyTable1 (Col1, Col2, Col4)
SELECT Col1, Col2, Col3 FROM MyTable2
The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".
If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.
Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.
Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.
So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.
A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.
The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.
You can use from pkg.components.core import GameLoopEvents
, for example I use pycharm, the below is my project structure image, I just import from the root package, then it works:
You could simply have: var result = (str == "true")
.
Logging has different levels such as :
Trace – A fine-grained debug message, typically capturing the flow through the application.
Debug- A general debugging event should be logged under this.
ALL – All events could be logged.
INFO- An informational purpose, information written in plain english.
Warn- An event that might possible lead to an error.
Error- An error in the application, possibly recoverable.
Logging captured with debug level is information helpful to developers as well as other personnel, so it captures in broad range. If your code doesn't have exception or errors then you should be alright to use DEBUG level of logging, otherwise you should carefully choose options.
Easiest way for me to fix this issue:
Use Prim's algorithm when you have a graph with lots of edges.
For a graph with V vertices E edges, Kruskal's algorithm runs in O(E log V) time and Prim's algorithm can run in O(E + V log V) amortized time, if you use a Fibonacci Heap.
Prim's algorithm is significantly faster in the limit when you've got a really dense graph with many more edges than vertices. Kruskal performs better in typical situations (sparse graphs) because it uses simpler data structures.
Actually, all the other answers have flaws. The most reliable way is:
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
Detailed Explanation:
Using "%1"=="-b"
will flat out crash if passing argument with spaces and quotes. This is the least reliable method.
IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "a b"
b""=="-b" was unexpected at this time.
Using [%1]==[-b]
is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.
IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "-b"
(does not match, and jumps to UNKNOWN instead of SPECIFIC)
Using "%~1"=="-b"
is the most reliable. %~1
will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"
(all of the above tests work correctly)
I think you can use REGEXP instead of LIKE
SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')
=VLOOKUP(LEFT(A1,3),LEFT(B$2:B$22,3), 1,FALSE)
LEFT() truncates the first n character of a string, and you need to do it in both columns. The third parameter of VLOOKUP is the number of the column to return with. So if your range is not only B$2:B$22 but B$2:C$22 you can choose to return with column B value (1) or column C value (2)
In Oracle:
SELECT 'Hello world' FROM dual
Dual equivalent in SQL Server:
SELECT 'Hello world'
Try doing something like this
**/node_modules
**
is used for a recursive call in the whole project
Two consecutive asterisks
**
in patterns matched against full pathname may have special meaning:A leading
**
followed by a slash means match in all directories. For example,**/foo
matches file or directoryfoo
anywhere, the same as patternfoo
.**/foo/bar
matches file or directorybar
anywhere that is directly under directoryfoo
.A trailing
/**
matches everything inside. For example,abc/**
matches all files inside directoryabc
, relative to the location of the .gitignore file, with infinite depth.A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example,
a/\**/b
matchesa/b
,a/x/b
,a/x/y/b
and so on.Other consecutive asterisks are considered invalid.
Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:
"temp" environment variable setting - then it would be:
%temp%\Temporary ASP.NET Files
Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:
c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files
There are also cases where the temp folder can be set via config for a machine or site specific using this:
<compilation tempDirectory="d:\MyTempPlace" />
I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.
Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.
let suppose we create a table Transactions using SQl server management studio
txn_id int,
txn_type_id varchar(200),
Account_id int,
Amount int,
tDate date
);
with date datatype we can insert values in simple format: 'yyyy-mm-dd'
INSERT INTO transactions (txn_id,txn_type_id,Account_id,Amount,tDate)
VALUES (978, 'DBT', 103, 100, '2004-01-22');
Moreover we can have differet time formats like
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
if you use a list of widgets you can use this:
class HomePage extends StatelessWidget {
bool notNull(Object o) => o != null;
@override
Widget build(BuildContext context) {
var condition = true;
return Scaffold(
appBar: AppBar(
title: Text("Provider Demo"),
),
body: Center(
child: Column(
children: <Widget>[
condition? Text("True"): null,
Container(
height: 300,
width: MediaQuery.of(context).size.width,
child: Text("Test")
)
].where(notNull).toList(),
)),
);
}
}
This should work with only one loop:
function checkIfArrayIsUnique(arr) {
var map = {}, i, size;
for (i = 0, size = arr.length; i < size; i++){
if (map[arr[i]]){
return false;
}
map[arr[i]] = true;
}
return true;
}
find -L /var/www/ -type l
# man find
-L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the
properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched.
If you really mean exactly what you say (that you only need to find out IF "there are any keys" in B and not in A, not WHICH ONES might those be if any), the fastest way should be:
if any(True for k in dictB if k not in dictA): ...
If you actually need to find out WHICH KEYS, if any, are in B and not in A, and not just "IF" there are such keys, then existing answers are quite appropriate (but I do suggest more precision in future questions if that's indeed what you mean;-).
If you put #!/bin/awk -f
on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)
#!/bin/awk -f
BEGIN {} # Begin section
{} # Loop section
END{} # End section
Change the file to be executable by running:
chmod ugo+x ./awk-script
and you can then call your AWK script like this:
`$ echo "something" | ./awk-script`
After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.
If you are using gradle build system, follow these steps:
put jar
files inside respective libs
folder of your android app. You will generally find it at Project
> app
> libs
. If libs
folder is missing, create one.
add this to your build.gradle
file your app
. (Not to your Project
's build.gradle
)
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
// other dependencies
}
This will include all your jar
files available in libs
folder.
If don't want to include all jar
files, then you can add it individually.
compile fileTree(dir: 'libs', include: 'file.jar')
I think the problem is making sure that MySQL server has the rights to the file and can edit it.
If you can get it to have access to the file, then you can try setting:
SET GLOBAL slow_query_log = 1;
If not, you can always 'reload' the server after changing the configuration file. On linux its usually /etc/init.d/mysql reload
How about Constraints? Unlike semanticContentAttribute, they don't change semantics. Something like this perhaps:
button.rightAnchorconstraint(equalTo: button.rightAnchor).isActive = true
or in Objective-C:
[button.imageView.rightAnchor constraintEqualToAnchor:button.rightAnchor].isActive = YES;
Caveats: Untested, iOS 9+
People will offer you obfuscators, but no amount of obfuscation can prevent someone from getting at your code. None. If your computer can run it, or in the case of movies and music if it can play it, the user can get at it. Even compiling it to machine code just makes the job a little more difficult. If you use an obfuscator, you are just fooling yourself. Worse, you're also disallowing your users from fixing bugs or making modifications.
Music and movie companies haven't quite come to terms with this yet, they still spend millions on DRM.
In interpreted languages like PHP and Perl it's trivial. Perl used to have lots of code obfuscators, then we realized you can trivially decompile them.
perl -MO=Deparse some_program
PHP has things like DeZender and Show My Code.
My advice? Write a license and get a lawyer. The only other option is to not give out the code and instead run a hosted service.
See also the perlfaq entry on the subject.
I wanted to update at the comment earlier made by DaShaun, but as it is my first time commenting, application didn't allow me.
Nonetheless, I am using eclipse and after I added the below mention code snippet to my pom.xml as suggested by Dashun and I ran the mvn clean package to generate the avro source files, but I was still getting compilation error in the workspace.
I right clicked on project_name -> maven -> update project and updated the project, which added the target/generated-sources as a source folder to my eclipse project.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>test</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/target/generated-sources</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
If you are using this form of the branch
command (with start point), it does not matter where your HEAD
is.
What you are doing:
git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8
First, you set your HEAD
to the branch dev
,
Second, you start a new branch on commit 07aeec98
. There is no bb.txt at this commit (according to your github repo).
If you want to start a new branch at the location you have just checked out, you can either run branch with no start point:
git branch test
or as other have answered, branch and checkout there in one operation:
git checkout -b test
I think that you might be confused by that fact that 07aeec98
is part of the branch dev
. It is true that this commit is an ancestor of dev
, its changes are needed to reach the latest commit in dev
. However, they are other commits that are needed to reach the latest dev
, and these are not necessarily in the history of 07aeec98
.
8480e8ae
(where you added bb.txt) is for example not in the history of 07aeec98
. If you branch from 07aeec98
, you won't get the changes introduced by 8480e8ae
.
In other words: if you merge branch A and branch B into branch C, then create a new branch on a commit of A, you won't get the changes introduced in B.
Same here, you had two parallel branches master and dev, which you merged in dev. Branching out from a commit of master (older than the merge) won't provide you with the changes of dev.
If you want to permanently integrate new changes from master into your feature branches, you should merge master
into them and go on. This will create merge commits in your feature branches, though.
If you have not published your feature branches, you can also rebase them on the updated master: git rebase master featureA
. Be prepared to solve possible conflicts.
If you want a workflow where you can work on feature branches free of merge commits and still integrate with newer changes in master, I recommend the following:
dev
branch on a commit of masterdev
.Do not commit into dev
directly, use it only for merging other branches.
For example, if you are working on feature A and B:
a---b---c---d---e---f---g -master
\ \
\ \-x -featureB
\
\-j---k -featureA
Merge branches into a dev
branch to check if they work well with the new master:
a---b---c---d---e---f---g -master
\ \ \
\ \ \--x'---k' -dev
\ \ / /
\ \-x---------- / -featureB
\ /
\-j---k--------------- -featureA
You can continue working on your feature branches, and keep merging in new changes from both master and feature branches into dev
regularly.
a---b---c---d---e---f---g---h---i----- -master
\ \ \ \
\ \ \--x'---k'---i'---l' -dev
\ \ / / /
\ \-x---------- / / -featureB
\ / /
\-j---k-----------------l------ -featureA
When it is time to integrate the new features, merge the feature branches (not dev
!) into master.
Another way is to use box-shadow
:
#mybox {
box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-moz-box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-webkit-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
}
<div id="mybox">ABC</div>
See example here.
in Angular 4 or CLI you can create a PIPE like this:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalize'
})
/**
* Place the first letter of each word in capital letters and the other in lower case. Ex: The LORO speaks = The Loro Speaks
*/
export class CapitalizePipe implements PipeTransform {
transform(value: any): any {
value = value.replace(' ', ' ');
if (value) {
let w = '';
if (value.split(' ').length > 0) {
value.split(' ').forEach(word => {
w += word.charAt(0).toUpperCase() + word.toString().substr(1, word.length).toLowerCase() + ' '
});
} else {
w = value.charAt(0).toUpperCase() + value.toString().substr(1, value.length).toLowerCase();
}
return w;
}
return value;
}
}
try this with jQuery:
$('body').load( url,[data],[callback] );
Read more at docs.jquery.com / Ajax / load
What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.
In your component
[
{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map((anObjectMapped, index) => {
return (
<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
{anObjectMapped.name} - {anObjectMapped.email}
</p>
);
})
And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.
Take a look at my answer at mapping an array to jsx
You need to access the dataset
property:
document.getElementById("the-span").addEventListener("click", function() {
var json = JSON.stringify({
id: parseInt(this.dataset.typeid),
subject: this.dataset.type,
points: parseInt(this.dataset.points),
user: "Luïs"
});
});
Result:
// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
There are a lot of answers to delete the SUO / hidden solution files.
In my case it was because I needed to run Visual Studio as an Admin in order publish. Which overrode those files with admin permissions. Now when running as a standard user I can not get rid of any errors.
If I re-run in admin mode I am able to resolve all the errors.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
U can use MySQL Proxy and its scripting system to view SQL queries in realtime in the terminal.
try out this if you want to assign value to object and it is showing this error in angular..
crate object in construtor
this.modelObj = new Model();
//<---------- after declaring object above
its happen when you try to delete the same object and then again update the same object use this after delete
session.clear();
May be Everything? It supports regexps and has a console util too.
If you want to remove the outline when focused as well try:
input[type="text"],
input[type="text"]:focus
{
background: transparent;
border: none;
outline-width: 0;
}
netem leverages functionality already built into Linux and userspace utilities to simulate networks. This is actually what Mark's answer refers to, by a different name.
The examples on their homepage already show how you can achieve what you've asked for:
Examples
Emulating wide area network delays
This is the simplest example, it just adds a fixed amount of delay to all packets going out of the local Ethernet.
# tc qdisc add dev eth0 root netem delay 100ms
Now a simple ping test to host on the local network should show an increase of 100 milliseconds. The delay is limited by the clock resolution of the kernel (Hz). On most 2.4 systems, the system clock runs at 100 Hz which allows delays in increments of 10 ms. On 2.6, the value is a configuration parameter from 1000 to 100 Hz.
Later examples just change parameters without reloading the qdisc
Real wide area networks show variability so it is possible to add random variation.
# tc qdisc change dev eth0 root netem delay 100ms 10ms
This causes the added delay to be 100 ± 10 ms. Network delay variation isn't purely random, so to emulate that there is a correlation value as well.
# tc qdisc change dev eth0 root netem delay 100ms 10ms 25%
This causes the added delay to be 100 ± 10 ms with the next random element depending 25% on the last one. This isn't true statistical correlation, but an approximation.
Delay distribution
Typically, the delay in a network is not uniform. It is more common to use a something like a normal distribution to describe the variation in delay. The netem discipline can take a table to specify a non-uniform distribution.
# tc qdisc change dev eth0 root netem delay 100ms 20ms distribution normal
The actual tables (normal, pareto, paretonormal) are generated as part of the iproute2 compilation and placed in /usr/lib/tc; so it is possible with some effort to make your own distribution based on experimental data.
Packet loss
Random packet loss is specified in the 'tc' command in percent. The smallest possible non-zero value is:
2-32 = 0.0000000232%
# tc qdisc change dev eth0 root netem loss 0.1%
This causes 1/10th of a percent (i.e. 1 out of 1000) packets to be randomly dropped.
An optional correlation may also be added. This causes the random number generator to be less random and can be used to emulate packet burst losses.
# tc qdisc change dev eth0 root netem loss 0.3% 25%
This will cause 0.3% of packets to be lost, and each successive probability depends by a quarter on the last one.
Probn = 0.25 × Probn-1 + 0.75 × Random
Note that you should use tc qdisc add
if you have no rules for that interface or tc qdisc change
if you already have rules for that interface. Attempting to use tc qdisc change
on an interface with no rules will give the error RTNETLINK answers: No such file or directory
.
Since spaces are used to separate command line arguments, they have to be escaped from the shell. This can be done with either a backslash () or quotes:
"/path/with/spaces in it/to/a/file"
somecommand -spaced\ option
somecommand "-spaced option"
somecommand '-spaced option'
This is assuming you're running from a shell. If you're writing code, you can usually pass the arguments directly, avoiding the problem:
Example in perl. Instead of doing:
print("code sample");
system("somecommand -spaced option");
you can do
print("code sample");
system("somecommand", "-spaced option");
Since when you pass the system() call a list, it doesn't break arguments on spaces like it does with a single argument call.
First check to see if it can be cast.
if (readData is T) {
return (T)readData;
}
try {
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException) {
return default(T);
}
The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.
Let's say you have a list of integers, and want to find the items that match those integers.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var items = from p in context.Items
where numbers.Contains(p.ItemId)
select p;
Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0
I was building a nav menu. I have overflow: hidden
in my nav's css which hid everything. I thought it was a z-index problem, but really I was hiding everything outside my nav.
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
This might be seen as a little complex but does exactly what you want
SELECT
DISTINCT(p.`ProductID`) AS ProductID,
SUM(pl.CashAmount) AS Cash,
SUM(pr.CashAmount) AS `Check`,
SUM(px.CashAmount) AS `Credit Card`,
SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
`payments` AS p
LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl
ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr
ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px
ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;
Output
ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
3 | 20 | 15 | 25 | 60
4 | 5 | 6 | 7 | 18
Using break
, just as practically any other language feature, can be a bad practice, within a specific context, where you are clearly misusing it. But some very important idioms cannot be coded without it, or at least would result in far less readable code. In those cases, break
is the way to go.
In other words, don't listen to any blanket, unqualified advice—about break
or anything else. It is not once that I've seen code totally emaciated just to literally enforce a "good practice".
Regarding your concern about performance overhead, there is absolutely none. At the bytecode level there are no explicit loop constructs anyway: all flow control is implemented in terms of conditional jumps.
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
{
int iii1=0;
int iii2=0;
int iii3=0;
while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
// iii2 is the number of the occurences
if(iii2>0) {
positions_ = new int[iii2];
while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
positions_[iii3] = iii1-1;
iii3 = iii3 + 1;
System.out.println("position=" + positions_[iii3 - 1]);
}
}
return iii2;
}
After try all those command line, and it is not work.I have to do following stuff:
mv /usr/local/Cellar/mysql/5.7.16/bin/mysqld /usr/local/Cellar/mysql/5.7.16/bin/mysqld.bak
mysql.server stop
This way works, the mysqld process is gone. but the /var/log/system.log have a lot of rubbish:
Jul 9 14:10:54 xxx com.apple.xpc.launchd[1] (homebrew.mxcl.mysql[78049]): Service exited with abnormal code: 1
Jul 9 14:10:54 xxx com.apple.xpc.launchd[1] (homebrew.mxcl.mysql): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
You can set the width in pixels via inline styling:
<input type="text" name="text" style="width: 195px;">
You can also set the width with a visible character length:
<input type="text" name="text" size="35">
Watching this course https://app.pluralsight.com/library/courses/angular-2-getting-started-update/discussion
The author explains that new version of JavaScript has for of and for in, the for of is to enumerate objects and the for in is to enumerate the index of the array.
Learn from Apple is the best way.
For example, Apple's keyboard notification:
extension UIResponder {
public class let keyboardWillShowNotification: NSNotification.Name
public class let keyboardDidShowNotification: NSNotification.Name
public class let keyboardWillHideNotification: NSNotification.Name
public class let keyboardDidHideNotification: NSNotification.Name
}
Now I learn from Apple:
extension User {
/// user did login notification
static let userDidLogInNotification = Notification.Name(rawValue: "User.userDidLogInNotification")
}
What's more, NSAttributedString.Key.foregroundColor
:
extension NSAttributedString {
public struct Key : Hashable, Equatable, RawRepresentable {
public init(_ rawValue: String)
public init(rawValue: String)
}
}
extension NSAttributedString.Key {
/************************ Attributes ************************/
@available(iOS 6.0, *)
public static let foregroundColor: NSAttributedString.Key // UIColor, default blackColor
}
Now I learn form Apple:
extension UIFont {
struct Name {
}
}
extension UIFont.Name {
static let SFProText_Heavy = "SFProText-Heavy"
static let SFProText_LightItalic = "SFProText-LightItalic"
static let SFProText_HeavyItalic = "SFProText-HeavyItalic"
}
usage:
let font = UIFont.init(name: UIFont.Name.SFProText_Heavy, size: 20)
Learn from Apple is the way everyone can do and can promote your code quality easily.
You can iterate through JavaScript objects this way:
for(var attributename in myobject){
console.log(attributename+": "+myobject[attributename]);
}
myobject could be your json.data
Do aman 2 sendfile
. You only need to open the source file on the client and destination file on the server, then call sendfile and the kernel will chop and move the data.
Additionally for gists, it seems you must leave out the username
git remote set-url origin [email protected]:<Project code>
Use stream_context_set_default
function. It is much easier to use as you can directly use file_get_contents or similar functions without passing any additional parameters
This blog post explains how to use it. Here is the code from that page.
<?php
// Edit the four values below
$PROXY_HOST = "proxy.example.com"; // Proxy server address
$PROXY_PORT = "1234"; // Proxy server port
$PROXY_USER = "LOGIN"; // Username
$PROXY_PASS = "PASSWORD"; // Password
// Username and Password are required only if your proxy server needs basic authentication
$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
stream_context_set_default(
array(
'http' => array(
'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
'request_fulluri' => true,
'header' => "Proxy-Authorization: Basic $auth"
// Remove the 'header' option if proxy authentication is not required
)
)
);
$url = "http://www.pirob.com/";
print_r( get_headers($url) );
echo file_get_contents($url);
?>
Select * from table where date > 'Today's date(mm/dd/yyyy)'
You can also add time in the single quotes(00:00:00AM)
For example:
Select * from Receipts where Sales_date > '08/28/2014 11:59:59PM'
You could use https://github.com/flew-software/trash-dump you can create file that is any size and with random data
heres a command you can run after installing trash-dump (creates a 1GB file)
$ trash-dump --filename="huge" --seed=1232 --noBytes=1000000000
BTW I created it
In my project I did it like this:
@register.simple_tag()
def format_string(string: str, *args: str) -> str:
"""
Adds [args] values to [string]
String format [string]: "Drew %s dad's %s dead."
Function call in template: {% format_string string "Dodd's" "dog's" %}
Result: "Drew Dodd's dad's dog's dead."
"""
return string % args
Here, the string you want concatenate and the args can come from the view, for example.
In template and using your case:
{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}
The nice part is that format_string can be reused for any type of string formatting in templates
You can compile your C programs with an ARM cross-compiler:
arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test
Then you can push your compiled binary file to somewhere (don't push it in to the SD card):
adb push test /data/local/tmp/test
Just a friendly reminder if you have files locally that aren't in github and yet your git status
says
Your branch is up to date with 'origin/master'. nothing to commit, working tree clean
It can happen if the files are in .gitignore
Try running
cat .gitignore
and seeing if these files show up there. That would explain why git doesn't want to move them to the remote.
According to the w3c, cols and rows are both required attributes for textareas. Rows and Cols are the number of characters that are going to fit in the textarea rather than pixels or some other potentially arbitrary value. Go with the rows/cols.
I found this online validator from 'corefiling' quite useful -
http://www.corefiling.com/opensource/schemaValidate.html
After trying few tools to validate my xsd, this is the one which gave me detailed error info - so I was able to fix the error in schema.
struct arg_struct *args = (struct arg_struct *)args;
--> this assignment is wrong, I mean the variable argument should be used in this context. Cheers!!!
If you have a vector of names already,which there are several ways to create, you can easily use the subset function to keep or drop an object.
dat2 <- subset(dat, select = names(dat) %in% c(KEEP))
In this case KEEP is a vector of column names which is pre-created. For example:
#sample data via Brandon Bertelsen
df <- data.frame(a=rnorm(100),
b=rnorm(100),
c=rnorm(100),
d=rnorm(100),
e=rnorm(100),
f=rnorm(100),
g=rnorm(100))
#creating the initial vector of names
df1 <- as.matrix(as.character(names(df)))
#retaining only the name values you want to keep
KEEP <- as.vector(df1[c(1:3,5,6),])
#subsetting the intial dataset with the object KEEP
df3 <- subset(df, select = names(df) %in% c(KEEP))
Which results in:
> head(df)
a b c d
1 1.05526388 0.6316023 -0.04230455 -0.1486299
2 -0.52584236 0.5596705 2.26831758 0.3871873
3 1.88565261 0.9727644 0.99708383 1.8495017
4 -0.58942525 -0.3874654 0.48173439 1.4137227
5 -0.03898588 -1.5297600 0.85594964 0.7353428
6 1.58860643 -1.6878690 0.79997390 1.1935813
e f g
1 -1.42751190 0.09842343 -0.01543444
2 -0.62431091 -0.33265572 -0.15539472
3 1.15130591 0.37556903 -1.46640276
4 -1.28886526 -0.50547059 -2.20156926
5 -0.03915009 -1.38281923 0.60811360
6 -1.68024349 -1.18317733 0.42014397
> head(df3)
a b c e
1 1.05526388 0.6316023 -0.04230455 -1.42751190
2 -0.52584236 0.5596705 2.26831758 -0.62431091
3 1.88565261 0.9727644 0.99708383 1.15130591
4 -0.58942525 -0.3874654 0.48173439 -1.28886526
5 -0.03898588 -1.5297600 0.85594964 -0.03915009
6 1.58860643 -1.6878690 0.79997390 -1.68024349
f
1 0.09842343
2 -0.33265572
3 0.37556903
4 -0.50547059
5 -1.38281923
6 -1.18317733
You cannot TRUNCATE
a table that has FK constraints applied on it (TRUNCATE
is not the same as DELETE
).
To work around this, use either of these solutions. Both present risks of damaging the data integrity.
Option 1:
TRUNCATE
Option 2: suggested by user447951 in their answer
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table $table_name;
SET FOREIGN_KEY_CHECKS = 1;
In your 'encrypt' method, you should either get rid of the try/catch and instead add a try/catch around where you call encrypt (inside 'actionPerformed') or return null inside the catch within encrypt (that's the second error.
this worked in java 8
public static boolean contains(final int[] array, final int key)
{
return Arrays.stream(array).anyMatch(n->n==key);
}
a = dict(one=1, two=2, three=3)
Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
Here is the mistake: as someone said before, you are using org.pharmacy insted of com.pharmacy in componentscan
package **com**.pharmacy.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("**org**.pharmacy")
public class SpringBootRunner {
use admin
db.createUser(
{
user: "admin",
pwd: "admin123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
mongod --auth
in case of linux you can edit the /etc/mongod.conf
file to add security.authorization : enabled
and then restart the mongd servicemongo -u "admin" -p "admin123" --authenticationDatabase "admin"
. That's itYou can check out this post to go into more details and to learn connecting to it using mongoose.
in the Kotlin you can do this simply: all you need is to create a static variable like this:
companion object {
var last_position = 0
}
then in your onBindViewHolder add this code:
holder.item.setOnClickListener{
holder.item.setBackgroundResource(R.drawable.selected_item)
notifyItemChanged(last_position)
last_position=position
}
which item is the child of recyclerView which you want to change its background after clicking on it.
I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...
I use @Thiho answer but i get this error:
'git' is not recognized as an internal or external command
For solving that i use this steps:
I add the following paths to PATH:
C:\Program Files\Git\bin\
C:\Program Files\Git\cmd\
In windows 7:
Finally close and re-open your console.
In my case I have to use something like <username>@<domain>
to successfully login.
sample_user@sample_domain
Font awesome is just a font so you can use the font size attribute in your CSS to change the size of the icon.
So you can just add a class to the icon like this:
.big-icon {
font-size: 32px;
}
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).
http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp
Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU
var testModule = angular.module('testmodule', []);
testModule
.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.service('myservice', function() {
this.xxx = "yyy";
});
For:
2 mod 4
We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.
A mod B = C
where C is the answer
K * B - A = |C|
where K is how many times B fits in A
2 mod 4
would be:
0 * 4 - 2 = |C|
C = |-2| => 2
Hope it works for you :)
Try shFlags -- Advanced command-line flag library for Unix shell scripts.
http://code.google.com/p/shflags/
It is very good and very flexible.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.
DEFINE_string: takes any input, and intreprets it as a string.
DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.
DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.
DEFINE_integer: takes an input and intreprets it as an integer.
SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing
EXAMPLE USAGE:
-- begin hello.sh --
! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --
$ ./hello.sh -n Kate
Hello, Kate.
Note: I took this text from shflags documentation
If it helps someone you can just use css property
text-decoration-color: red;
I was not able to clone a repository due to have logged on with other credentials.
To switch to another user, I >>desperate<< did:
git config --global --unset user.name
git config --global --unset user.email
git config --global --unset credential.helper
after, instead using ssh link, I used HTTPS link. It asked for credentials and it worked fine FOR ME!
First off the warning is generated by the variable definition in the source file not the header file. The header can stay pristine and should, since you might be using something like doxygen to generate the API-documentation.
I will assume that you have completely different implementation in source files. In these cases you can either comment out the offending parameter or just write the parameter.
Example:
func(int a, int b)
{
b;
foo(a);
}
This might seem cryptic, so defined a macro like UNUSED. The way MFC did it is:
#ifdef _DEBUG
#define UNUSED(x)
#else
#define UNUSED(x) x
#endif
Like this you see the warning still in debug builds, might be helpful.
The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);
echo $dt->format('F j, Y @ G:i');