in my case I have used -
(Hyphen) in my script name in case of Jenkinsfile Library.
Got resolved after replacing Hyphen(-) with Underscore(_)
For ViewPager2,
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
})
where OnPageChangeCallback
is a static class with three methods:
onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position),
onPageScrollStateChanged(@ScrollState int state)
Try this:
"dependencies" : {
"name1" : "git://github.com/user/project.git#commit-ish",
"name2" : "git://github.com/user/project.git#commit-ish"
}
You could also try this, where visionmedia/express is name/repo:
"dependencies" : {
"express" : "visionmedia/express"
}
Or (if the npm package module exists):
"dependencies" : {
"name": "*"
}
Taken from NPM docs
The following code is less complex and gives the same result. Note that 'X' is the number of seconds to be converted to hours.
In Oracle use:
SELECT TO_CHAR (TRUNC (SYSDATE) + NUMTODSINTERVAL (X, 'second'),
'hh24:mi:ss'
) hr
FROM DUAL;
In SqlServer use:
SELECT CONVERT(varchar, DATEADD(s, X, 0), 108);
A complex filter condition is better in performance perspective, but the best performance will show old fashion for loop with a standard if clause
is the best option. The difference on a small array 10 elements difference might ~ 2 times, for a large array the difference is not that big.
You can take a look on my GitHub project, where I did performance tests for multiple array iteration options
For small array 10 element throughput ops/s: For medium 10,000 elements throughput ops/s: For large array 1,000,000 elements throughput ops/s:
NOTE: tests runs on
UPDATE: Java 11 has some progress on the performance, but the dynamics stay the same
This workaround worked for me. I edited the serverInfo.properties file as given below:
server.info=Apache Tomcat/8.0.0
server.number=8.0.0.0
server.built=Oct 6 2016 20:15:31 UTC
Much easier to use Pandas for basic one-hot encoding. If you're looking for more options you can use scikit-learn
.
For basic one-hot encoding with Pandas you pass your data frame into the get_dummies function.
For example, if I have a dataframe called imdb_movies:
...and I want to one-hot encode the Rated column, I do this:
pd.get_dummies(imdb_movies.Rated)
This returns a new dataframe
with a column for every "level" of rating that exists, along with either a 1 or 0 specifying the presence of that rating for a given observation.
Usually, we want this to be part of the original dataframe
. In this case, we attach our new dummy coded frame onto the original frame using "column-binding.
We can column-bind by using Pandas concat function:
rated_dummies = pd.get_dummies(imdb_movies.Rated)
pd.concat([imdb_movies, rated_dummies], axis=1)
We can now run an analysis on our full dataframe
.
SIMPLE UTILITY FUNCTION
I would recommend making yourself a utility function to do this quickly:
def encode_and_bind(original_dataframe, feature_to_encode):
dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
res = pd.concat([original_dataframe, dummies], axis=1)
return(res)
Usage:
encode_and_bind(imdb_movies, 'Rated')
Result:
Also, as per @pmalbu comment, if you would like the function to remove the original feature_to_encode then use this version:
def encode_and_bind(original_dataframe, feature_to_encode):
dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
res = pd.concat([original_dataframe, dummies], axis=1)
res = res.drop([feature_to_encode], axis=1)
return(res)
You can encode multiple features at the same time as follows:
features_to_encode = ['feature_1', 'feature_2', 'feature_3',
'feature_4']
for feature in features_to_encode:
res = encode_and_bind(train_set, feature)
resoverall
is a sqlalchemy ResultProxy object. You can read more about it in the sqlalchemy docs, the latter explains basic usage of working with Engines and Connections. Important here is that resoverall
is dict like.
Pandas likes dict like objects to create its data structures, see the online docs
Good luck with sqlalchemy and pandas.
Arrays' constructors are different. Here are some ways to make an empty string array:
var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()
(sorry, on mobile)
I was able to get mine working using the following Client Credentials:
Authorized JavaScript origins
http://localhost
Authorized redirect URIs
http://localhost:8090/oauth2callback
Note: I used port 8090 instead of 8080, but that doesn't matter as long as your python script uses the same port as your client_secret.json file.
Reference: Python Quickstart
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.
For further visitors:
// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);
// get_where sample,
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);
// Produces: LIMIT 10
$this->db->limit(10);
// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);
You can use enums to implement an interface.
public interface Room {
public Room north();
public Room south();
public Room east();
public Room west();
}
public enum Rooms implements Room {
FIRST {
public Room north() {
return SECOND;
}
},
SECOND {
public Room south() {
return FIRST;
}
}
public Room north() { return null; }
public Room south() { return null; }
public Room east() { return null; }
public Room west() { return null; }
}
EDIT: Years later....
I use this feature here
public enum AffinityStrategies implements AffinityStrategy {
By using an interface, developers can define their own strategies. Using an enum
means I can define a collection (of five) built in ones.
sometimes require a carriage return:
os.popen("sudo -S %s"%(command), 'w').write('mypass\n')
The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window
I know it's not the answer you want, but IMO the proposed solutions are not good (and your own way is). Why? Because they depend on the application state. In JavaFX, a control, a scene and a stage do not depend on each other. This means a control can live without being added to a scene and a scene can exist without being attached to a stage. And then, at a time instant t1, control can get attached to a scene and at instant t2, that scene can be added to a stage (and that explains why they are observable properties of each other).
So the approach that suggests getting the controller reference and invoking a method, passing the stage to it adds a state to your application. This means you need to invoke that method at the right moment, just after the stage is created. In other words, you need to follow an order now: 1- Create the stage 2- Pass this created stage to the controller via a method.
You cannot (or should not) change this order in this approach. So you lost statelessness. And in software, generally, state is evil. Ideally, methods should not require any call order.
So what is the right solution? There are two alternatives:
1- Your approach, in the controller listening properties to get the stage. I think this is the right approach. Like this:
pane.sceneProperty().addListener((observableScene, oldScene, newScene) -> {
if (oldScene == null && newScene != null) {
// scene is set for the first time. Now its the time to listen stage changes.
newScene.windowProperty().addListener((observableWindow, oldWindow, newWindow) -> {
if (oldWindow == null && newWindow != null) {
// stage is set. now is the right time to do whatever we need to the stage in the controller.
((Stage) newWindow).maximizedProperty().addListener((a, b, c) -> {
if (c) {
System.out.println("I am maximized!");
}
});
}
});
}
});
2- You do what you need to do where you create the Stage
(and that's not what you want):
Stage stage = new Stage();
stage.maximizedProperty().addListener((a, b, c) -> {
if (c) {
System.out.println("I am maximized!");
}
});
stage.setScene(someScene);
...
JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output>
element and an oninput
form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):
<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
<input type="password" name="p1" value="" required />
<input type="password" name="p2" value="" required />
<output name="result"></output>
</form>
I had the same error, because I was trying to manipulate session variables inside a custom Session class.
I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.
MA
private float distanceFrom_in_Km(float lat1, float lng1, float lat2, float lng2) {
if (lat1== null || lng1== null || lat2== null || lng2== null)
{
return null;
}
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
There is a third recovery mode not mentioned above. The recovery mode ultimately determines how large the LDF files become and how ofter they are written to. In cases where you are going to be doing any type of bulk inserts, you should set the DB to be in "BULK/LOGGED". This makes bulk inserts move speedily along and can be changed on the fly.
To do so,
USE master ;
ALTER DATABASE model SET RECOVERY BULK_LOGGED ;
To change it back:
USE master ;
ALTER DATABASE model SET RECOVERY FULL ;
In the spirit of adding to the conversation about why someone would not want an LDF, I add this: We do multi-dimensional modelling. Essentially we use the DB as a large store of variables that are processed in bulk using external programs. We do not EVER require rollbacks. If we could get a performance boost by turning of ALL logging, we'd take it in a heart beat.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$rt = curl_exec($ch);
$info = curl_getinfo($ch);
echo $info["http_code"];
Google Page-Speed: Don't include a query string in the URL for static resources. Most proxies, most notably Squid up through version 3.0, do not cache resources with a "?" in their URL even if a Cache-control: public header is present in the response. To enable proxy caching for these resources, remove query strings from references to static resources, and instead encode the parameters into the file names themselves.
In this case, you can include the version into URL ex: http://abc.com/v1.2/script.js and use apache mod_rewrite to redirect the link to http://abc.com/script.js. When you change the version, client browser will update the new file.
If not work, try
1. clean the project.
2. deleted derived data.
if you don't know how to delete derived data go here
If you are using an IBM JVM, download the IBM Thread and Monitor Dump Analyzer. It is an excellent tool. It provides thread detail and can point out deadlocks, etc. The following blog post provides a nice overview on how to use it.
For dynamic 2D charts, I have been using JChart2D. It's fast, simple, and being updated regularly. The author has been quick to respond to my one bug report and few feature requests. We, at our company, prefer it over JFreeChart because it was designed for dynamic use, unlike JFreeChart.
There is a system function called ISNUMERIC for SQL 2008 and up. An example:
SELECT myCol
FROM mTable
WHERE ISNUMERIC(myCol)<> 1;
I did a couple of quick tests and also looked further into the docs:
ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.
Which means it is fairly predictable for example
-9879210433
would pass but 987921-0433
does not.
$9879210433
would pass but 9879210$433
does not.
So using this information you can weed out based on the list of valid currency symbols and +
& -
characters.
There could be a very big misunderstanding related to string in the database are. Almost everyone has thought that database representation of numbers are more compact than for strings. They think that in db-s numbers are represented as in the memory. BUT it is not true. In most cases number representation is more close to A string like representation as to other.
The speed of using number or string is more dependent on the indexing then the type itself.
You could use event delegation on the parent div. Or use the closest method to find the parent of the button.
The easiest of the two is probably the closest.
var id = $("button").closest("div").prop("id");
declare
z exception;
begin
if to_char(sysdate,'day')='sunday' then
raise z;
end if;
exception
when z then
dbms_output.put_line('to day is sunday');
end;
You can try to use myPySQL. It's really easy to use; no compilation for windows, and even if you need to compile it for any reason, you only need Python and Visual C installed (not mysql).
http://code.google.com/p/mypysql/
Good luck
You can use this syntax:
#!/bin/bash
echo " Write in your age: "
read age
if [[ "$age" -le 7 || "$age" -ge 65 ]] ; then
echo " You can walk in for free "
elif [[ "$age" -gt 7 && "$age" -lt 65 ]] ; then
echo " You have to pay for ticket "
fi
You can save String and custom array list using Gson library.
=>First you need to create function to save array list to SharedPreferences.
public void saveListInLocal(ArrayList<String> list, String key) {
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
=> You need to create function to get array list from SharedPreferences.
public ArrayList<String> getListFromLocal(String key)
{
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
=> How to call save and retrieve array list function.
ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());
=> Don't forgot to add gson library in you app level build.gradle.
implementation 'com.google.code.gson:gson:2.8.2'
ulimit max memory size and virtual memory set to unlimited?
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM tablename"); //delete all rows in a table
db.close();
this work for me :)
curl -H @<header_file> <host>
Since curl 7.55 headers from file are supported with @<file>
echo 'Cookie: USER_TOKEN=Yes' > /tmp/cookie
curl -H @/tmp/cookie <host>
You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:
import httplib2 as http
import json
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
uri = 'http://yourservice.com'
path = '/path/to/resource/'
target = urlparse(uri+path)
method = 'GET'
body = ''
h = http.Http()
# If you need authentication some example:
if auth:
h.add_credentials(auth.user, auth.password)
response, content = h.request(
target.geturl(),
method,
body,
headers)
# assume that content is a json reply
# parse content with the json module
data = json.loads(content)
The Swift version from String to Data and back to String:
Xcode 10.1 • Swift 4.2.1
extension Data {
var string: String? {
return String(data: self, encoding: .utf8)
}
}
extension StringProtocol {
var data: Data {
return Data(utf8)
}
}
extension String {
var base64Decoded: Data? {
return Data(base64Encoded: self)
}
}
Playground
let string = "Hello World" // "Hello World"
let stringData = string.data // 11 bytes
let base64EncodedString = stringData.base64EncodedString() // "SGVsbG8gV29ybGQ="
let stringFromData = stringData.string // "Hello World"
let base64String = "SGVsbG8gV29ybGQ="
if let data = base64String.base64Decoded {
print(data) // 11 bytes
print(data.base64EncodedString()) // "SGVsbG8gV29ybGQ="
print(data.string ?? "nil") // "Hello World"
}
let stringWithAccent = "Olá Mundo" // "Olá Mundo"
print(stringWithAccent.count) // "9"
let stringWithAccentData = stringWithAccent.data // "10 bytes" note: an extra byte for the acute accent
let stringWithAccentFromData = stringWithAccentData.string // "Olá Mundo\n"
You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.
My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries.
Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID
WHERE p.isactive = 1
The better version of this query is :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1
(Assuming isactive is a field in product table which represents the active/inactive products).
apparently on sql server 2008 r2 64bit, with long running query from IIS the kill spid doesn't seem to work, the query just gets restarted again and again. and it seems to be reusing the spid's. the query is causing sql server to take like 35% cpu constantly and hang the website. I'm guessing bc/ it can't respond to other queries for logging in
Without using any type of JOIN cumulative salary for a person fetch by using follow query:
SELECT * , (
SELECT SUM( salary )
FROM `abc` AS table1
WHERE table1.ID <= `abc`.ID
AND table1.name = `abc`.Name
) AS cum
FROM `abc`
ORDER BY Name
Here's a really nice and simple way of doing it with really easy to follow instructions using a custom MultiButtonAttribute:
To summarise, make your submit buttons like this:
<input type="submit" value="Cancel" name="action" />
<input type="submit" value="Create" name="action" />
Your actions like this:
[HttpPost]
[MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
public ActionResult Cancel()
{
return Content("Cancel clicked");
}
[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
public ActionResult Create(Person person)
{
return Content("Create clicked");
}
And create this class:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string MatchFormKey { get; set; }
public string MatchFormValue { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request[MatchFormKey] != null &&
controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
}
}
I tried a couple of solution but I thing easy way like this (you are in the local folder):
#!/bin/bash
git fetch
var_local=`cat .git/refs/heads/master`
var_remote=`git log origin/master -1 | head -n1 | cut -d" " -f2`
if [ "$var_remote" = "$var_local" ]; then
echo "Strings are equal." #1
else
echo "Strings are not equal." #0 if you want
fi
Then you did compare local git and remote git last commit number....
I found out just now that it might be because of Fast Boot
option in Settings
> Power
When I have this option off, my application receives a this broadcast but not otherwise.
By the way, I have Android 2.3.3
on HTC Incredible S
.
Hope it helps.
Polished version + case ignoring support:
public static int[] AllIndexesOf(string str, string substr, bool ignoreCase = false)
{
if (string.IsNullOrWhiteSpace(str) ||
string.IsNullOrWhiteSpace(substr))
{
throw new ArgumentException("String or substring is not specified.");
}
var indexes = new List<int>();
int index = 0;
while ((index = str.IndexOf(substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) != -1)
{
indexes.Add(index++);
}
return indexes.ToArray();
}
Remove .idea folder
$rm -R .idea/
Add rule
$echo ".idea/*" >> .gitignore
Commit .gitignore file
$git commit -am "remove .idea"
Next commit will be ok
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
Pelo Hyper-V:
private PerformanceCounter theMemCounter = new PerformanceCounter(
"Hyper-v Dynamic Memory VM",
"Physical Memory",
Process.GetCurrentProcess().ProcessName);
ShowPopUpForToDoList: function (id, apprId, tab) {
var snapShot = "isFromAlert";
if (tab != "Request")
snapShot = "isFromTodoList";
$.ajax({
type: "GET",
url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
data: { id: id, tab: tab },
async:false,
success: function (data) {
ActionForm.EditActionFormPopup(id, snapShot);
}
});
},
Here SetParamForToDoList
will be excecuted first after the function ActionForm.EditActionFormPopup
will fire.
MsgBox("Variable {0} " , variable)
Here is a solution written in golang. The method is similar to some other answers posted here, but not quite the same. It is easy to implement, and has been tested. Here are the steps:
The values for A, B, and C for the quadratic are derived here, where (n-et) and (m-dt) are the equations for the line's x and y coordinates, respectively. r is the radius of the circle.
(n-et)(n-et) + (m-dt)(m-dt) = rr
nn - 2etn + etet + mm - 2mdt + dtdt = rr
(ee+dd)tt - 2(en + dm)t + nn + mm - rr = 0
Therefore A = ee+dd, B = - 2(en + dm), and C = nn + mm - rr.
Here is the golang code for the function:
package geom
import (
"math"
)
// SegmentCircleIntersection return points of intersection between a circle and
// a line segment. The Boolean intersects returns true if one or
// more solutions exist. If only one solution exists,
// x1 == x2 and y1 == y2.
// s1x and s1y are coordinates for one end point of the segment, and
// s2x and s2y are coordinates for the other end of the segment.
// cx and cy are the coordinates of the center of the circle and
// r is the radius of the circle.
func SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r float64) (x1, y1, x2, y2 float64, intersects bool) {
// (n-et) and (m-dt) are expressions for the x and y coordinates
// of a parameterized line in coordinates whose origin is the
// center of the circle.
// When t = 0, (n-et) == s1x - cx and (m-dt) == s1y - cy
// When t = 1, (n-et) == s2x - cx and (m-dt) == s2y - cy.
n := s2x - cx
m := s2y - cy
e := s2x - s1x
d := s2y - s1y
// lineFunc checks if the t parameter is in the segment and if so
// calculates the line point in the unshifted coordinates (adds back
// cx and cy.
lineFunc := func(t float64) (x, y float64, inBounds bool) {
inBounds = t >= 0 && t <= 1 // Check bounds on closed segment
// To check bounds for an open segment use t > 0 && t < 1
if inBounds { // Calc coords for point in segment
x = n - e*t + cx
y = m - d*t + cy
}
return
}
// Since we want the points on the line distance r from the origin,
// (n-et)(n-et) + (m-dt)(m-dt) = rr.
// Expanding and collecting terms yeilds the following quadratic equation:
A, B, C := e*e+d*d, -2*(e*n+m*d), n*n+m*m-r*r
D := B*B - 4*A*C // discriminant of quadratic
if D < 0 {
return // No solution
}
D = math.Sqrt(D)
var p1In, p2In bool
x1, y1, p1In = lineFunc((-B + D) / (2 * A)) // First root
if D == 0.0 {
intersects = p1In
x2, y2 = x1, y1
return // Only possible solution, quadratic has one root.
}
x2, y2, p2In = lineFunc((-B - D) / (2 * A)) // Second root
intersects = p1In || p2In
if p1In == false { // Only x2, y2 may be valid solutions
x1, y1 = x2, y2
} else if p2In == false { // Only x1, y1 are valid solutions
x2, y2 = x1, y1
}
return
}
I tested it with this function, which confirms that solution points are within the line segment and on the circle. It makes a test segment and sweeps it around the given circle:
package geom_test
import (
"testing"
. "**put your package path here**"
)
func CheckEpsilon(t *testing.T, v, epsilon float64, message string) {
if v > epsilon || v < -epsilon {
t.Error(message, v, epsilon)
t.FailNow()
}
}
func TestSegmentCircleIntersection(t *testing.T) {
epsilon := 1e-10 // Something smallish
x1, y1 := 5.0, 2.0 // segment end point 1
x2, y2 := 50.0, 30.0 // segment end point 2
cx, cy := 100.0, 90.0 // center of circle
r := 80.0
segx, segy := x2-x1, y2-y1
testCntr, solutionCntr := 0, 0
for i := -100; i < 100; i++ {
for j := -100; j < 100; j++ {
testCntr++
s1x, s2x := x1+float64(i), x2+float64(i)
s1y, s2y := y1+float64(j), y2+float64(j)
sc1x, sc1y := s1x-cx, s1y-cy
seg1Inside := sc1x*sc1x+sc1y*sc1y < r*r
sc2x, sc2y := s2x-cx, s2y-cy
seg2Inside := sc2x*sc2x+sc2y*sc2y < r*r
p1x, p1y, p2x, p2y, intersects := SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r)
if intersects {
solutionCntr++
//Check if points are on circle
c1x, c1y := p1x-cx, p1y-cy
deltaLen1 := (c1x*c1x + c1y*c1y) - r*r
CheckEpsilon(t, deltaLen1, epsilon, "p1 not on circle")
c2x, c2y := p2x-cx, p2y-cy
deltaLen2 := (c2x*c2x + c2y*c2y) - r*r
CheckEpsilon(t, deltaLen2, epsilon, "p2 not on circle")
// Check if points are on the line through the line segment
// "cross product" of vector from a segment point to the point
// and the vector for the segment should be near zero
vp1x, vp1y := p1x-s1x, p1y-s1y
crossProd1 := vp1x*segy - vp1y*segx
CheckEpsilon(t, crossProd1, epsilon, "p1 not on line ")
vp2x, vp2y := p2x-s1x, p2y-s1y
crossProd2 := vp2x*segy - vp2y*segx
CheckEpsilon(t, crossProd2, epsilon, "p2 not on line ")
// Check if point is between points s1 and s2 on line
// This means the sign of the dot prod of the segment vector
// and point to segment end point vectors are opposite for
// either end.
wp1x, wp1y := p1x-s2x, p1y-s2y
dp1v := vp1x*segx + vp1y*segy
dp1w := wp1x*segx + wp1y*segy
if (dp1v < 0 && dp1w < 0) || (dp1v > 0 && dp1w > 0) {
t.Error("point not contained in segment ", dp1v, dp1w)
t.FailNow()
}
wp2x, wp2y := p2x-s2x, p2y-s2y
dp2v := vp2x*segx + vp2y*segy
dp2w := wp2x*segx + wp2y*segy
if (dp2v < 0 && dp2w < 0) || (dp2v > 0 && dp2w > 0) {
t.Error("point not contained in segment ", dp2v, dp2w)
t.FailNow()
}
if s1x == s2x && s2y == s1y { //Only one solution
// Test that one end of the segment is withing the radius of the circle
// and one is not
if seg1Inside && seg2Inside {
t.Error("Only one solution but both line segment ends inside")
t.FailNow()
}
if !seg1Inside && !seg2Inside {
t.Error("Only one solution but both line segment ends outside")
t.FailNow()
}
}
} else { // No intersection, check if both points outside or inside
if (seg1Inside && !seg2Inside) || (!seg1Inside && seg2Inside) {
t.Error("No solution but only one point in radius of circle")
t.FailNow()
}
}
}
}
t.Log("Tested ", testCntr, " examples and found ", solutionCntr, " solutions.")
}
Here is the output of the test:
=== RUN TestSegmentCircleIntersection
--- PASS: TestSegmentCircleIntersection (0.00s)
geom_test.go:105: Tested 40000 examples and found 7343 solutions.
Finally, the method is easily extendable to the case of a ray starting at one point, going through the other and extending to infinity, by only testing if t > 0 or t < 1 but not both.
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier
.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
You can use and implement Secure Licensing API from very easily in your Software Projects using it,(you need to download the desktop application for creating secure license from https://www.systemsoulsoftwares.com/)
Issue is with remote server, can you login to the remote server and check if "scp" works
probable causes: - scp is not in path - openssh client not installed correctly
for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/
An array is a pointer. It points to the start of a sequence of "objects".
If we do this: ìnt arr[10];
, then arr
is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];
.
For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be
docker.io/<dockerimagename>:version
The suggestion above of registry.hub.docker.com/library/<dockerimagename>
did not work for me.
I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
from names) n2
on (n2.author_id = n1.author_id)
Where true
used distinct
if more inner join, because more join group performance is slow
But I have declared that var in the top of the other files.
That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const
.
Instead, use var
, use only one declaration in your main file, or only assign to window.APP
exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.
<a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })" type="submit" id="runReport" target="_blank" class="button Secondary"> @Reports.RunReport </a>
If you just want the last date for each account, you'd use this:
var q = from n in table
group n by n.AccountId into g
select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};
If you want the whole record:
var q = from n in table
group n by n.AccountId into g
select g.OrderByDescending(t=>t.Date).FirstOrDefault();
Transaction - is just a logically composed set of operations you want all together be either committed or rolled back.
Open the PHP file under question, in Notepad++.
Click on Encoding at the top and change from "Encoding in UTF-8 without BOM" to just "Encoding in UTF-8". Save and overwrite the file on your server.
I would like to give you also the idea to disable an <option>
with a given defined value (not innerhtml
). I recommend to it with jQuery
to get the simplest way. See my sample below.
HTML
Status:
<div id="option">
<select class="status">
<option value="hand" selected>Hand</option>
<option value="simple">Typed</option>
<option value="printed">Printed</option>
</select>
</div>
Javascript
The idea here is how to disable Printed
option when current Status
is Hand
var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
You may see how it works here:
One more jQuery solution
For a single stylesheet with id "css" try this:
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:
var reloadCSS = function() {
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};
Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:
ALTER TABLE dbo.Content
ADD CONSTRAINT FK_Content_Libraries
FOREIGN KEY(LibraryID, Application)
REFERENCES dbo.Libraries(ID, Application)
Is that what you're using?? If (ID, Application)
is indeed the primary key on dbo.Libraries
, this statement should definitely work.
Luk: just to check - can you run this statement in your database and report back what the output is??
SELECT
tc.TABLE_NAME,
tc.CONSTRAINT_NAME,
ccu.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
tc.TABLE_NAME IN ('Libraries', 'Content')
I think there is only one intuitive solution and it is:
int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);
Output:
First: 1
Last: 5
While the other answers are correct, there is an easy way to get rid of the underline on all those pesky links:
a {
text-decoration:none;
}
This will remove the underline from EVERY SINGLE LINK on your page!
@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :
<h:inputHidden value="#{loginBean.loginStatus}"/>
and in your bean code:
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getLoginStatus() {
// Do your stuff here.
return loginStatus;
}
That can be achieve in plain LaTeX without any specific package.
\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
\left\{
\begin{array}{l}
0\\
1
\end{array}
\right.
\end{math}
\end{document}
This code produces something which looks what you seems to need.
The same example as in the @Tombart can be obtained with similar code.
\documentclass{article}
\begin{document}
\begin{math}
f(x)=\left\{
\begin{array}{ll}
1, & \mbox{if $x<0$}.\\
0, & \mbox{otherwise}.
\end{array}
\right.
\end{math}
\end{document}
This code produces very similar results.
What's the difference between VARCHAR and CHAR in MySQL?
To already given answers I would like to add that in OLTP systems or in systems with frequent updates consider using CHAR
even for variable size columns because of possible VARCHAR
column fragmentation during updates.
I am trying to store MD5 hashes.
MD5 hash is not the best choice if security really matters. However, if you will use any hash function, consider BINARY
type for it instead (e.g. MD5 will produce 16-byte hash, so BINARY(16)
would be enough instead of CHAR(32)
for 32 characters representing hex digits. This would save more space and be performance effective.
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
Further to @Kyle Kelley and @DGrady, here is the entry which can be found in the
$HOME/.ipython/profile_default/ipython_kernel_config.py
(or whichever profile you have created)
Change
# Configure matplotlib for interactive use with the default matplotlib backend.
# c.IPKernelApp.matplotlib = none
to
# Configure matplotlib for interactive use with the default matplotlib backend.
c.IPKernelApp.matplotlib = 'inline'
This will then work in both ipython qtconsole and notebook sessions.
In agreement with aleho's response here's a complete example. It works like a charm and is super simple.
Controller code
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
Javascript code in the view
var url = '@Html.Raw(@Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
Hope this helps someone else!
This is an old question, but attempting to apply a new field (either NEWID() or ORDER BY rand()) to a table with a large number of rows would be prohibitively expensive. If you have incremental, unique IDs (and do not have any holes) it will be more efficient to calculate the X # of IDs to be selected instead of applying a GUID or similar to every single row and then taking the top X # of.
DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];
DECLARE @randomId1 int, @randomId2 int, @randomId3 int, @randomId4 int, @randomId5 int
SET @randomId1 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId2 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId3 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId4 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId5 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
--select @maxValue as MaxValue, @minValue as MinValue
-- , @randomId1 as SelectedId1
-- , @randomId2 as SelectedId2
-- , @randomId3 as SelectedId3
-- , @randomId4 as SelectedId4
-- , @randomId5 as SelectedId5
select * from [TABLE] el
where el.id in (@randomId1, @randomId2, @randomId3, @randomId4, @randomId5)
If you wanted to select many more rows I would look into populating a #tempTable with an ID and a bunch of rand() values then using each rand() value to scale to the min-max values. That way you do not have to define all of the @randomId1...n parameters. I've included an example below using a CTE to populate the initial table.
DECLARE @NumItems int = 100;
DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];
DECLARE @range int = @maxValue+1 - @minValue;
with cte (n) as (
select 1 union all
select n+1 from cte
where n < @NumItems
)
select cast( @range * rand(cast(newid() as varbinary(100))) + @minValue as int) tp
into #Nt
from cte;
select * from #Nt ntt
inner join [TABLE] i on i.id = ntt.tp;
drop table #Nt;
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
div
has an ID.class
"collapse", this will hide your block by
default. If you want your div to be collapsible AND be shown by
default you need to add "in" class to the collapse. Otherwise the
toggle behavior will not work properly.data-toggle="collapse"
to instruct
Bootstrap to add an appropriate toggle script to this tag.Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
This div (Bar) is shown by default and can toggle
</div>
1 Way
Use document.cloneNode()
Performance is:
Call to document.cloneNode()
took ~0.22499999977299012 milliseconds.
and maybe will be more.
var t0, t1, html;
t0 = performance.now();
html = document.cloneNode(true);
t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
html.documentElement.innerHTML = '<!DOCTYPE html><html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';
console.log(html.getElementById("test1"));
_x000D_
2 Way
Use document.implementation.createHTMLDocument()
Performance is:
Call to document.implementation.createHTMLDocument()
took ~0.14000000010128133 milliseconds.
var t0, t1, html;
t0 = performance.now();
html = document.implementation.createHTMLDocument("test");
t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
html.documentElement.innerHTML = '<!DOCTYPE html><html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';
console.log(html.getElementById("test1"));
_x000D_
3 Way
Use document.implementation.createDocument()
Performance is:
Call to document.implementation.createHTMLDocument()
took ~0.14000000010128133 milliseconds.
var t0 = performance.now();
html = document.implementation.createDocument('', 'html',
document.implementation.createDocumentType('html', '', '')
);
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
html.documentElement.innerHTML = '<html><head><title>Test</title></head><body><div id="test1">test</div></body></html>';
console.log(html.getElementById("test1"));
4 Way
Use new Document()
Performance is:
Call to document.implementation.createHTMLDocument()
took ~0.13499999840860255 milliseconds.
ParentNode.append
is experimental technology in 2020 year.
var t0, t1, html;
t0 = performance.now();
//---------------
html = new Document();
html.append(
html.implementation.createDocumentType('html', '', '')
);
html.append(
html.createElement('html')
);
//---------------
t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
html.documentElement.innerHTML = '<html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';
console.log(html.getElementById("test1"));
If you "want to return a fixed value when the input parameter has a particular value", maybe you don't even need a mock and could use a dict
along with its get
method:
foo = {'input1': 'value1', 'input2': 'value2'}.get
foo('input1') # value1
foo('input2') # value2
This works well when your fake's output is a mapping of input. When it's a function of input I'd suggest using side_effect
as per Amber's answer.
You can also use a combination of both if you want to preserve Mock
's capabilities (assert_called_once
, call_count
etc):
self.mock.side_effect = {'input1': 'value1', 'input2': 'value2'}.get
You can Change Backcolor
row by row using your condition.and this function call after applying Datasource
of DatagridView
.
Here Is the function for that.
Simply copy that and put it after Databind
private void ChangeRowColor()
{
for (int i = 0; i < gvItem.Rows.Count; i++)
{
if (BindList[i].MainID == 0 && !BindList[i].SchemeID.HasValue)
gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#C9CADD");
else if (BindList[i].MainID > 0 && !BindList[i].SchemeID.HasValue)
gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#DDC9C9");
else if (BindList[i].MainID > 0)
gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#D5E8D7");
else
gvItem.Rows[i].DefaultCellStyle.BackColor = Color.White;
}
}
Do the following:
npm i bootstrap@next --save
This will add bootstrap 4 to your project.
Next go to your src/style.scss
or src/style.css
file (choose whichever you are using) and import bootstrap there:
For style.css
/* You can add global styles to this file, and also import other style files */
@import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
For style.scss
/* You can add global styles to this file, and also import other style files */
@import "../node_modules/bootstrap/scss/bootstrap";
For scripts you will still have to add the file in the angular-cli.json file like so (In Angular version 6, this edit needs to be done in the file angular.json):
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
Very very minified version of http://www.featureblend.com/javascript-flash-detection-library.html (only boolean flash detection)
var isFlashInstalled = (function(){
var b=new function(){var n=this;n.c=!1;var a="ShockwaveFlash.ShockwaveFlash",r=[{name:a+".7",version:function(n){return e(n)}},{name:a+".6",version:function(n){var a="6,0,21";try{n.AllowScriptAccess="always",a=e(n)}catch(r){}return a}},{name:a,version:function(n){return e(n)}}],e=function(n){var a=-1;try{a=n.GetVariable("$version")}catch(r){}return a},i=function(n){var a=-1;try{a=new ActiveXObject(n)}catch(r){a={activeXError:!0}}return a};n.b=function(){if(navigator.plugins&&navigator.plugins.length>0){var a="application/x-shockwave-flash",e=navigator.mimeTypes;e&&e[a]&&e[a].enabledPlugin&&e[a].enabledPlugin.description&&(n.c=!0)}else if(-1==navigator.appVersion.indexOf("Mac")&&window.execScript)for(var t=-1,c=0;c<r.length&&-1==t;c++){var o=i(r[c].name);o.activeXError||(n.c=!0)}}()};
return b.c;
})();
if(isFlashInstalled){
// Do something with flash
}else{
// Don't use flash
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function scollPos() {
var div = document.getElementById("myDiv").scrollTop;
document.getElementById("pos").innerHTML = div;
}
</script>
</head>
<body>
<form id="form1">
<div id="pos">
</div>
<div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
Place some large content here
</div>
</form>
</body>
</html>
You can use the margin
property:
li.menu-item {
margin:0 0 10px 0;
}
The accepted answer only renamed the user but the privileges were left behind.
I'd recommend using:
RENAME USER 'foo'@'1.2.3.4' TO 'foo'@'1.2.3.5';
According to MySQL documentation:
RENAME USER causes the privileges held by the old user to be those held by the new user.
From June 2018 Android officially support this feature for Android 4.0 (API level 14) and higher.
With Android 8.0 (API level 26) and higher:
setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize,
int autoSizeStepGranularity, int unit);
Android versions prior to Android 8.0 (API level 26):
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(TextView textView,
int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)
Check out my detail answer.
You can also use LocalBroadcast
for this purpose. Here is a quick guide
Create a broadcast receiver:
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("speedExceeded"));
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Double currentSpeed = intent.getDoubleExtra("currentSpeed", 20);
Double currentLatitude = intent.getDoubleExtra("latitude", 0);
Double currentLongitude = intent.getDoubleExtra("longitude", 0);
// ... react to local broadcast message
}
This is how you can trigger it
Intent intent = new Intent("speedExceeded");
intent.putExtra("currentSpeed", currentSpeed);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
unRegister receiver in onPause:
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
Well, the code that renders the button enabled/disabled:
if(name.getText().equals("")) {
loginbt.setEnabled(false);
}else {
loginbt.setEnabled(true);
}
must be written in javax.swing.event.ChangeListener
and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?
Get the library from http://commons.apache.org/net/download_net.cgi
//NTP server list: http://tf.nist.gov/tf-cgi/servers.cgi
public static final String TIME_SERVER = "time-a.nist.gov";
public static long getCurrentNetworkTime() {
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
//long returnTime = timeInfo.getReturnTime(); //local device time
long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); //server time
Date time = new Date(returnTime);
Log.d(TAG, "Time from " + TIME_SERVER + ": " + time);
return returnTime;
}
getReturnTime() is same as System.currentTimeMillis().
getReceiveTimeStamp() or getTransmitTimeStamp() method should be used.
You can see the difference after setting system time to 1 hour ago.
local time :
System.currentTimeMillis()
timeInfo.getReturnTime()
timeInfo.getMessage().getOriginateTimeStamp().getTime()
NTP server time :
timeInfo.getMessage().getReceiveTimeStamp().getTime()
timeInfo.getMessage().getTransmitTimeStamp().getTime()
To load python code reliably, have that code in a module, and that module installed in python's library.
Installed modules can always be loaded from the top level namespace with import <name>
There is a great sample project available officially here: https://github.com/pypa/sampleproject
Basically, you can have a directory structure like so:
the_foo_project/
setup.py
bar.py # `import bar`
foo/
__init__.py # `import foo`
baz.py # `import foo.baz`
faz/ # `import foo.faz`
__init__.py
daz.py # `import foo.faz.daz` ... etc.
.
Be sure to declare your setuptools.setup()
in setup.py
,
official example: https://github.com/pypa/sampleproject/blob/master/setup.py
In our case we probably want to export bar.py
and foo/__init__.py
, my brief example:
#!/usr/bin/env python3
import setuptools
setuptools.setup(
...
py_modules=['bar'],
packages=['foo'],
...
entry_points={},
# Note, any changes to your setup.py, like adding to `packages`, or
# changing `entry_points` will require the module to be reinstalled;
# `python3 -m pip install --upgrade --editable ./the_foo_project
)
.
Now we can install our module into the python library;
with pip, you can install the_foo_project
into your python library in edit mode,
so we can work on it in real time
python3 -m pip install --editable=./the_foo_project
# if you get a permission error, you can always use
# `pip ... --user` to install in your user python library
.
Now from any python context, we can load our shared py_modules and packages
#!/usr/bin/env python3
import bar
import foo
print(dir(bar))
print(dir(foo))
Try this way header('Content-Type: text/plain; charset=utf-8');
You can use the setTimeout
or setInterval
functions.
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
According to docker docs,
Both CMD and ENTRYPOINT instructions define what command gets executed when running a container. There are few rules that describe their co-operation.
- Dockerfile should specify at least one of
CMD
orENTRYPOINT
commands.ENTRYPOINT
should be defined when using the container as an executable.CMD
should be used as a way of defining default arguments for anENTRYPOINT
command or for executing an ad-hoc command in a container.CMD
will be overridden when running the container with alternative arguments.
The tables below shows what command is executed for different ENTRYPOINT
/ CMD
combinations:
-- No ENTRYPOINT
+----------------------------------------------------------+
¦ No CMD ¦ error, not allowed ¦
¦----------------------------+-----------------------------¦
¦ CMD ["exec_cmd", "p1_cmd"] ¦ exec_cmd p1_cmd ¦
¦----------------------------+-----------------------------¦
¦ CMD ["p1_cmd", "p2_cmd"] ¦ p1_cmd p2_cmd ¦
¦----------------------------+-----------------------------¦
¦ CMD exec_cmd p1_cmd ¦ /bin/sh -c exec_cmd p1_cmd ¦
+----------------------------------------------------------+
-- ENTRYPOINT exec_entry p1_entry
+---------------------------------------------------------------+
¦ No CMD ¦ /bin/sh -c exec_entry p1_entry ¦
¦----------------------------+----------------------------------¦
¦ CMD ["exec_cmd", "p1_cmd"] ¦ /bin/sh -c exec_entry p1_entry ¦
¦----------------------------+----------------------------------¦
¦ CMD ["p1_cmd", "p2_cmd"] ¦ /bin/sh -c exec_entry p1_entry ¦
¦----------------------------+----------------------------------¦
¦ CMD exec_cmd p1_cmd ¦ /bin/sh -c exec_entry p1_entry ¦
+---------------------------------------------------------------+
-- ENTRYPOINT ["exec_entry", "p1_entry"]
+------------------------------------------------------------------------------+
¦ No CMD ¦ exec_entry p1_entry ¦
¦----------------------------+-------------------------------------------------¦
¦ CMD ["exec_cmd", "p1_cmd"] ¦ exec_entry p1_entry exec_cmd p1_cmd ¦
¦----------------------------+-------------------------------------------------¦
¦ CMD ["p1_cmd", "p2_cmd"] ¦ exec_entry p1_entry p1_cmd p2_cmd ¦
¦----------------------------+-------------------------------------------------¦
¦ CMD exec_cmd p1_cmd ¦ exec_entry p1_entry /bin/sh -c exec_cmd p1_cmd ¦
+------------------------------------------------------------------------------+
I had enabled the extension_dir in php.ini by uncommenting,
extension_dir = "ext"
extension=phpchartdir550.dll
and copying phpchartdir550 dll to the extension_dir (/usr/lib/php5/20121212), resulted in the same error.
PHP Warning: PHP Startup: Unable to load dynamic library 'ext/phpchartdir550.dll' - ext/phpchartdir550.dll: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning: PHP Startup: Unable to load dynamic library 'ext/pdo.so' - ext/pdo.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning: PHP Startup: Unable to load dynamic library 'ext/gd.so' - ext/gd.so: cannot open shared object file: No such file or directory in Unknown on line 0
As @Mike pointed out, it is not necessary to install all the stuff when they are not actually required in the application.
The easier way is to provide the full path to the extensions to be loaded after copying the libraries to the correct location.
Copy phpchartdir550.dll to /usr/lib/php5/20121212, which is the extension_dir in my Ubuntu 14.04 (this can be seen using phpinfo()) and then provide full path to the library in php.ini,
; extension=/path/to/extension/msql.so
extension=/usr/lib/php5/20121212/phpchartdir550.dll
restart apache: sudo service apache2 restart
even though other .so's are present in the same directory, only the required ones can be selectively loaded.
This line will unconditionally restart the running program from scratch:
os.execl(sys.executable, sys.executable, *sys.argv)
One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.
This can be useful if, for example, you are modifying its code in another window.
Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!
Right way
<table>
<tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
<td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">
<b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
<small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>
</td>
</tr>
</table>
Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:
BASE64: blahblah
UTF8: nVnV
not the other way around. I can't reproduce it completely in PS though. See sample below:
PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV?nV?
PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==
EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.
PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah
PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
????
PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah
Assume you have three view controllers instantiated like so:
UIViewController* vc1 = [[UIViewController alloc] init];
UIViewController* vc2 = [[UIViewController alloc] init];
UIViewController* vc3 = [[UIViewController alloc] init];
You have added them to a tab bar like this:
UITabBarController* tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:vc1, vc2, vc3, nil]];
Now you are trying to do something like this:
[tabBarController presentModalViewController:vc3];
This will give you an error because that Tab Bar Controller has a death grip on the view controller that you gave it. You can either not add it to the array of view controllers on the tab bar, or you can not present it modally.
Apple expects you to treat their UI elements in a certain way. This is probably buried in the Human Interface Guidelines somewhere as a "don't do this because we aren't expecting you to ever want to do this".
Use on :
$('#registered_participants').on('click', '.new_participant_form', function() {
So that the click is delegated to any element in #registered_participants
having the class new_participant_form
, even if it's added after you bound the event handler.
The Stream API was designed to make it easy to write computations in a way that was abstracted away from how they would be executed, making switching between sequential and parallel easy.
However, just because its easy, doesn't mean its always a good idea, and in fact, it is a bad idea to just drop .parallel()
all over the place simply because you can.
First, note that parallelism offers no benefits other than the possibility of faster execution when more cores are available. A parallel execution will always involve more work than a sequential one, because in addition to solving the problem, it also has to perform dispatching and coordinating of sub-tasks. The hope is that you'll be able to get to the answer faster by breaking up the work across multiple processors; whether this actually happens depends on a lot of things, including the size of your data set, how much computation you are doing on each element, the nature of the computation (specifically, does the processing of one element interact with processing of others?), the number of processors available, and the number of other tasks competing for those processors.
Further, note that parallelism also often exposes nondeterminism in the computation that is often hidden by sequential implementations; sometimes this doesn't matter, or can be mitigated by constraining the operations involved (i.e., reduction operators must be stateless and associative.)
In reality, sometimes parallelism will speed up your computation, sometimes it will not, and sometimes it will even slow it down. It is best to develop first using sequential execution and then apply parallelism where
(A) you know that there's actually benefit to increased performance and
(B) that it will actually deliver increased performance.
(A) is a business problem, not a technical one. If you are a performance expert, you'll usually be able to look at the code and determine (B), but the smart path is to measure. (And, don't even bother until you're convinced of (A); if the code is fast enough, better to apply your brain cycles elsewhere.)
The simplest performance model for parallelism is the "NQ" model, where N
is the number of elements, and Q
is the computation per element. In general, you need the product NQ to exceed some threshold before you start getting a performance benefit. For a low-Q problem like "add up numbers from 1
to N
", you will generally see a breakeven between N=1000
and N=10000
. With higher-Q problems, you'll see breakevens at lower thresholds.
But the reality is quite complicated. So until you achieve experthood, first identify when sequential processing is actually costing you something, and then measure if parallelism will help.
Just add the following line in your build.sbt
PlayKeys.devSettings := Seq("play.server.http.port" -> "8080")
Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)
The solution for me is:
I strongly recommend the pyenv-win project.
Thanks to kirankotari's work, now we have a Windows version of pyenv.
The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:
Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.
Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.
To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark
was used.
require_relative 'base'
require 'benchmark'
class LargeDOM < Base
LOCATORS = {
nested_sibling_traversal: {
css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
},
nested_sibling_traversal_by_class: {
css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
},
table_header_id_and_class: {
css: "table#large-table thead .column-50",
xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
},
table_header_id_class_and_direct_desc: {
css: "table#large-table > thead .column-50",
xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
},
table_header_traversing: {
css: "table#large-table thead tr th:nth-of-type(50)",
xpath: "//table[@id='large-table']//thead//tr//th[50]"
},
table_header_traversing_and_direct_desc: {
css: "table#large-table > thead > tr > th:nth-of-type(50)",
xpath: "//table[@id='large-table']/thead/tr/th[50]"
},
table_cell_id_and_class: {
css: "table#large-table tbody .column-50",
xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
},
table_cell_id_class_and_direct_desc: {
css: "table#large-table > tbody .column-50",
xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
},
table_cell_traversing: {
css: "table#large-table tbody tr td:nth-of-type(50)",
xpath: "//table[@id='large-table']//tbody//tr//td[50]"
},
table_cell_traversing_and_direct_desc: {
css: "table#large-table > tbody > tr > td:nth-of-type(50)",
xpath: "//table[@id='large-table']/tbody/tr/td[50]"
}
}
attr_reader :driver
def initialize(driver)
@driver = driver
visit '/large'
is_displayed?(id: 'siblings')
super
end
# The benchmarking approach was borrowed from
# http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
def benchmark
Benchmark.bmbm(27) do |bm|
LOCATORS.each do |example, data|
data.each do |strategy, locator|
bm.report(example.to_s + " using " + strategy.to_s) do
begin
ENV['iterations'].to_i.times do |count|
find(strategy => locator)
end
rescue Selenium::WebDriver::Error::NoSuchElementError => error
puts "( 0.0 )"
end
end
end
end
end
end
end
NOTE: The output is in seconds, and the results are for the total run time of 100 executions.
In Table Form:
In Chart Form:
You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.
The right way is to use Culture:
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())
Note: This will capitalise each word within a string, e.g. "red house" --> "Red House". The solution will also lower-case capitalisation within words, e.g. "old McDonald" --> "Old Mcdonald".
I am just updating this with Microsoft SQL Server Management Studio 2008 R2 version. if you run the installer normally, you can just add Management Tools – Basic, and by clicking Basic it should select Management Tools – Complete.
That is what worked for me.
this works for me, sudo apt-get install libx11-dev
The @Context
annotation (see answers in this question :What does context annotation do in Spring?) will cause it to be injected for you.
I had to use
@Context
private HttpServletRequest request;
I once had this problem. I realized that while moving a class, I had overwritten the .mm
file with .h
file on the destination folder.
Fixing that issue fixed the error.
You don't need to create any stored types, you can evaluate Oracle's built-in collection types.
select distinct column_value from table(sys.odcinumberlist(1,1,2,3,3,4,4,5))
Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.
cat test.csv | gzip > test.csv.gz
cat test.csv
will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.
make your class public
access modifier,
just add public
keyword infront of your class name
namespace Test
{
public class Delivery
{
private string name;
private string address;
private DateTime arrivalTime;
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public DateTime ArrivlaTime
{
get { return arrivalTime; }
set { arrivalTime = value; }
}
public string ToString()
{
{ return name + address + arrivalTime.ToString(); }
}
}
}
A solution based on a comment by kbjorklu is:
bool isNumber(const std::string& s)
{
return !s.empty() && s.find_first_not_of("-.0123456789") == std::string::npos;
}
As with David Rector's answer it is not robust to strings with multiple dots or minus signs, but you can remove those characters to just check for integers.
However, I am partial to a solution, based on Ben Voigt's solution, using strtod
in cstdlib to look decimal values, scientific/engineering notation, hexidecimal notation (C++11), or even INF/INFINITY/NAN (C++11) is:
bool isNumberC(const std::string& s)
{
char* p;
strtod(s.c_str(), &p);
return *p == 0;
}
querySelectorAll
function and split the values
string.Array#forEach
to iterate over every element from the values
array.Array#find
to find the option matching given value.selected
attribute to true
.Note: Array#from
transforms an array-like object into an array and then you are able to use Array.prototype
functions on it, like find or map.
var values = "Test,Prof,Off",_x000D_
options = Array.from(document.querySelectorAll('#strings option'));_x000D_
_x000D_
values.split(',').forEach(function(v) {_x000D_
options.find(c => c.value == v).selected = true;_x000D_
});
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
<option value="Test">Test</option>_x000D_
<option value="Prof">Prof</option>_x000D_
<option value="Live">Live</option>_x000D_
<option value="Off">Off</option>_x000D_
<option value="On">On</option>_x000D_
</select>
_x000D_
The RFC for the HTTP Header Field X-Frame-Options states that the "ALLOW-FROM" field in the X-Frame-Options header value can only contain one domain. Multiple domains are not allowed.
The RFC suggests a work around for this problem. The solution is to specify the domain name as a url parameter in the iframe src url. The server that hosts the iframe src url can then check the domain name given in the url parameters. If the domain name matches a list of valid domain names, then the server can send the X-Frame-Options header with the value: "ALLOW-FROM domain-name", where domain name is the name of the domain that is trying to embed the remote content. If the domain name is not given or is not valid, then the X-Frame-Options header can be sent with the value: "deny".
If you happen to have jQuery around, you can intercept the click on the link like this:
$(document).on('click', 'a', function (event) {
event.preventDefault();
window.open($(this).attr('href'), '_system');
return false;
});
This way you don't have to modify the links in the html, which can save a lot of time. I have set this up using a delegate, that's why you see it being tied to the document object, with the 'a' tag as the second argument. This way all 'a' tags will be handled, regardless of when they are added.
Ofcourse you still have to install the InAppBrowser plug-in:
cordova plugin add org.apache.cordova.inappbrowser
Just go to Web.Config
from Main
folder, not the one in Views
Folder:
configSections
section name="entityFramework" type="System.Data. .....,Version=" <strong>5</strong>.0.0.0"..
<..>
ADJUST THE VERSION OF EntityFramework you have installed, ex. like Version 6.0.0.0"
I allways use UPPER(text)
like UPPER('%blah%')
Scenario
I was getting SSLHandshake exceptions on devices running versions of Android earlier than Android 5.0. In my use case I also wanted to create a TrustManager to trust my client certificate.
I implemented NoSSLv3SocketFactory and NoSSLv3Factory to remove SSLv3 from my client's list of supported protocols but I could get neither of these solutions to work.
Some things I learned:
What worked for me
Allow Android's security Provider
to update when starting your app.
The default Provider before 5.0+ does not disable SSLv3. Provided you have access to Google Play services it is relatively straightforward to patch Android's security Provider from your app.
private void updateAndroidSecurityProvider(Activity callingActivity) {
try {
ProviderInstaller.installIfNeeded(this);
} catch (GooglePlayServicesRepairableException e) {
// Thrown when Google Play Services is not installed, up-to-date, or enabled
// Show dialog to allow users to install, update, or otherwise enable Google Play services.
GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), callingActivity, 0);
} catch (GooglePlayServicesNotAvailableException e) {
Log.e("SecurityException", "Google Play Services not available.");
}
}
If you now create your OkHttpClient or HttpURLConnection TLSv1.1 and TLSv1.2 should be available as protocols and SSLv3 should be removed. If the client/connection (or more specifically it's SSLContext) was initialised before calling ProviderInstaller.installIfNeeded(...)
then it will need to be recreated.
Don't forget to add the following dependency (latest version found here):
compile 'com.google.android.gms:play-services-auth:16.0.1'
Sources:
Aside
I didn't need to explicitly set which cipher algorithms my client should use but I found a SO post recommending those considered most secure at the time of writing: Which Cipher Suites to enable for SSL Socket?
This can be a good option if you want python completion as well as other languages. https://github.com/Valloric/YouCompleteMe
The python completion is jedi based same as jedi-vim.
Swift 5.1. Use with two extension, method return CALayer, so you would reuse it to update frames.
enum Border: Int {
case top = 0
case bottom
case right
case left
}
extension UIView {
func addBorder(for side: Border, withColor color: UIColor, borderWidth: CGFloat) -> CALayer {
let borderLayer = CALayer()
borderLayer.backgroundColor = color.cgColor
let xOrigin: CGFloat = (side == .right ? frame.width - borderWidth : 0)
let yOrigin: CGFloat = (side == .bottom ? frame.height - borderWidth : 0)
let width: CGFloat = (side == .right || side == .left) ? borderWidth : frame.width
let height: CGFloat = (side == .top || side == .bottom) ? borderWidth : frame.height
borderLayer.frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height)
layer.addSublayer(borderLayer)
return borderLayer
}
}
extension CALayer {
func updateBorderLayer(for side: Border, withViewFrame viewFrame: CGRect) {
let xOrigin: CGFloat = (side == .right ? viewFrame.width - frame.width : 0)
let yOrigin: CGFloat = (side == .bottom ? viewFrame.height - frame.height : 0)
let width: CGFloat = (side == .right || side == .left) ? frame.width : viewFrame.width
let height: CGFloat = (side == .top || side == .bottom) ? frame.height : viewFrame.height
frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height)
}
}
$*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
$@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).
Source: Bash man
For Bootstrap 3, there is
placement: 'auto right'
which is easier. By default, it will be right, but if the element is located in the right side of the screen, the popover will be left. So it should be:
$('.infopoint').popover({
trigger:'hover',
animation: false,
placement: 'auto right'
});
This article thoroughly explains the difference between different implementations of Python. Like the article puts it:
The first thing to realize is that ‘Python’ is an interface. There’s a specification of what Python should do and how it should behave (as with any interface). And there are multiple implementations (as with any interface).
The second thing to realize is that ‘interpreted’ and ‘compiled’ are properties of an implementation, not an interface.
Try to declare UseHttpGet over your method.
[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
return "Hello World";
}
document.getElementById('username').value="moo"
document.forms[0].submit()
We can mute it in this way (device and simulator need different values):
Add the Name OS_ACTIVITY_MODE
and the Value ${DEBUG_ACTIVITY_MODE}
and check it (in Product -> Scheme -> Edit Scheme -> Run -> Arguments -> Environment).
Add User-Defined Setting DEBUG_ACTIVITY_MODE
, then add Any iOS Simulator SDK
for Debug
and set it's value to disable
(in Project -> Build settings -> + -> User-Defined Setting)
Take a look at CBFG
and the Android port of the loading/rendering
code. You should be able to drop the code into your project and use it
straight away.
I have problems with this implementation. It displays only one character, when I try do change size of the font's bitmap (I need special letters) whole draw fails :(
The following code will split a string with an arbitrary number of substrings:
@echo off
setlocal ENABLEDELAYEDEXPANSION
REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=The;rain;in;spain
REM Do something with each substring
:stringLOOP
REM Stop when the string is empty
if "!teststring!" EQU "" goto END
for /f "delims=;" %%a in ("!teststring!") do set substring=%%a
REM Do something with the substring -
REM we just echo it for the purposes of demo
echo !substring!
REM Now strip off the leading substring
:striploop
set stripchar=!teststring:~0,1!
set teststring=!teststring:~1!
if "!teststring!" EQU "" goto stringloop
if "!stripchar!" NEQ ";" goto striploop
goto stringloop
)
:END
endlocal
Dto response = softConvertValue(jsonData, Dto.class);
public static <T> T softConvertValue(Object fromValue, Class<T> toValueType)
{
ObjectMapper objMapper = new ObjectMapper();
return objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.convertValue(fromValue, toValueType);
}
Technically there aren't actually any "remote" things at all1 in your Git repo, there are just local names that should correspond to the names on another, different repo. The ones named origin/whatever
will initially match up with those on the repo you cloned-from:
git clone ssh://some.where.out.there/some/path/to/repo # or git://some.where...
makes a local copy of the other repo. Along the way it notes all the branches that were there, and the commits those refer-to, and sticks those into your local repo under the names refs/remotes/origin/
.
Depending on how long you go before you git fetch
or equivalent to update "my copy of what's some.where.out.there", they may change their branches around, create new ones, and delete some. When you do your git fetch
(or git pull
which is really fetch plus merge), your repo will make copies of their new work and change all the refs/remotes/origin/<name>
entries as needed. It's that moment of fetch
ing that makes everything match up (well, that, and the initial clone, and some cases of push
ing too—basically whenever Git gets a chance to check—but see caveat below).
Git normally has you refer to your own refs/heads/<name>
as just <name>
, and the remote ones as origin/<name>
, and it all just works because it's obvious which one is which. It's sometimes possible to create your own branch names that make it not obvious, but don't worry about that until it happens. :-) Just give Git the shortest name that makes it obvious, and it will go from there: origin/master
is "where master was over there last time I checked", and master
is "where master is over here based on what I have been doing". Run git fetch
to update Git on "where master is over there" as needed.
Caveat: in versions of Git older than 1.8.4, git fetch
has some modes that don't update "where master is over there" (more precisely, modes that don't update any remote-tracking branches). Running git fetch origin
, or git fetch --all
, or even just git fetch
, does update. Running git fetch origin master
doesn't. Unfortunately, this "doesn't update" mode is triggered by ordinary git pull
. (This is mainly just a minor annoyance and is fixed in Git 1.8.4 and later.)
1Well, there is one thing that is called a "remote". But that's also local! The name origin
is the thing Git calls "a remote". It's basically just a short name for the URL you used when you did the clone. It's also where the origin
in origin/master
comes from. The name origin/master
is called a remote-tracking branch, which sometimes gets shortened to "remote branch", especially in older or more informal documentation.
You should be using
git stash save
and not
git stash create
because this creates a stash (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. Hence won't be accessible with stash apply.
Use git stash save "some comment"
is used when you have unstaged changes you wanna replicate/move onto another branch
Use git stash apply stash@{0}
(assuming your saved stash index is 0) when you want your saved(stashed) changes to reflect on your current branch
you can always use git stash list
to check all you stash indexes
and use git stash drop stash@{0}
(assuming your saved stash index is 0 and you wanna delete it) to delete a particular stash.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
If you have global environment variables defined outside Gradle,
test {
environment "ENV_VAR", System.getenv('ENV_VAR')
useJUnitPlatform()
}
This is what I use:
Uri baseUri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, String.Empty));
Then when I combine it with another relative path, I use the following:
string resourceRelative = "~/images/myImage.jpg";
Uri resourceFullPath = new Uri(baseUri, VirtualPathUtility.ToAbsolute(resourceRelative));
Use (keyup.enter)
.
Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter
pseudo-event.
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
For a binary number of n digits the maximum decimal value it can hold will be
2^n - 1, and 2^n is the total permutations that can be generated using these many digits.
Taking a case where you only want three digits, ie your case 1. We see that the requirements is,
2^n - 1 >= 999
Applying log to both sides,
log(2^n - 1) >= log(999)
log(2^n) - log(1) >= log(999)
n = 9.964 (approx).
Taking the ceil value of n since 9.964 can't be a valid number of digits, we get n = 10.
Sample Array: Left ones are the keys, right one are my values
$array = array(
'key-1' => 'value-1',
'key-2' => 'value-2',
'key-3' => 'value-3',
);
Example A: I want only the values of $array
foreach($array as $value) {
echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'
}
Example B: I want each value AND key of $array
foreach($array as $key => $value) {
echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'
echo $key; // Through $key I get access to 'key-1' then 'key-2' and finally 'key-3'
echo $array[$key]; // Accessing the value through $key = Same output as echo $value;
$array[$key] = $value + 1; // Exmaple usage of $key: Change the value by increasing it by 1
}
a less "Math" oriented approach ,but should also work , this way, the < / > test is exposed (maybe more understandable than minimaxing) but it really depends on what you mean by "readable"
function clamp(num, min, max) {
return num <= min ? min : num >= max ? max : num;
}
I have been trying to attach an audio which should autoplay and will be hidden. It's very simple. Just a few lines of HTML and CSS. Check this out!! Here is the piece of code I used within the body.
<div id="player">
<audio controls autoplay hidden>
<source src="file.mp3" type="audio/mpeg">
unsupported !!
</audio>
</div>
For some devices, if the default language is set different (an Indian can set English (US)) then
context.getResources().getConfiguration().locale.getDisplayCountry();
will give the wrong value. So this method is not reliable.
Also, getNetworkCountryIso() method of TelephonyManager will not work on devices which don't have SIM card (Wi-Fi tablets).
If a device doesn't have a SIM card then we can use the time zone to get the country. For countries like India, this method will work.
Use the below values in your constants file
(Constants.INDIA_TIME_ZONE_ID: "asia/calcutta", Constants.NETWORK_INDIA_CODE :"in")
And in your activity, add the following code:
private void checkCountry() {
TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telMgr == null)
return;
int simState = telMgr.getSimState();
switch (simState) {
// If a SIM card is not available then the
// country is found using the timezone ID
case TelephonyManager.SIM_STATE_ABSENT:
TimeZone tz = TimeZone.getDefault();
String timeZoneId = tz.getID();
if (timeZoneId.equalsIgnoreCase(Constants.INDIA_TIME_ZONE_ID)) {
// Do something
}
else {
// Do something
}
break;
// If a SIM card is available then the telephony
// manager network country information is used
case TelephonyManager.SIM_STATE_READY:
if (telMgr != null) {
String countryCodeValue = tm.getNetworkCountryIso();
// Check if the network country code is "in"
if (countryCodeValue.equalsIgnoreCase(Constants.NETWORK_INDIA_CODE)) {
// Do something
}
else {
// Do something
}
}
break;
}
}
In Java 0 or null are simple types and not objects.
The method equals() is not built for simple types. Simple types can be matched with ==.
MessageBox::Show
uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Here is a simple example :
Create or alter PROCEDURE getPersonCountByLastName (
@lastName varchar(20),
@count int OUTPUT
)
As
Begin
select @count = count(personSid) from Person where lastName like @lastName
End;
Execute below statements in one batch (by selecting all)
1. Declare @count int
2. Exec getPersonCountByLastName kumar, @count output
3. Select @count
When i tried to execute statements 1,2,3 individually, I had the same error. But when executed them all at one time, it worked fine.
The reason is that SQL executes declare, exec statements in different sessions.
Open to further corrections.
Since Android 7.0, logcat has --pid filter option, and pidof command is available, replace com.example.app to your package name.
(ubuntu terminal / Since Android 7.0)
adb logcat --pid=`adb shell pidof -s com.example.app`
or
adb logcat --pid=$(adb shell pidof -s com.example.app)
For more info about pidof command:
https://stackoverflow.com/a/15622698/7651532
Your code was right except you are not passing the JSON keys as strings.
It should have double or single quotes around it
{ "field1": "hello", "field2" : "hello2"}
$.ajax(
{
type: 'post',
url: 'superman',
data: {
"field1": "hello", // Quotes were missing
"field2": "hello1" // Here also
},
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
}
);
Use:
find . ! -readable -prune -o -print
or more generally
find <paths> ! -readable -prune -o <other conditions like -name> -print
Works with: find (GNU findutils) 4.4.2. Background:
-readable
test matches readable files. The !
operator returns true, when test is false. And ! -readable
matches not readable directories (&files).-prune
action does not descend into directory.! -readable -prune
can be translated to: if directory is not readable, do not descend into it.-readable
test takes into account access control lists and other permissions artefacts which the -perm
test ignores.See also find
(1) manpage for many more details.
An N-tier application is an application which has more than three components involved. What are those components?
All the social applications like Instagram, Facebook, large scale industry services like Uber, Airbnb, online massive multiplayer games like Pokemon Go, applications with fancy features are n-tier applications.
DB Transaction Log Shrink to min size:
I made tests on several number of DBs: this sequence works.
It usually shrinks to 2MB.
OR by a script:
DECLARE @DB_Name nvarchar(255);
DECLARE @DB_LogFileName nvarchar(255);
SET @DB_Name = '<Database Name>'; --Input Variable
SET @DB_LogFileName = '<LogFileEntryName>'; --Input Variable
EXEC
(
'USE ['+@DB_Name+']; '+
'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +
'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2) ' +
'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +
'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2)'
)
GO
You get the warning because you did not assign a value to one
, which is a pointer. This is undefined behavior.
You should declare it like this:
Vector* one = malloc(sizeof(Vector));
or like this:
Vector one;
in which case you need to replace ->
operator with .
like this:
one.a = 12;
one.b = 13;
one.c = -11;
Finally, in C99 and later you can use designated initializers:
Vector one = {
.a = 12
, .b = 13
, .c = -11
};
Extend UITableView to create function that get indexpath for a view:
extension UITableView {
func indexPath(for view: UIView) -> IndexPath? {
self.indexPathForRow(at: view.convert(.zero, to: self))
}
}
How to use:
let row = tableView.indexPath(for: sender)?.row
What I need is a function which prints an object (obj), but only if global variable verbose is true, else it does nothing.
I want to be able to change the global parameter "verbose" at any time. Simplicity and readability to me are of paramount importance. So I would proceed as the following lines indicate:
ak@HP2000:~$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> verbose = True
>>> def vprint(obj):
... if verbose:
... print(obj)
... return
...
>>> vprint('Norm and I')
Norm and I
>>> verbose = False
>>> vprint('I and Norm')
>>>
Global variable "verbose" can be set from the parameter list, too.
The problem was the MySQL56 service was running and it has occupied the port of WAMP MySQL.After MySQL56 service stopped the WAMP server started successfully.
Also the error can be solved by adding several flags, like -marm -mthumb-interwork
. It was helpful for me to avoid this same error.
In the Spring configuration typo applicationContext.xml
where the sessionFactory
configured put this property
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="${package.name}"/>
Try this,
table{
border-collapse: collapse; /* 'cellspacing' equivalent */
}
table td,
table th{
padding: 0; /* 'cellpadding' equivalent */
}
Giving us the whole error message would be much more useful. If it's for make install then you're probably trying to install something to a system directory and you're not root. If you have root access then you can run
sudo make install
or log in as root and do the whole process as root.
You're the victim of the classic deadlock. task.Wait()
or task.Result
is a blocking call in UI thread which causes the deadlock.
Don't block in the UI thread. Never do it. Just await it.
private async void Button_Click(object sender, RoutedEventArgs
{
var task = GetResponseAsync<MyObject>("my url");
var items = await task;
}
Btw, why are you catching the WebException
and throwing it back? It would be better if you simply don't catch it. Both are same.
Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse
method. StreamReader.ReadToEnd
is a blocking call --you should be using StreamReader.ReadToEndAsync
.
Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.
Your method should look something like the following when you've addressed all the above concerns.
public static async Task<List<T>> GetResponseAsync<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
Stream stream = response.GetResponseStream();
StreamReader strReader = new StreamReader(stream);
string text = await strReader.ReadToEndAsync();
return JsonConvert.DeserializeObject<List<T>>(text);
}
echo "mydir/doc/ mydir/usoe ./mydir/usm" | awk '{ split($0,array," "); for(i in array){ system("cd "array[i]" && echo $PWD") } }'
I suggest you to use provider
.
Provide is good when you want to configure it first before to use (against Service/Factory)
Something like:
.provider('Magazines', function() {
this.url = '/';
this.urlArray = '/';
this.organId = 'Default';
this.$get = function() {
var url = this.url;
var urlArray = this.urlArray;
var organId = this.organId;
return {
invoke: function() {
return ......
}
}
};
this.setUrl = function(url) {
this.url = url;
};
this.setUrlArray = function(urlArray) {
this.urlArray = urlArray;
};
this.setOrganId = function(organId) {
this.organId = organId;
};
});
.config(function(MagazinesProvider){
MagazinesProvider.setUrl('...');
MagazinesProvider.setUrlArray('...');
MagazinesProvider.setOrganId('...');
});
And now controller:
function MyCtrl($scope, Magazines) {
Magazines.invoke();
....
}
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%.%MM%.%DD%.%HH%.%Min%.%Sec%"
set drive=your backup folder
set databaseName=your databasename
set user="your database user"
set password="your database password"
subst Z: "C:\Program Files\7-Zip"
subst M: "D:\AppServ\MySQL\bin"
set zipFile="%drive%\%databaseName%-%datestamp%.zip"
set sqlFile="%drive%\%databaseName%-%datestamp%.sql"
M:\mysqldump.exe --user=%user% --password=%password% --result-file="%sqlFile%" --databases %databaseName%
@echo Mysql Backup Created
Z:\7z.exe a -tzip "%zipFile%" "%sqlFile%"
@echo File Compress End
del %sqlFile%
@echo Delete mysql file
pause;
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
This actually happens because the complex objects are what makes the resulting json object fails. And it fails because when the object is mapped it maps the children, which maps their parents, making a circular reference to occur. Json would take infinite time to serialize it, so it prevents the problem with the exception.
Entity Framework mapping also produces the same behavior, and the solution is to discard all unwanted properties.
Just expliciting the final answer, the whole code would be:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
new {
Result = (from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
}
, JsonRequestBehavior.AllowGet
);
}
It could also be the following in case you don't want the objects inside a Result
property:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
(from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
, JsonRequestBehavior.AllowGet
);
}
This whole thread confused the h#$l out of me until I realized you have to be running the debugger to see ANY trace or debug output. I needed a debug output (outside of the debugger) because my WebApp runs fine when I debug it but not when the debugger isn't running (SqlDataSource is instantiated correctly when running through the debugger).
Just because debug output can be seen when you're running in release mode doesn't mean you'll see anything if you're not running the debugger. Careful reading of Writing to output window of Visual Studio? gave me DebugView as an alternative. Extremely useful!
Hopefully this helps anyone else confused by this.
An alternative is:
for(var word = ''; word.length < 10; word += 'a'){}
If you need to repeat multiple chars, multiply your conditional:
for(var word = ''; word.length < 10 * 3; word += 'foo'){}
NOTE: You do not have to overshoot by 1 as with word = Array(11).join('a')
I needed to ignore errors in multiple commands and fuckit did the trick
import fuckit
@fuckit
def helper():
print('before')
1/0
print('after1')
1/0
print('after2')
helper()
If you have successfully deleted from workspace tab but still it is showing in drop down menu. Then also you can successfully remove that by following these steps:
user_name will be your username of your computer
There will be two tag
varName = "RecentlyUsedWorkspaces" remove the deleted workspace tag
A propertyList tag will be there with varName=deleted_workspace_name delete that tag.
from drop down menu workspace name will be deleted
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
easiest way to append class name using javascript.
It can be useful when .siblings()
are misbehaving.
document.getElementById('myId').className += ' active';
There are three types of exposing your service Nodeport ClusterIP LoadBalancer
When we use a loadbalancer we basically ask our cloud provider to give us a dns which can be accessed online Note not a domain name but a dns.
So loadbalancer type does not work in our local minikube env.
You can add attributes using attr
like so:
$('#someid').attr('name', 'value');
However, for DOM properties like checked
, disabled
and readonly
, the proper way to do this (as of JQuery 1.6) is to use prop
.
$('#someid').prop('disabled', true);
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
Although cursors usually considered horrible evil I believe this is a case for FAST_FORWARD cursor - the closest thing you can get to FOREACH in TSQL.
I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. Its not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...
// Add code below ...
function locationHashChanged(qs)
{
var q = parseQs(qs);
// ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !!
// YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION
// THAT IS PASSED TO changeHashValue(hashQuery)
}
// CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ...
function changeHashValue(hashQuery)
{
stopHashListener();
hashValue = hashQuery;
location.hash = hashQuery;
startHashListener();
}
// AND DONT WORRY ABOUT ANYTHING BELOW ...
function checkIfHashChanged()
{
var hashQuery = getHashQuery();
if (hashQuery == hashValue)
return;
hashValue = hashQuery;
locationHashChanged(hashQuery);
}
function parseQs(qs)
{
var q = {};
var pairs = qs.split('&');
for (var idx in pairs) {
var arg = pairs[idx].split('=');
q[arg[0]] = arg[1];
}
return q;
}
function startHashListener()
{
hashListener = setInterval(checkIfHashChanged, 1000);
}
function stopHashListener()
{
if (hashListener != null)
clearInterval(hashListener);
hashListener = null;
}
function getHashQuery()
{
return location.hash.replace(/^#/, '');
}
var hashListener = null;
var hashValue = '';//getHashQuery();
startHashListener();
Get-ADPrincipalGroupMembership username | select name
Got it from another answer but the script works magic. :)
You may use negative superthick semi-transparent border...
.red {_x000D_
outline: 100px solid rgba(255, 0, 0, 0.5) !important;_x000D_
outline-offset: -100px;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
}
_x000D_
<div class="red">Anything can be red.</div>_x000D_
<h1>Or even image...</h1>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" class="red"/>
_x000D_
This solution requires you to know exact sizes of covered object.
There are several ways to implement modules in JavaScript. Here are the two most popular ones:
Browsers do not support this moduling system yet, so in order for you to use this syntax you must use a bundler like Webpack. Using a bundler is better anyway because this can combine all of your different files into a single (or a couple of related) files. This will serve the files from the server to the client faster because each HTTP request has some associated overhead accompanied with it. Thus by reducing the overall HTTP request we improve the performance. Here is an example of ES6 modules:
// main.js file
export function add (a, b) {
return a + b;
}
export default function multiply (a, b) {
return a * b;
}
// test.js file
import {add}, multiply from './main'; // For named exports between curly braces {export1, export2}
// For default exports without {}
console.log(multiply(2, 2)); // logs 4
console.log(add(1, 2)); // logs 3
This moduling system is used in Node.js. You basically add your exports to an object which is called module.exports
. You then can access this object via a require('modulePath')
. Important here is to realize that these modules are being cached, so if you require()
a certain module twice it will return the already created module.
// main.js file
function add (a, b) {
return a + b;
}
module.exports = add; // Here we add our 'add' function to the exports object
// test.js file
const add = require('./main');
console.log(add(1,2)); // logs 3
I'd check out SQLAlchemy
It's really easy to use and the models you work with aren't bad at all. Django uses SQLAlchemy for it's ORM but using it by itself lets you use it's full power.
Here's a small example on creating and selecting orm objects
>>> ed_user = User('ed', 'Ed Jones', 'edspassword')
>>> session.add(ed_user)
>>> our_user = session.query(User).filter_by(name='ed').first()
>>> our_user
<User('ed','Ed Jones', 'edspassword')>
I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.
Assuming your data is in ColumnA:C
and has column labels in Row 1, also that Month is formatted mmm
(this last for ease of sorting):
D2
=IF(AND(A2=A1,C2=C1),D1+1,1)
(One way to deal with what is the tricky issue of multiple entries for the same person for the same month).A1:D(last occupied row no.)
F1
.I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.
L1
.L1
and shift down.L1
.ColumnL
, select Row Labels
and numeric values.L2:L(last selected cell)
Happy to explain further/try again (I've not really tested this) if does not suit.
EDIT (To avoid second block of steps above and facilitate updating for source data changes)
.0. Before first step 2. add a blank row at the very top and move A2:D2
up.
.2. Adjust cell references accordingly (in D3
=IF(AND(A3=A2,C3=C2),D2+1,1)
.
.3. Create pivot table from A:D
.6. Overwrite Row Labels
with Name
.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1
, ColumnG
and rows and columns that show (blank)
.
Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).
Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank)
into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.
I had the same problem until I used a 3rd Party tool to generate the Class from the XSD and it worked! I discovered that the tool was adding some extra code at the top of my class. When I added this same code to the top of my original class it worked. Here's what I added...
#pragma warning disable
namespace MyNamespace
{
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Xml;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1064.2")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class MyClassName
{
...
The problem is where you are executing:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.
Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.
x='buffalo'
exec("%s = %d" % (x,2))
After that you can check it by:
print buffalo
As an output you will see:
2
You can use StringBuilder
in Aggregate
:
List<string> strings = new List<string>() { "one", "two", "three" };
StringBuilder sb = strings
.Select(s => s)
.Aggregate(new StringBuilder(), (ag, n) => ag.Append(n).Append(", "));
if (sb.Length > 0) { sb.Remove(sb.Length - 2, 2); }
Console.WriteLine(sb.ToString());
(The Select
is in there just to show you can do more LINQ stuff.)
For InstallShield MSI based projects I have found the following to work:
setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn"
This command will lead to an extracted MSI in a directory you can freely specify and a silently failed uninstall of the product.
The command line basically tells the setup.exe to attempt to uninstall the product (/x) and do so silently (/s). While doing that it should extract the MSI to a specific location (/b).
The /v command passes arguments to Windows Installer, in this case the /qn argument. The /qn argument disables any GUI output of the installer.
Jeff Bridgman is correct. All you need is
background: url('pic.jpg')
and this assumes that pic is in the same folder as your html.
Also, Roberto's answer works fine. Tested in Firefox, and IE. Thanks to Raptor for adding formatting that displays full picture fit to screen, and without scrollbars... In a folder f, on the desktop is this html and a picture, pic.jpg, using your userid. Make those substitutions in the below:
<html>
<head>
<style>
body {
background: url('file:///C:/Users/userid/desktop/f/pic.jpg') no-repeat center center fixed;
background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
-webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
-moz-background-size: cover; /* optional for Firefox 3.6 */
-o-background-size: cover; /* for Opera 9.5 */
margin: 0; /* to remove the default white margin of body */
padding: 0; /* to remove the default white margin of body */
overflow: hidden;
}
</style>
</head>
<body>
hello
</body>
</html>
You can simply use CSS transitions, see this fiddle
.on {
color:#fff;
transition:all 1s;
}
.off{
color:#000;
transition:all 1s;
}
It should be a comment to the basename answer but I haven't enough point.
If you do not use double quotes, basename
will not work with path where there is space character:
$ basename /home/foo/bar foo/bar.png
bar
ok with quotes " "
$ basename "/home/foo/bar foo/bar.png"
bar.png
file example
$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3
$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3
Your code is reading a sequence of UTF8-encoded bytes, and decoding them using an 8-bit encoding.
You need to fix that code to decode the bytes as UTF8.
Alternatively (not ideal), you could convert the bad string back to the original byte array—by encoding it using the incorrect encoding—then re-decode the bytes as UTF8.
A JUnit4 test with Autowired and bean mocking (Mockito):
// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
"spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {
@MockBean
private PersonRepository repository;
@Autowired
private PersonService personService; // uses PersonRepository
@Test
public void testSomething() {
// using Mockito
when(repository.findByName(any())).thenReturn(Collection.emptyList());
Person person = new Person();
person.setName(null);
// when
boolean found = personService.checkSomething(person);
// then
assertTrue(found, "Something is wrong");
}
}
I would start with something simple, like a Koch Snowflake. It's a simple process of taking a line and transforming it, then repeating the process recursively until it looks neat-o.
Something super simple like taking 2 points (a line) and adding a 3rd point (making a corner), then repeating on each new section that's created.
fractal(p0, p1){
Pmid = midpoint(p0,p1) + moved some distance perpendicular to p0 or p1;
fractal(p0,Pmid);
fractal(Pmid, p1);
}
As of Laravel 5 the database username and password goes in the .env file that exists in the project directory, e.g.
DB_HOST=127.0.0.1
DB_DATABASE=db1
DB_USERNAME=user1
DB_PASSWORD=pass1
As you can see these environment variables are overriding the 'forge' strings here so changing them has no effect:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
More information is here https://mattstauffer.co/blog/laravel-5.0-environment-detection-and-environment-variables
This might be an alternative solution. Paste the following code into the new module:
Public Function ModDate()
ModDate =
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm")
End Function
Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.
Paste the following code into the cell where you want to display the last modification time:
=ModDate()
I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel
SELECT CONVERT(nvarchar(6), GETDATE(), 112)
Real VNC Viewer (5.0.3) - Free :
Options->Expert->UseAllMonitors = True
Use arrows or hjkl
to get to one of the bracketing expressions, then v
to select visual (i.e. selecting) mode, then %
to jump to the other bracket.
A bit late but I hope it helps someone.
Some time ago even I faced a problem where the string data contained \n
in between and while reading the file it used to read as different lines.
Eg.
"Harry\nPotter","21","Gryffindor"
While-Reading:
Harry
Potter,21,Gryffindor
I had used a library csvtojson in my angular project to solve this problem.
You can read the CSV file as a string using the following code and then pass that string to the csvtojson library and it will give you a list of JSON.
Sample Code:
const csv = require('csvtojson');
if (files && files.length > 0) {
const file: File = files.item(0);
const reader: FileReader = new FileReader();
reader.readAsText(file);
reader.onload = (e) => {
const csvs: string = reader.result as string;
csv({
output: "json",
noheader: false
}).fromString(csvs)
.preFileLine((fileLine, idx) => {
//Convert csv header row to lowercase before parse csv file to json
if (idx === 0) { return fileLine.toLowerCase() }
return fileLine;
})
.then((result) => {
// list of json in result
});
}
}
Using join
:
join -t $'\t' -o 1.2,1.1 file.txt file.txt
Notes:
-t $'\t'
In GNU join
the more intuitive -t '\t'
without the $
fails, (coreutils v8.28 and earlier?); it's probably a bug that a workaround like $
should be necessary. See: unix join separator char.
join
needs two filenames, even though there's just one file being worked on. Using the same name twice tricks join
into performing the desired action.
For systems with low resources join
offers a smaller footprint than some of the tools used in other answers:
wc -c $(realpath `which cut join sed awk perl`) | head -n -1
43224 /usr/bin/cut
47320 /usr/bin/join
109840 /bin/sed
658072 /usr/bin/gawk
2093624 /usr/bin/perl
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.