Switch -J
only works on newer systems. The universal command is:
To make .tar.xz archive
tar cf - directory/ | xz -z - > directory.tar.xz
Explanation
tar cf - directory
reads directory/ and starts putting it to TAR format. The output of this operation is generated on the standard output.
|
pipes standard output to the input of another program...
... which happens to be xz -z -
. XZ is configured to compress (-z
) the archive from standard input (-
).
You redirect the output from xz
to the tar.xz
file.
This is a very frustrating part of XCode. Like many, I wasted hours on this when I switched to a newer version of xcode (version 8). The solution for me was to open the properties for my project and under the "App Icons and Launch Images" choose the "migrate" option for the icons. This made absolutely no sense to me as I already had all my icons there, but it worked! Unfortunately I now seem to have two copies of my launcher icons in the project though.
There's nothing in the BCL to do this for you, but there are two great libraries for .NET which do support the functionality.
I've used both and can say that the two are very complete and have well-designed APIs, so it's mainly a matter of personal preference.
I'm not sure whether they explicitly support adding Folders rather than just individual files to zip files, but it should be quite easy to create something that recursively iterated over a directory and its sub-directories using the DirectoryInfo
and FileInfo
classes.
What about System.IO.Packaging.ZipPackage
?
It would require .NET 3.0 or greater.
#Load some assemblys. (No line break!)
[System.Reflection.Assembly]::Load("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
#Create a zip file named "MyZipFile.zip". (No line break!)
$ZipPackage=[System.IO.Packaging.ZipPackage]::Open("C:\MyZipFile.zip",
[System.IO.FileMode]"OpenOrCreate", [System.IO.FileAccess]"ReadWrite")
#The files I want to add to my archive:
$files = @("/Penguins.jpg", "/Lighthouse.jpg")
#For each file you want to add, we must extract the bytes
#and add them to a part of the zip file.
ForEach ($file In $files)
{
$partName=New-Object System.Uri($file, [System.UriKind]"Relative")
#Create each part. (No line break!)
$part=$ZipPackage.CreatePart($partName, "",
[System.IO.Packaging.CompressionOption]"Maximum")
$bytes=[System.IO.File]::ReadAllBytes($file)
$stream=$part.GetStream()
$stream.Write($bytes, 0, $bytes.Length)
$stream.Close()
}
#Close the package when we're done.
$ZipPackage.Close()
via Anders Hesselbom
I had no luck getting tar to exclude a 5 Gigabyte subdirectory a few levels deep. In the end, I just used the unix Zip command. It worked a lot easier for me.
So for this particular example from the original post
(tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz . )
The equivalent would be:
zip -r /backup/filename.zip . -x upload/folder/**\* upload/folder2/**\*
(NOTE: Here is the post I originally used that helped me https://superuser.com/questions/312301/unix-zip-directory-but-excluded-specific-subdirectories-and-everything-within-t)
An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.
It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.
I successfully use the following method in one file,
But come up with exactly the same error again... Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
# import required python modules
# You have to install zipfile package using pip install
import os,zipfile
# Change the directory where you want your new zip file to be
os.chdir('Type your destination')
# Create a new zipfile ( I called it myfile )
zf = zipfile.ZipFile('myfile.zip','w')
# os.walk gives a directory tree. Access the files using a for loop
for dirnames,folders,files in os.walk('Type your directory'):
zf.write('Type your Directory')
for file in files:
zf.write(os.path.join('Type your directory',file))
On Solaris, you can use the option -I to read the filenames that you would normally state on the command line from a file. In contrast to the command line, this can create tar archives with hundreds of thousands of files (just did that).
So the example would read
tar -cvf allfiles.tar -I mylist.txt
You can also create archive as usual and extract it with:
tar --strip-components 1 -xvf my_directory.tar.gz
~dp0
: d=drive, p=path, %0=full path\name of this batch-file.
cd /d %~dp0
will change the path to the same, where the batch file resides.
See for /?
or call /
for more details about the %~...
modifiers.
See cd /?
about the /d
switch.
Try this->
EditText text = (EditText) findViewById(R.id.text_input);
Editable name = text.getText();
Editable is the return data type of getText() method it will handle both string and integer values
//sort by number
bool sortByStartNumber(Player &p1, Player &p2) {
return p1.getStartNumber() < p2.getStartNumber();
}
//sort by string
bool sortByName(Player &p1, Player &p2) {
string s1 = p1.getFullName();
string s2 = p2.getFullName();
return s1.compare(s2) == -1;
}
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)
should do it for you. But I prefer ggplot2
and would suggest that for better graphics in R.
If it helps you can embed a tab character in a double quoted string:
PS> "`t hello"
while test the condition before executing statements in the while loop.
do while test the condition after having executed statement inside the loop.
If using style and implement
colorControlActivate
replace its value other that color/white.
WITH uniq AS (
SELECT DISTINCT posts.id as post_id
FROM posts
JOIN votes ON votes.post_id = posts.id
-- GROUP BY not needed anymore
-- GROUP BY posts.id
)
SELECT COUNT(*)
FROM uniq;
I had the same issue, but reason was different.
In my web.config there was a URL rewrite module rule and I haven’t installed URL rewrite module also. After I install url rewrite module this problem solved.
If you are fine using a graphical tool this works very well:
gitk <file>
gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!
Minimal code needed for this one. Create a common 'key' to cartesian merge the two:
df1['key'] = 0
df2['key'] = 0
df_cartesian = df1.merge(df2, how='outer')
the order of registering routes is important . register 404
routes after static files.
correct order:
app.use("/admin", admin);
...
app.use(express.static(join(__dirname, "public")));
app.use((req, res) => {
res.status(404);
res.send("404");
});
otherwise everything which is not in routes , like css files etc.. , will become 404 .
bean.xhtml
<h:form enctype="multipart/form-data">
<p:outputLabel value="Choose your file" for="submissionFile" />
<p:fileUpload id="submissionFile"
value="#{bean.file}"
fileUploadListener="#{bean.uploadFile}" mode="advanced"
auto="true" dragDropSupport="false" update="messages"
sizeLimit="100000" fileLimit="1" allowTypes="/(\.|\/)(pdf)$/" />
</h:form>
Bean.java
@ManagedBean
@ViewScoped public class Submission implements Serializable {
private UploadedFile file;
//Gets
//Sets
public void uploadFasta(FileUploadEvent event) throws FileNotFoundException, IOException, InterruptedException {
String content = IOUtils.toString(event.getFile().getInputstream(), "UTF-8");
String filePath = PATH + "resources/submissions/" + nameOfMyFile + ".pdf";
MyFileWriter.writeFile(filePath, content);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
event.getFile().getFileName() + " is uploaded.", null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
You can do a form.serializeArray(), then add name-value pairs before posting:
var form = $(this).closest('form');
form = form.serializeArray();
form = form.concat([
{name: "customer_id", value: window.username},
{name: "post_action", value: "Update Information"}
]);
$.post('/change-user-details', form, function(d) {
if (d.error) {
alert("There was a problem updating your user details")
}
});
Using SQL_CALC_FOUND_ROWS
you can't.
The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.
As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS
is frequently slower than just getting a count.
Perhaps you'd be best off doing this as as subquery:
SELECT
(select count(*) from my_table WHERE Name LIKE '%prashant%')
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
mysqladmin
is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).
You type that command from a shell prompt.
Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:
FLUSH HOSTS;
Setting null values can be done with np.nan
:
import numpy as np
df.replace('-', np.nan)
Advantage is that df.last_valid_index()
recognizes these as invalid.
Finaly, my service provider answered :
This is a limitation of the virtualization system we use (OpenVZ), basic iptables rules are possible but not those who use the nat table.
If this really is a problem, we can offer you to migrate to a other system virtualization (KVM) as we begin to offer our customers.
SO I had to migrate my server to the new system...
getDay()
returns the day of the week. To get the date, use date.getDate()
. getMonth()
retrieves the month, but month is zero based, so using getMonth()+1
should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC
to the methods (e.g. date.getUTCFullYear()
, date.getUTCHours()
)
var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.
Some answers seem to be a little misleading.
.cpp
file for initializing since it can be done in the same Header file.Also, you can even initialize a static object in the same class scope just like a normal variable using the inline
keyword.
Initialize with no values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str;
int A::x;
Initialize with values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str = "SO!";
int A::x = 900;
Initialize in the same class scope using the inline
keyword
#include <string>
class A
{
static inline std::string str = "SO!";
static inline int x = 900;
};
// only int
public static boolean isNumber(int num)
{
return (num >= 48 && c <= 57); // 0 - 9
}
// is type of number including . - e E
public static boolean isNumber(String s)
{
boolean isNumber = true;
for(int i = 0; i < s.length() && isNumber; i++)
{
char c = s.charAt(i);
isNumber = isNumber & (
(c >= '0' && c <= '9') || (c == '.') || (c == 'e') || (c == 'E') || (c == '')
);
}
return isInteger;
}
// is type of number
public static boolean isInteger(String s)
{
boolean isInteger = true;
for(int i = 0; i < s.length() && isInteger; i++)
{
char c = s.charAt(i);
isInteger = isInteger & ((c >= '0' && c <= '9'));
}
return isInteger;
}
public static boolean isNumeric(String s)
{
try
{
Double.parseDouble(s);
return true;
}
catch (Exception e)
{
return false;
}
}
By default flush mode is AUTO which means that: "The Session is sometimes flushed before query execution in order to ensure that queries never return stale state", but most of the time session is flushed when you commit your changes. Manual calling of the flush method is usefull when you use FlushMode=MANUAL or you want to do some kind of optimization. But I have never done this so I can't give you practical advice.
Try this command in terminal and then reload. It worked for me
adb reverse tcp:8081 tcp:8081
Since the remove method is depreciated in the mongoose library we can use the deleteMany function with no parameters passed.
Model.deleteMany();
This will delete all content of this particular Model and your collection will be empty.
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.
If you want to connect Context with other familiar classes in Android, keep in mind this structure:
Context < ContextWrapper < Application
Context < ContextWrapper < ContextThemeWrapper < Activity
Context < ContextWrapper < ContextThemeWrapper < Activity < ListActivity
Context < ContextWrapper < Service
Context < ContextWrapper < Service < IntentService
So, all of those classes are contexts in their own way. You can cast Service and ListActivity to Context if you wish. But if you look closely, some of the classes inherit theme as well. In activity or fragment, you would like theming to be applied to your views, but don't care about it Service class, for instance.
I explain the difference in contexts here.
There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment
private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
fragment.init(music);
return fragment;
}
public void init(List<Music> music){
this.listMusic = music;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.musiclistview, container, false);
listMusic = (ListView) view.findViewById(R.id.musicListView);
listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));
return view;
}
}
In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.
I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.
Google for "Gideros Mobile"
How is this possible? Without an index on the er101_upd_date_iso column how can a clustered index scan be used?
An index is a B-Tree where each leaf node is pointing to a 'bunch of rows'(called a 'Page' in SQL internal terminology), That is when the index is a non-clustered index.
Clustered index is a special case, in which the leaf nodes has the 'bunch of rows' (rather than pointing to them). that is why...
1) There can be only one clustered index on the table.
this also means the whole table is stored as the clustered index, that is why you started seeing index scan rather than a table scan.
2) An operation that utilizes clustered index is generally faster than a non-clustered index
Read more at http://msdn.microsoft.com/en-us/library/ms177443.aspx
For the problem you have, you should really consider adding this column to a index, as you said adding a new index (or a column to an existing index) increases INSERT/UPDATE costs. But it might be possible to remove some underutilized index (or a column from an existing index) to replace with 'er101_upd_date_iso'.
If index changes are not possible, i recommend adding a statistics on the column, it can fasten things up when the columns have some correlation with indexed columns
http://msdn.microsoft.com/en-us/library/ms188038.aspx
BTW, You will get much more help if you can post the table schema of ER101_ACCT_ORDER_DTL. and the existing indices too..., probably the query could be re-written to use some of them.
Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation. http://www.jusfortechies.com/java/core-java/static-blocks.php
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
Safest method, which I use frequently:
git clean -fd
Syntax explanation as per /docs/git-clean
page:
-f
(alias: --force
). If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f, -n or -i. Git will refuse to delete directories with .git sub directory or file unless a second -f is given.-d
. Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use -f option twice if you really want to remove such a directory.As mentioned in the comments, it might be preferable to do a git clean -nd
which does a dry run and tells you what would be deleted before actually deleting it.
Link to git clean
doc page:
https://git-scm.com/docs/git-clean
You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line
127.0.0.1 FALSE / FALSE 0 USER_TOKEN in
having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.
What I do is:
Set the td width:
<td width="200" height="50"><!--blaBlaBla Contents here--></td>
Set the td width with CSS:
<td style="width:200px; height:50px;">
Set the width again as max and min with CSS:
<td style="max-width:200px; min-width:200px; max-height:50px; min-height:50px; width:200px; height:50px;">
It sounds little bit repetitive but it gives me the desired result. To achieve this with much ease, you may need put the CSS values in a class in your style-sheet:
.td_size {
width:200px;
height:50px;
max-width:200px;
min-width:200px;
max-height:50px;
min-height:50px;
**overflow:hidden;** /*(Optional)This might be useful for some overflow contents*/
}
then:
<td class="td_size">
Place the class attribute to any <td>
you want.
You could use the Date.getDay()
method, which returns 0 for sunday, up to 6 for saturday. So, you could simply create an array with the name for the day names:
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(dateString);
var dayName = days[d.getDay()];
Here dateString
is the string you received from the third party API.
Alternatively, if you want the first 3 letters of the day name, you could use the Date
object's built-in toString
method:
var d = new Date(dateString);
var dayName = d.toString().split(' ')[0];
That will take the first word in the d.toString()
output, which will be the 3-letter day name.
Thanks to Waseem05 for his Swift 3 translation but his method only worked for me when I wrapped it inside an extension to UIImage and placed it outside/below the parent class like so:
extension UIImage {
func fixOrientation() -> UIImage
{
if self.imageOrientation == UIImageOrientation.up {
return self
}
var transform = CGAffineTransform.identity
switch self.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: self.size.height)
transform = transform.rotated(by: CGFloat(M_PI));
case .left, .leftMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0);
transform = transform.rotated(by: CGFloat(M_PI_2));
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: self.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
case .up, .upMirrored:
break
}
switch self.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: self.size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1);
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGContext(
data: nil,
width: Int(self.size.width),
height: Int(self.size.height),
bitsPerComponent: self.cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: self.cgImage!.colorSpace!,
bitmapInfo: UInt32(self.cgImage!.bitmapInfo.rawValue)
)
ctx!.concatenate(transform);
switch self.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.height ,height:self.size.width))
default:
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.width ,height:self.size.height))
break;
}
// And now we just create a new UIImage from the drawing context
let cgimg = ctx!.makeImage()
let img = UIImage(cgImage: cgimg!)
return img;
}
}
Then called it with:
let correctedImage:UIImage = wonkyImage.fixOrientation()
And all was then well! Apple should make it easier to discard orientation when we don't need front/back camera and up/down/left/right device orientation metadata.
Normal ways would be Integer.toString(i)
or String.valueOf(i)
.
int i = 5;
String strI = String.valueOf(i);
Or
int aInt = 1;
String aString = Integer.toString(aInt);
Well, URL API object avoids splitting and constructing the url's manually.
let url = new URL('https://stackoverflow.com/questions/1420881');
alert(url.origin);
To find any file location
My answer is based on the one provided by @x-yuri; but my scenario it's a little bit different. I wanted an image containing the script, not bind without needing to bind-mount it.
mongo-init.sh
-- don't know whether or not is need but but I ran chmod +x mongo-init.sh
also:
#!/bin/bash
# https://stackoverflow.com/a/53522699
# https://stackoverflow.com/a/37811764
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
var user = '$MONGO_INITDB_USERNAME';
var passwd = '$MONGO_INITDB_PASSWORD';
var admin = db.getSiblingDB('admin');
admin.auth(rootUser, rootPassword);
db.createUser({
user: user,
pwd: passwd,
roles: [
{
role: "root",
db: "admin"
}
]
});
EOF
Dockerfile
:
FROM mongo:3.6
COPY mongo-init.sh /docker-entrypoint-initdb.d/mongo-init.sh
CMD [ "/docker-entrypoint-initdb.d/mongo-init.sh" ]
docker-compose.yml
:
version: '3'
services:
mongodb:
build: .
container_name: mongodb-test
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=example
- MONGO_INITDB_USERNAME=myproject
- MONGO_INITDB_PASSWORD=myproject
- MONGO_INITDB_DATABASE=myproject
myproject:
image: myuser/myimage
restart: on-failure
container_name: myproject
environment:
- DB_URI=mongodb
- DB_HOST=mongodb-test
- DB_NAME=myproject
- DB_USERNAME=myproject
- DB_PASSWORD=myproject
- DB_OPTIONS=
- DB_PORT=27017
ports:
- "80:80"
After that, I went ahead and publish this Dockefile as an image to use in other projects.
note: without adding the CMD
it mongo throws: unbound variable error
In the right side of Android Studio go to Gradle -> Tasks -> android -> signingReport
and run it.
Copy the SHA-1 key and transform it into base64 using this, and then add the converted base64 hash to your app in the Facebook Developer Console.
If you want to use a release hash run this in the command line:keytool -exportcert -alias YOUR_KEYSTORE_ALIAS -keystore YOUR_KEYSTORE | openssl sha1 -binary | openssl base64
Where YOUR_KEYSTORE
is the path to the .keystore
or .jks
that you used as signinConfig
for your release variant and YOUR_KEYSTORE_ALIAS
is the alias which you gave when you created the keystore. If you do not remember the alias you can run keytool -v -list -keystore YOUR_KEYSTORE
and see all the info about the keystore
There is a maven plugin called properties-maven-plugin this one provides a goal set-system-properties
to set system variables. This is especially useful if you have a file containing all these properties. So you're able to read a property file and set them as system variable.
Another thing to try is
Tools -> Options -> search for IIS -> tick Use the 64 bit version of IIS Express for web sites and projects.
The following works for me in Firefox and Chrome. In Firefox it even works from file:///
models/course.js
export function Course() {
this.id = '';
this.name = '';
};
models/student.js
import { Course } from './course.js';
export function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
};
index.html
<div id="myDiv">
</div>
<script type="module">
import { Student } from './models/student.js';
window.onload = function () {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
When using docker-machine, you can copy images between machines mach1
and mach2
with:
docker $(docker-machine config <mach1>) save <image> | docker $(docker-machine config <mach2>) load
And of course you can also stick pv
in the middle to get a progess indicator:
docker $(docker-machine config <mach1>) save <image> | pv | docker $(docker-machine config <mach2>) load
You may also omit one of the docker-machine config
sub-shells, to use your current default docker-host.
docker save <image> | docker $(docker-machine config <mach>) load
to copy image from current docker-host to mach
or
docker $(docker-machine config <mach>) save <image> | docker load
to copy from mach
to current docker-host.
Radio buttons are meant to be required options... If you want them to be unchecked, use a checkbox, there is no need to complicate things and allow users to uncheck a radio button; removing the JQuery allows you to select from one of them
In addition to the other answers using HTML (either in Markdown or using the %%HTML
magic:
If you need to specify the image height, this will not work:
<img src="image.png" height=50> <-- will not work
That is because the CSS styling in Jupyter uses height: auto
per default for the img
tags, which overrides the HTML height attribute. You need need to overwrite the CSS height
attribute instead:
<img src="image.png" style="height:50px"> <-- works
Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:
This might help http://docs.pytest.org/en/latest/xunit_setup.html
In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls)
and teardown_class(cls)
classmethods.
And for the setup and teardown I need for each of the test case, I use the setup_method(method)
and teardown_method(methods)
Example:
lh = <got log handler from logger module>
class TestClass:
@classmethod
def setup_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
@classmethod
def teardown_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
def setup_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def teardown_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def test_tc1(self):
<tc_content>
assert
def test_tc2(self):
<tc_content>
assert
Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..
You can add up other setup and teardown steps you might have in the respective locations.
Hope it helps!
Try this instead:
SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)
Explanation
Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:
The CASE expression has two formats:
- The simple CASE expression compares an expression to a set of simple expressions to determine the result.
- The searched CASE expression evaluates a set of Boolean expressions to determine the result.
You want the searched CASE expression syntax:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.
JavaScript Code
//this function is used to fire click event
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function showPdf(){
eventFire(document.getElementById('picToClick'), 'click');
}
HTML Code
<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
<button onclick="showPdf()">Click me</button>
Closing and Re-Importing project worked for me.
When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.
GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.
MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.
If you use Maven, you can use xvfb-maven-plugin to start xvfb before tests, run them using related DISPLAY
environment variable, and stop xvfb after all.
Quoting from http://dev.mysql.com/doc/refman/5.1/en/create-table.html
{INDEX|KEY}
So KEY
is an INDEX
;)
A generic solution like so
public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input,
Function<Y, Z> function) {
return input
.entrySet()
.stream()
.collect(
Collectors.toMap((entry) -> entry.getKey(),
(entry) -> function.apply(entry.getValue())));
}
Example
Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<String, Integer> output = transform(input,
(val) -> Integer.parseInt(val));
code below allows user to input items until they press enter key to stop:
In [1]: items=[]
...: i=0
...: while 1:
...: i+=1
...: item=input('Enter item %d: '%i)
...: if item=='':
...: break
...: items.append(item)
...: print(items)
...:
Enter item 1: apple
Enter item 2: pear
Enter item 3: #press enter here
['apple', 'pear']
In [2]:
Some more detail for completeness in case it helps someone...
Note that the most common reason for this exception these days is attempting to load a 32 bit-specific (/platform:x86
) DLL into a process that is 64 bit or vice versa (viz. load a 64 bit-specific (/platform:x64
) DLL into a process that is 32 bit). If your platform
is non-specific (/platform:AnyCpu
), this won't arise (assuming no referenced dependencies are of the wrong bitness).
In other words, running:
%windir%\Microsoft.NET\Framework\v2.0.50727\installutil.exe
or:
%windir%\Microsoft.NET\Framework64\v2.0.50727\installutil.exe
will not work (substitute in other framework versions: v1.1.4322
(32-bit only, so this issue doesn't arise) and v4.0.30319
as desired in the above).
Obviously, as covered in the other answer, one will also need the .NET version number of the installutil
you are running to be >= (preferably =) that of the EXE/DLL file you are running the installer of.
Finally, note that in Visual Studio 2010, the tooling will default to generating x86 binaries (rather than Any CPU as previously).
Complete details of System.BadImageFormatException (saying the only cause is mismatched bittedness is really a gross oversimplification!).
Another reason for a BadImageFormatException
under an x64 installer is that in Visual Studio 2010, the default .vdproj
Install Project type generates a 32-bit InstallUtilLib
shim, even on an x64 system (Search for "64-bit managed custom actions throw a System.BadImageFormatException exception" on the page).
SQL SERVER 2005:
print upper('hello');
print lower('HELLO');
Paulo's help lead me to the solution. It was a combination of the following:
The bash shell treats the dollar sign as a special character for expansion to an environment variable, so we need to escape it with a backslash. Incidentally, we don't have to do this in the case where the dollar sign is the final character of the password.
As an example, if your password is "pas$word", from Linux bash we must connect as follows:
# mysql --host=192.168.233.142 --user=root --password=pas\$word
Hi I'm late to the party.. just wanted to point out that the instructions from http://davidtsadler.com/archives/2012/06/03/how-to-install-magento-on-ubuntu/ were really useful.
I had Ubuntu server installed with Apache, MySql and Php so I thought I could jump to the heading Creating the directory from which Magento will be served from and I reached the same problem as the OP, i.e. I had 'index.php' needed in all the URLs (or I would get 404 not found). I then went back to Installing and configuring the Apache HTTP server and after restarting apache it works perfectly.
For reference, I was missing:
sudo bash -c "cat >> /etc/apache2/conf.d/servername.conf <<EOF
ServerName localhost
EOF"
... and
sudo a2enmod rewrite
sudo service apache2 restart
Hope this helps
If you need only display the trimmed value then I'd suggest against manipulating the original string and using a filter instead.
app.filter('trim', function () {
return function(value) {
if(!angular.isString(value)) {
return value;
}
return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
};
});
And then
<span>{{ foo | trim }}</span>
Preserve the name of the column and avoid extra column addition by using the same name as input column:
changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))
Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
The reason your functor example does not work is that you need an instance to invoke the operator()
.
Add android:background="@drawable/your_image"
inside your Relativelayout/Linearlayout
Worked.
here is my solution. I have also extended the PDO class:
class Db extends PDO
{
/**
* SELECT ... WHERE fieldName IN (:paramName) workaround
*
* @param array $array
* @param string $prefix
*
* @return string
*/
public function CreateArrayBindParamNames(array $array, $prefix = 'id_')
{
$newparams = [];
foreach ($array as $n => $val)
{
$newparams[] = ":".$prefix.$n;
}
return implode(", ", $newparams);
}
/**
* Bind every array element to the proper named parameter
*
* @param PDOStatement $stmt
* @param array $array
* @param string $prefix
*/
public function BindArrayParam(PDOStatement &$stmt, array $array, $prefix = 'id_')
{
foreach($array as $n => $val)
{
$val = intval($val);
$stmt -> bindParam(":".$prefix.$n, $val, PDO::PARAM_INT);
}
}
}
Here is a sample usage for the above code:
$idList = [1, 2, 3, 4];
$stmt = $this -> db -> prepare("
SELECT
`Name`
FROM
`User`
WHERE
(`ID` IN (".$this -> db -> CreateArrayBindParamNames($idList)."))");
$this -> db -> BindArrayParam($stmt, $idList);
$stmt -> execute();
foreach($stmt as $row)
{
echo $row['Name'];
}
Let me know what you think
Could be SELinux. Check the appropriate log file (/var/log/messages? - been a while since I've used a RedHat derivative) to see if that's blocking the access.
f-strings, also called “formatted string literals,” are string literals that have an f
at the beginning; and curly braces containing expressions that will be replaced with their values.
f-strings are evaluated at runtime.
So your code can be re-written as:
string1="go"
string2="now"
string3="great"
print(f"""
I will {string1} there
I will go {string2}
{string3}
""")
And this will evaluate to:
I will go there
I will go now
great
You can learn more about it here.
The best format to use is "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK".
The last K on string will be changed to 'Z' if the date is UTC or with timezone (+-hh:mm) if is local. (http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)
As LukeH said, is good to use the ToUniversalTime if you want that all the dates will be UTC.
The final code is:
string foo = yourDateTime.ToUniversalTime()
.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");
According to this link
Actually, SO_REUSEADDR flag can lead to much greater consequences: SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port in TIME_WAIT. I can reuse local port 1010 right away to connect to anywhere except for foobar.com port 300.
However you can completely avoid TIME_WAIT state by ensuring that the remote end initiates the closure (close event). So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.
I also advice you to learn more about networking and network programming. You should now at least how tcp protocol works. The protocol is quite trivial and small and hence, may save you a lot of time in future.
With netstat
command you can easily see which programs ( (program_name,pid) tuple) are binded to which ports and what is the socket current state: TIME_WAIT, CLOSING, FIN_WAIT and so on.
A really good explanation of linux network configurations can be found https://serverfault.com/questions/212093/how-to-reduce-number-of-sockets-in-time-wait.
scp -r C:/site user@server_ip:path
path
is the place, where site
will be copied into the remote server
EDIT: As I said in my comment, try pscp
, as you want to use scp
using PuTTY
.
The other option is WinSCP
There two ways, what I found either go to the directory where kernels are residing and delete from there. Secondly, using this command below
List all kernels and grap the name of the kernel you want to remove
jupyter kernelspec list
to get the paths of all your kernels.
Then simply uninstall your unwanted-kernel
jupyter kernelspec remove kernel_name
Download this file :- (https://pypi.python.org/packages/1f/3b/ee6f354bcb1e28a7cd735be98f39ecf80554948284b41e9f7965951befa6/pyserial-3.2.1.tar.gz#md5=7142a421c8b35d2dac6c47c254db023d):
cd /opt
sudo tar -xvf ~/Downloads/pyserial-3.2.1.tar.gz -C .
cd /opt/pyserial-3.2.1
sudo python setup.py install
I know it's not exactly what you are looking for, but maybe it'll help you.
You can try use a jQuery selector :contains()
, add a class and then do a normal style for a class.
Avoiding redundancy I don't repeat my answer here again.
Please refer to my answer here. (note that answer only covers compiling to python bytecode.)
The one that I like is HexEdit Quick and easy to use
Another way to make it in Python 3:
numbers = [*map(int, numbers)]
Because TRUNCATE TABLE
is a DDL command, it cannot check to see whether the records in the table are being referenced by a record in the child table.
This is why DELETE
works and TRUNCATE TABLE
doesn't: because the database is able to make sure that it isn't being referenced by another record.
You can do that using CSS's background
propieties. There are few ways to do it:
HTML:
<div id="div-with-bg"></div>
CSS:
#div-with-bg
{
background: color url('path') others;
}
HTML:
<div class="div-with-bg"></div>
CSS:
.div-with-bg
{
background: color url('path') others;
}
HTML:
<div style="background: color url('path')"></div>
Where:
background
CSS Property is a connection of all background-xxx propieties in that syntax:
background: background-color background-image background-repeat background-attachment background-position;
Source: w3schools
i hope this will be helpful.
put this on the top of source code :
import java.awt.Toolkit;
and then write this code :
private void formWindowOpened(java.awt.event.WindowEvent evt) {
int lebar = this.getWidth()/2;
int tinggi = this.getHeight()/2;
int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar;
int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi;
this.setLocation(x, y);
}
good luck :)
This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).
Suppose your data was : He said "This is how it is done".
Then the actual data should look like "He said \"This is how it is done\"."
.
This ensures that the \"
is treated as "(Quotation mark)
and not as JSON formatting. This is called escape character
.
This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.
Try this
$arr = ['This is a sample','This is also a "sample"'];
echo json_encode($arr);
OUTPUT:
["This is a sample","This is also a \"sample\""]
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
The SQL Server Maximums are disclosed http://msdn.microsoft.com/en-us/library/ms143432.aspx (this is the 2008 version)
A SQL Query can be a varchar(max) but is shown as limited to 65,536 * Network Packet size, but even then what is most likely to trip you up is the 2100 parameters per query. If SQL chooses to parameterize the literal values in the in clause, I would think you would hit that limit first, but I havn't tested it.
Edit : Test it, even under forced parameteriztion it survived - I knocked up a quick test and had it executing with 30k items within the In clause. (SQL Server 2005)
At 100k items, it took some time then dropped with:
Msg 8623, Level 16, State 1, Line 1 The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.
So 30k is possible, but just because you can do it - does not mean you should :)
Edit : Continued due to additional question.
50k worked, but 60k dropped out, so somewhere in there on my test rig btw.
In terms of how to do that join of the values without using a large in clause, personally I would create a temp table, insert the values into that temp table, index it and then use it in a join, giving it the best opportunities to optimse the joins. (Generating the index on the temp table will create stats for it, which will help the optimiser as a general rule, although 1000 GUIDs will not exactly find stats too useful.)
I spent a lot of time trying to figure this one out. Finally, I tried shutting down my development server and booting it up again. Frustratingly, this worked for me.
I came to the conclusion, that after editing the .env
file in Laravel 5, you have to exit the server, and run php artisan serve
again.
To "remove" the 1st character point to the second character:
char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */
To remove the last character replace it with a '\0'
.
p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */
Just a supplement here.
The following question is that what if I want more subplots in the figure?
As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2)
to set a group of subplots with grid(2,2) in one figure object.
Then as we know, the fig, ax = plt.subplots()
returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)
firstly.
ValueError: not enough values to unpack (expected 4, got 2)
It raises a error, but no worry, because we now see that plt.subplots()
actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.
So let's try this again:
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
and check the type:
type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>
Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:
fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)
So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.
Hope this would be helpful for you.
TypeScript has Map. You can use like:
public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);
myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data
To list mongodb database on shell
show databases //Print a list of all available databases.
show dbs // Print a list of all databases on the server.
Few more basic commands
use <db> // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections //Print a list of all collections for current database.
show users //Print a list of users for current database.
show roles //Print a list of all roles, both user-defined and built-in, for the current database.
Thanks @Laurence Gonsalves your answer helped me a lot. your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
You can now link to an external site using React Link by providing an object to to
with the pathname
key:
<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >
If you find that you need to use JS to generate the link in a callback, you can use window.location.replace()
or window.location.assign()
.
Over using window.location.replace()
, as other good answers suggest, try using window.location.assign()
.
window.location.replace()
will replace the location history without preserving the current page.
window.location.assign()
will transition to the url specified, but will save the previous page in the browser history, allowing proper back-button functionality.
https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
Also, if you are using a window.location = url
method as mentioned in other answers, I highly suggest switching to window.location.href = url
.
There is a heavy argument about it, where many users seem to adamantly want to revert the newer object
type window.location
to its original implementation as string
merely because they can (and they egregiously attack anyone who says otherwise), but you could theoretically interrupt other library functionality accessing the window.location
object.
Check out this convo. It's terrible. Javascript: Setting location.href versus location
You can just set the default value to null.
<?php
function functionName($value, $value2 = null) {
// do stuff
}
Make sure you encode and decode as appropriate.
This example will roundtrip some example text in utf-8 to a csv file and back out to demonstrate:
# -*- coding: utf-8 -*-
import csv
tests={'German': [u'Straße',u'auslösen',u'zerstören'],
'French': [u'français',u'américaine',u'épais'],
'Chinese': [u'???',u'??',u'???']}
with open('/tmp/utf.csv','w') as fout:
writer=csv.writer(fout)
writer.writerows([tests.keys()])
for row in zip(*tests.values()):
row=[s.encode('utf-8') for s in row]
writer.writerows([row])
with open('/tmp/utf.csv','r') as fin:
reader=csv.reader(fin)
for row in reader:
temp=list(row)
fmt=u'{:<15}'*len(temp)
print fmt.format(*[s.decode('utf-8') for s in temp])
Prints:
German Chinese French
Straße ??? français
auslösen ?? américaine
zerstören ??? épais
Simply write outline:none;
. No need to use pseudo element focus
The first is better. If you try to debug the second and look at the call stack you won't see where the original exception came from. There are tricks to keep the call-stack intact (try search, it's been answered before) if you really need to rethrow.
As of Groovy 2.2 it is possible to declare a base script class with the new @BaseScript
AST transform annotation.
Example:
file MainScript.groovy:
abstract class MainScript extends Script {
def meaningOfLife = 42
}
file test.groovy:
import groovy.transform.BaseScript
@BaseScript MainScript mainScript
println "$meaningOfLife" //works as expected
found this here:
<!--[if lte IE 8]>
<script type="text/javascript">
if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
!Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get)
(function() {
var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
Object.defineProperty(Element.prototype, "textContent",
{ // It won't work if you just drop in innerText.get
// and innerText.set or the whole descriptor.
get : function() {
return innerText.get.call(this)
},
set : function(x) {
return innerText.set.call(this, x)
}
}
);
})();
</script>
<![endif]-->
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
ModelStateException
that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)HandleModelStateExceptionAttribute
that catches custom exception and returns HTTP error status with model state error in the bodyThis provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success
and error
handlers.
$.ajax({
type: "POST",
url: "some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
The whole problem is detailed in this blog post where you can find all the code to run this in your application.
I am using CentOS 7.
$ cd /etc/profile.d
$ vim yourstuffs.sh
Type the following into the yourstuffs.sh script.
type whatever you want here to execute
export LD_LIBRARY_PATH=/usr/local/cuda-7.0/lib64:$LD_LIBRARY_PATH
Save and reboot the OS.
public WebElement fluientWaitforElement(WebElement element, int timoutSec, int pollingSec) {
FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS)
.pollingEvery(pollingSec, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class);
for (int i = 0; i < 2; i++) {
try {
//fWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@id='reportmanager-wrapper']/div[1]/div[2]/ul/li/span[3]/i[@data-original--title='We are processing through trillions of data events, this insight may take more than 15 minutes to complete.']")));
fWait.until(ExpectedConditions.visibilityOf(element));
fWait.until(ExpectedConditions.elementToBeClickable(element));
} catch (Exception e) {
System.out.println("Element Not found trying again - " + element.toString().substring(70));
e.printStackTrace();
}
}
return element;
}
In AndroidManifest.xml
I changed here the first activity to be MainActivity4 instead of MainActivity:
Before:
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2" />
<activity android:name=".MainActivity3" />
<activity android:name=".MainActivity4" />
<activity android:name=".MainActivity5" />
<activity android:name=".MainActivity6"/>
After:
<activity android:name=".MainActivity" />
<activity android:name=".MainActivity2" />
<activity android:name=".MainActivity3" />
<activity android:name=".MainActivity4" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity5" />
<activity android:name=".MainActivity6"/>
You can run the top
command (to run non-interactively, type top -b -n 1
). To see applications which are leaking memory, look at the following columns:
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
If you use Firebase in a library module, you need to apply the google play services gradle plugin to it in addition to the app(s) module(s), but also, you need to beware of version 4.2.0 (and 4.1.0) which are broken, and use version 4.0.2 instead.
Here's the issue: https://github.com/google/play-services-plugins/issues/22
On Windows 2019 Server, you can run a Minecraft java server with these commands:
sc create minecraft-server DisplayName= "minecraft-server" binpath= "cmd.exe /C C:\Users\Administrator\Desktop\rungui1151.lnk" type= own start= auto
The .lnk file is a standard windows shortcut to a batch file.
--- .bat file begins ---
java -Xmx40960M -Xms40960M -d64 -jar minecraft_server.1.15.1.jar
--- .bat file ends ---
All this because:
service does not know how to start in a folder,
cmd.exe does not know how to start in a folder
Starting the service will produce "timely manner" error, but the log file reveals the server is running.
If you need to shut down the server, just go into task manager and find the server java in background processes and end it, or terminate the server from in the game using the /stop command, or for other programs/servers, use the methods relevant to the server.
$(':input').bind('click keyup', function(){
// do stuff
});
There's no NotifyIcon for WPF.
A colleague of mine used this freely available library to good effect:
They're different characters. \r
is carriage return, and \n
is line feed.
On "old" printers, \r
sent the print head back to the start of the line, and \n
advanced the paper by one line. Both were therefore necessary to start printing on the next line.
Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r
to move to the start of the line and overwrite the existing text.
More importantly, Unix tends to use \n
as a line separator; Windows tends to use \r\n
as a line separator and Macs (up to OS 9) used to use \r
as the line separator. (Mac OS X is Unix-y, so uses \n
instead; there may be some compatibility situations where \r
is used instead though.)
For more information, see the Wikipedia newline article.
EDIT: This is language-sensitive. In C# and Java, for example, \n
always means Unicode U+000A, which is defined as line feed. In C and C++ the water is somewhat muddier, as the meaning is platform-specific. See comments for details.
The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.
But you could make an own link for every from url.
Example: http://example.com?auth=holasite
In this example your site is: example.com
If somebody open that link it's give you the holasite value for the auth variable.
Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.
Like: $holasite = http://holasite.com (You could use mysql too..)
And just match it, and you have the url.
This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.
You can handle it like this:
for API level 5 and greater
@Override
public void onBackPressed() {
// your code.
}
older than API 5
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code
return true;
}
return super.onKeyDown(keyCode, event);
}
I think is better automate the process:
Add the composer.lock file in your git repository, make sure you use composer.phar install --no-dev when you release, but in you dev machine you could use any composer command without concerns, this will no go to production, the production will base its dependencies in the lock file.
On the server you checkout this specific version or label, and run all the tests before replace the app, if the tests pass you continue the deployment.
If the test depend on dev dependencies, as composer do not have a test scope dependency, a not much elegant solution could be run the test with the dev dependencies (composer.phar install), remove the vendor library, run composer.phar install --no-dev again, this will use cached dependencies so is faster. But that is a hack if you know the concept of scopes in other build tools
Automate this and forget the rest, go drink a beer :-)
PS.: As in the @Sven comment bellow, is not a good idea not checkout the composer.lock file, because this will make composer install work as composer update.
You could do that automation with http://deployer.org/ it is a simple tool.
Simply best way from linux server
sudo mysql --defaults-file=/etc/mysql/debian.cnf -e 'use mysql;UPDATE user SET password=PASSWORD("snippetbucket-technologies") WHERE user="root";FLUSH PRIVILEGES;'
This way work for any linux server, I had 100% sure on Debian and Ubuntu you win.
The correct way to do this as of v4 is:
$('.select2-chosen').select2('data')[0].text
It is undocumented so could break in the future without warning.
You will probably want to check if there is a selection first however:
var s = $('.select2-chosen');
if(s.select2('data') && !!s.select2('data')[0]){
//do work
}
I struggled with this, too. Here's what I found. Expanding on Adam's answer, here's a bit more detail, including how to encode VP9 with alpha in a Webm container.
First, Here's a CodePen playground you can play with, feel free to use my videos for testing.
<video width="600" height="100%" autoplay loop muted playsinline>
<source src="https://rotato.netlify.app/alpha-demo/movie-hevc.mov" type='video/mp4'; codecs="hvc1">
<source src="https://rotato.netlify.app/alpha-demo/movie-webm.webm" type="video/webm">
</video>
And here's a full demo page using z-index to layer the transparent video on top and below certain elements. (You can clone the Webflow template)
So, we'll need a Webm movie for Chrome, and an HEVC with Alpha (supported by Safari on all platforms since 2019)
For Chrome, I've tested successfully on version 30 from 2013. (Caniuse webm doesn't seem to say which webm codec is supported, so I had to try my way). Earlier versions of chrome seem to render a black area.
For Safari, it's simpler: Catalina (2019) or iOS 11 (2019)
Depending on which editing app you're using, I recommend exporting the HEVC with Alpha directly.
But many apps don't support the Webm format, especially on Mac, since it's not a part of AVFoundation.
I recommend exporting an intermediate format like ProRes4444 with an alpha channel to not lose too much quality at this step. Once you have that file, making your webm is as simple as
ffmpeg -i "your-movie-in-prores.mov" -c:v libvpx-vp9 movie-webm.webm
See more approaches in this blog post.
I use apex_util.string_to_table to parse strings, but you can use a different parser if you wish. Then you can insert the data as in this example:
declare
myString varchar2(2000) :='0.75, 0.64, 0.56, 0.45';
myAmount varchar2(2000) :='0.25, 0.5, 0.65, 0.8';
v_array1 apex_application_global.vc_arr2;
v_array2 apex_application_global.vc_arr2;
begin
v_array1 := apex_util.string_to_table(myString, ', ');
v_array2 := apex_util.string_to_table(myAmount, ', ');
forall i in 1..v_array1.count
insert into mytable (a, b) values (v_array1(i), v_array2(i));
end;
Apex_util is available from Oracle 10G onwards. Prior to this it was called htmldb_util and was not installed by default. If you can't use that you could use the string parser I wrote many years ago and posted here.
If anyone is looking for a React Hook approach to implementing setInterval. Dan Abramov talked about it on his blog. Check it out if you want a good read about the subject including a Class approach. Basically the code is a custom Hook that turns setInterval as declarative.
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
Also posting the CodeSandbox link for convenience: https://codesandbox.io/s/105x531vkq
Pretty late and not sure if this was available when the question was asked, set width: auto;
Seems to do the trick
With Nodejs, if you are using routers, make sure to add cors before the routers. Otherwise, you'll still get the cors error. Like below:
const cors = require('cors');
const userRouter = require('./routers/user');
expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());
expressApp.use(userRouter);
$('#_SelectID').change(function () {
var SelectedText = $('option:selected',this).text();
var SelectedValue = $('option:selected',this).val();
});
This problem can occur if a class tries to get value of a non-existent key in web.config
.
For example, the class has a static variable ClientID
private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();
but the web.config
doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation
DateTime
is a non-nullable value type
DateTime? newdate = null;
You can use a Nullable<DateTime>
You can try using max() in subquery, something like this :
SELECT model, date
FROM doc
WHERE date in (SELECT MAX(date) from doc GROUP BY model);
Instead of doing all these, one can simply use ".Result" to get the result from a particular task.
eg: List list = GetListAsync().Result;
Which as per the definition => Gets the result value of this Task < TResult >
Try setting a default value in the css (to let it know where you want it to start out)
position: relative;
transition: all 2s ease 0s;
top: 0; /* start out at position 0 */
Try this :abc > myFile.txt
First, it will create a file with name myFile.txt
in present working directory (in command prompt). Then it will run the command abc
which is not a valid command. In this way, you have gotten a new empty file with the name myFile.txt
.
=
, the indent command can take motions. So, gg
to get the start of the file, =
to indent, G
to the end of the file, gg=G
.
My approach is:
.bashrc
export JAVA6_HOME=`/usr/libexec/java_home -v 1.6`
export JAVA7_HOME=`/usr/libexec/java_home -v 1.7`
export JAVA_HOME=$JAVA6_HOME
# -- optional
# export PATH=$JAVA_HOME/bin:$PATH
This makes it very easy to switch between J6 and J7
There are some good answers on here, so I will just add some process improvements. A better way of determining if the folder exists (does not use FileSystemObjects, which not all computers are allowed to use):
Function FolderExists(FolderPath As String) As Boolean
FolderExists = True
On Error Resume Next
ChDir FolderPath
If Err <> 0 Then FolderExists = False
On Error GoTo 0
End Function
Likewise,
Function FileExists(FileName As String) As Boolean
If Dir(FileName) <> "" Then FileExists = True Else FileExists = False
EndFunction
If you need quick read speed, the best option is to use a closure table. A closure table contains a row for each ancestor/descendant pair. So in your example, the closure table would look like
ancestor | descendant | depth
0 | 0 | 0
0 | 19 | 1
0 | 20 | 2
0 | 21 | 3
0 | 22 | 4
19 | 19 | 0
19 | 20 | 1
19 | 21 | 3
19 | 22 | 4
20 | 20 | 0
20 | 21 | 1
20 | 22 | 2
21 | 21 | 0
21 | 22 | 1
22 | 22 | 0
Once you have this table, hierarchical queries become very easy and fast. To get all the descendants of category 20:
SELECT cat.* FROM categories_closure AS cl
INNER JOIN categories AS cat ON cat.id = cl.descendant
WHERE cl.ancestor = 20 AND cl.depth > 0
Of course, there is a big downside whenever you use denormalized data like this. You need to maintain the closure table alongside your categories table. The best way is probably to use triggers, but it is somewhat complex to correctly track inserts/updates/deletes for closure tables. As with anything, you need to look at your requirements and decide what approach is best for you.
Edit: See the question What are the options for storing hierarchical data in a relational database? for more options. There are different optimal solutions for different situations.
Another more generic solution is to get wrap_content
to just work.
I've extended ViewPager
to override onMeasure()
. The height is wraped around the first child view. This could lead to unexpected results if the child views are not exactly the same height. For that the class can be easily extended to let's say animate to the size of the current view/page. But I didn't need that.
You can use this ViewPager in yout XML layouts just like the original ViewPager:
<view
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="de.cybergen.ui.layout.WrapContentHeightViewPager"
android:id="@+id/wrapContentHeightViewPager"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"/>
Advantage: This approach allows using the ViewPager in any layout including RelativeLayout to overlay other ui elements.
One drawback remains: If you want to use margins, you have to create two nested layouts and give the inner one the desired margins.
Here's the code:
public class WrapContentHeightViewPager extends ViewPager {
/**
* Constructor
*
* @param context the context
*/
public WrapContentHeightViewPager(Context context) {
super(context);
}
/**
* Constructor
*
* @param context the context
* @param attrs the attribute set
*/
public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// find the first child view
View view = getChildAt(0);
if (view != null) {
// measure the first child view with the specified measure spec
view.measure(widthMeasureSpec, heightMeasureSpec);
}
setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view));
}
/**
* Determines the height of this view
*
* @param measureSpec A measureSpec packed into an int
* @param view the base view with already measured height
*
* @return The height of the view, honoring constraints from measureSpec
*/
private int measureHeight(int measureSpec, View view) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
// set the height from the base view if available
if (view != null) {
result = view.getMeasuredHeight();
}
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
}
Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package
import sun.misc.BASE64Encoder;
import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;
and then,
String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );
public String getAuthantication(String username, String password) {
String auth = new String(Base64.encode(username + ":" + password));
return auth;
}
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
Well, you could try something like this, :
public String getElapsedTimeHoursMinutesSecondsString() {
long elapsedTime = getElapsedTime();
String format = String.format("%%0%dd", 2);
elapsedTime = elapsedTime / 1000;
String seconds = String.format(format, elapsedTime % 60);
String minutes = String.format(format, (elapsedTime % 3600) / 60);
String hours = String.format(format, elapsedTime / 3600);
String time = hours + ":" + minutes + ":" + seconds;
return time;
}
to convert milliseconds to a time value
This should work.
app = angular.module('plunker', [])
app.controller 'MainCtrl', ($scope) ->
$scope.users = ['bob', 'sean', 'rocky', 'john']
$scope.test = ->
console.log $scope.users
HTML:
<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />
When you start a thread, it begins executing a function you give it (if you're extending threading.Thread
, the function will be run()
). To end the thread, just return from that function.
According to this, you can also call thread.exit()
, which will throw an exception that will end the thread silently.
Just delete /etc/ImageMagick/policy.xml
file. E.g.
rm /etc/<ImageMagick_PATH>/policy.xml
For ImageMagick 6, it's:
sudo rm /etc/ImageMagick-6/policy.xml
Yet another way to do it:
//Where $file is an instance of Illuminate\Http\UploadFile
$extension = $file->getClientOriginalExtension();
Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:
LEFT OUTER JOIN or LEFT JOIN
RIGHT OUTER JOIN or RIGHT JOIN
FULL OUTER JOIN or FULL JOIN
From MSDN
The full outer join
or full join
returns all rows from both tables, matching up the rows wherever a match can be made and placing NULL
s in the places where no matching row exists.
<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone required name='strMobileNo' ng-model="formModel.strMobileNo" type="text" placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>
the following code will help for phone number validation and the respected directive is
app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
return {
link: function(scope, elm) {
elm.on("keyup",function(){
var isMatchRegex = PHONE_REGEXP.test(elm.val());
if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
elm.removeClass('warning');
}else if(isMatchRegex == false && !elm.hasClass('warning')){
elm.addClass('warning');
}
});
}
}
});
Try this, it also handles the single quote which is failed to parse by JSON.parse() method and also supports the UTF-8 character code.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}
pg_ctl -D /usr/local/var/postgres start
FATAL: could not open directory "pg_tblspc": No such file or directory
.mkdir /usr/local/var/postgres/pg_tblspc
FATAL: lock file "postmaster.pid" already exists
rm /usr/local/var/postgres/postmaster.pid
pg_ctl -D /usr/local/var/postgres start
Laravel 5 uses bcrypt
. So, you can do this as well.
$hashedpassword = bcrypt('plaintextpassword');
output of which you can save to your database table's password field.
Fn Ref: bcrypt
In 2020, I use apply()
with argument result_type='expand'
>>> appiled_df = df.apply(lambda row: fn(row.text), axis='columns', result_type='expand')
>>> df = pd.concat([df, appiled_df], axis='columns')
In case you are using Silex add the Symfony Asset as a dependency:
composer require symfony/asset
Then you may register Asset Service Provider:
$app->register(new Silex\Provider\AssetServiceProvider(), array(
'assets.version' => 'v1',
'assets.version_format' => '%s?version=%s',
'assets.named_packages' => array(
'css' => array(
'version' => 'css2',
'base_path' => __DIR__.'/../public_html/resources/css'
),
'images' => array(
'base_urls' => array(
'https://img.example.com'
)
),
),
));
Then in your Twig template file in head section:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
{% block head %}
<link rel="stylesheet" href="{{ asset('style.css') }}" />
{% endblock %}
</head>
<body>
</body>
</html>
"Is it safe..?" is a question about the language standard and the generated code.
"Is is a good practice?" is a question about how well the statement is understood by any arbitrary human reader of the statement. If you are asking this question, it suggests that the "safe" version is less clear to future readers and writers.
You can do this ( where data-x has the appropriate display:xxxx set ):
<!-- TH -->
<div data-tr>
<div data-th style="width:25%">TH</div>
<div data-th style="width:50%">
<div data-table style="width:100%">
<div data-tr>
<div data-th style="width:25%">TH</div>
<div data-th style="width:25%">TH</div>
<div data-th style="width:25%">TH</div>
<div data-th style="width:25%">TH</div>
</div>
</div>
</div>
<div data-th style="width:25%">TH</div>
</div>
<!-- TD -->
<div data-tr>
<div data-td style="width:25%">TD</div>
<div data-th style="width:50%">
<div data-table style="width:100%">
<div data-tr>
<div data-td style="width:25%">TD</div>
<div data-td style="width:25%">TD</div>
<div data-td style="width:25%">TD</div>
<div data-td style="width:25%">TD</div>
</div>
<div data-tr>
...
</div>
</div>
</div>
<div data-td style="width:25%">TD</div>
</div>
it should help:
android {
...
useLibrary 'org.apache.http.legacy'
...
}
To avoid missing link errors add to dependencies
dependencies {
provided 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
or
dependencies {
compileOnly 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
because
Warning: Configuration 'provided' is obsolete and has been replaced with 'compileOnly'.
I'm using the following:
const isNumber = s => !isNaN(+s)
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
Try:
$a1=@(1,2,3,4,5)
$b1=@(1,2,3,4,5,6)
(Compare-Object $a1 $b1).InputObject
Or, you can use:
(Compare-Object $b1 $a1).InputObject
The order doesn't matter.
Sampling randomizes, so just sample the entire data frame.
df.sample(frac=1)
Use the bootstrap classes to your advantage. navbar-static-bottom
leaves it at the bottom.
<div class="navbar-static-bottom" id="footer"></div>
This is not a problem with XAML. The error message is saying that it tried to create an instance of DVRClientInterface.MainWindow
and your constructor threw an exception.
You will need to look at the "Inner Exception" property to determine the underlying cause. It could be quite literally anything, but should provide direction.
An example would be that if you are connecting to a database in the constructor for your window, and for some reason that database is unavailable, the inner exception may be a TimeoutException
or a SqlException
or any other exception thrown by your database code.
If you are throwing exceptions in static constructors, the exception could be generated from any class referenced by the MainWindow
. Class initializers are also run, if any MainWindow
fields are calling a method which may throw.
I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.
public class RegisterViewModel : IValidatableObject
{
/// <summary>
/// Error message for Minimum password
/// </summary>
public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";
/// <summary>
/// Minimum acceptable password length
/// </summary>
public const int PasswordMinimumLength = 8;
/// <summary>
/// Gets or sets the password provided by the user.
/// </summary>
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
/// <summary>
/// Only need to validate the minimum length
/// </summary>
/// <param name="validationContext">ValidationContext, ignored</param>
/// <returns>List of validation errors</returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errorList = new List<ValidationResult>();
if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
{
errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
}
return errorList;
}
}
The markup in the Razor is then...
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
<div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
</div>
@Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>
This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:
<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>
With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!
Try CountA
:
Dim myArray(1 to 10) as String
Dim arrayCount as String
arrayCount = Application.CountA(myArray)
Debug.Print arrayCount
try this, this will search all MyFolder under root dir and delete all folders named MyFolder
for /d /r "C:\Users\test" %%a in (MyFolder\) do if exist "%%a" rmdir /s /q "%%a"
Short answer: You can't.
Long answer: You could use a modal to display a popup with the image you need.
You can refer to this as an example to a modal.
First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:
There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction
Row-By-Row Processing Without Cursor
That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.
But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....
if you have :
/Users/james/Development/AndroidProjects/myapp/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.0/res/values-v23/values-v23.xml
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
error , you must change your appcompat
, buildtools
, sdk
to 23
but , if you don't like to change it and must be in 22
do this :
SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020
RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.
How to print:
NSLog(@"Something To Print");
Or
NSString * someString = @"Something To Print";
NSLog(@"%@", someString);
For other types of variables, use:
NSLog(@"%@", someObject);
NSLog(@"%i", someInt);
NSLog(@"%f", someFloat);
/// etc...
Can you show it in phone?
Not by default, but you could set up a display to show you.
print("Print this string")
print("Print this \(variable)")
print("Print this ", variable)
print(variable)
The snippet here works fine, tested with windows sound:
public static void main(String[] args) {
AePlayWave aw = new AePlayWave( "C:\\WINDOWS\\Media\\tada.wav" );
aw.start();
}
Simply:
$(function(){
$("#my-div").removeClass('hide');
});
Or if you somehow want the class to still be there:
$(function(){
$("#my-div").css('display', 'block !important');
});
/**
* If $header is an array of headers
* It will format and return the correct $header
* $header = [
* 'Accept' => 'application/json',
* 'Content-Type' => 'application/x-www-form-urlencoded'
* ];
*/
$i_header = $header;
if(is_array($i_header) === true){
$header = [];
foreach ($i_header as $param => $value) {
$header[] = "$param: $value";
}
}
either of these jQuery functions should work:
$("#element").removeAttr("style");
$("#element").removeAttr("background-color")
You're missing at least a couple of things:
Unless you're using reflection, the type arguments need to be known at compile-time, so you can't use
PrintGeneric<test2.GetType()>
... although in this case you don't need to anyway
PrintGeneric
doesn't know anything about T
at the moment, so the compiler can't find a member called T
Options:
Put a property in the ITest
interface, and change PrintGeneric
to constrain T
:
public void PrintGeneric<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.PropertyFromInterface);
}
Put a property in the ITest
interface and remove the generics entirely:
public void PrintGeneric(ITest test)
{
Console.WriteLine("Property : " + test.PropertyFromInterface);
}
Use dynamic typing instead of generics if you're using C# 4
I think the easiest way to achieve this is by using set().
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> y = [1,3,5,7,9]
>>> list(set(x)- set(y))
[0, 2, 4, 6, 8]
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
This will surely work .
To Disable a button
$('#btn_id').button('disable');
To Enable a button
$('#btn_id').button('enable');
For everyone that says checking types and doing something based on the type is not a great idea for generics I sort of agree but I think there could be some circumstances where this perfectly makes sense.
For example if you have a class that say is implemented like so (Note: I am not showing everything that this code does for simplicity and have simply cut and pasted into here so it may not build or work as intended like the entire code does but it gets the point across. Also, Unit is an enum):
public class FoodCount<TValue> : BaseFoodCount
{
public TValue Value { get; set; }
public override string ToString()
{
if (Value is decimal)
{
// Code not cleaned up yet
// Some code and values defined in base class
mstrValue = Value.ToString();
decimal mdecValue;
decimal.TryParse(mstrValue, out mdecValue);
mstrValue = decimal.Round(mdecValue).ToString();
mstrValue = mstrValue + mstrUnitOfMeasurement;
return mstrValue;
}
else
{
// Simply return a string
string str = Value.ToString() + mstrUnitOfMeasurement;
return str;
}
}
}
...
public class SaturatedFat : FoodCountWithDailyValue<decimal>
{
public SaturatedFat()
{
mUnit = Unit.g;
}
}
public class Fiber : FoodCount<int>
{
public Fiber()
{
mUnit = Unit.g;
}
}
public void DoSomething()
{
nutritionFields.SaturatedFat oSatFat = new nutritionFields.SaturatedFat();
string mstrValueToDisplayPreFormatted= oSatFat.ToString();
}
So in summary, I think there are valid reasons why you might want to check to see what type the generic is, in order to do something special.
Using Alt+ Insert or Right-click and choose "Generate..." You may easily generate getter and setter or Override methods in Android Studio. This has the same effect as using the Menu Bar Code -> Generate...
last-child pseudo class does not work in IE
It means you did something like this.
Class myObject = GetObjectFromFunction();
And without doing
if(myObject!=null)
, you go ahead do myObject.Method();
You can use blank.gif (1px transparent image) as target in your tag
<input type="image" src="img/blank.gif" class="button">
and then style background in css:
.button {border:0;background:transparent url("../img/button.png") no-repeat 0 0;}
.button:hover {background:transparent url("../img/button-hover.png") no-repeat 0 0;}
You only need to add .Returns(Task.FromResult(0));
after the Callback.
Example:
mock.Setup(arg => arg.DoSomethingAsync())
.Callback(() => { <my code here> })
.Returns(Task.FromResult(0));
Kernel space and user space is the separation of the privileged operating system functions and the restricted user applications. The separation is necessary to prevent user applications from ransacking your computer. It would be a bad thing if any old user program could start writing random data to your hard drive or read memory from another user program's memory space.
User space programs cannot access system resources directly so access is handled on the program's behalf by the operating system kernel. The user space programs typically make such requests of the operating system through system calls.
Kernel threads, processes, stack do not mean the same thing. They are analogous constructs for kernel space as their counterparts in user space.
Runtime is a general term that refers to any library, framework, or platform that your code runs on.
The C and C++ runtimes are collections of functions.
The .NET runtime contains an intermediate language interpreter, a garbage collector, and more.
Use ToString("X4")
.
The 4 means that the string will be 4 digits long.
Reference: The Hexadecimal ("X") Format Specifier on MSDN.
eval()
can not handle the list object
tf.reset_default_graph()
a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
print("z:", z.eval())
print("grad", grad.eval())
but Session.run()
can
print("grad", sess.run(grad))
correct me if I am wrong
As of git 2.18 you can use git --list-cmds=alias
http://php.net/session.gc-maxlifetime
session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)
I was unable to commit csharp-files (*.cs). In the end the problem was that at some point i installed mod_mono, which made the *.cs-files inaccessible, through its configuration. So it may well be an apache-configuration issue, if only some sort of files are not accessible.
grep ".cs" /etc/apache2/mods-enabled/*
...
mod_mono_auto.conf:AddType application/x-asp-net .cs
...
This is actually possible since Facebook was able to do it. Well, not the actual web developer tools but the execution of Javascript in console.
See this: How does Facebook disable the browser's integrated Developer Tools?
This really wont do much though since there are other ways to bypass this type of client-side security.
When you say it is client-side, it happens outside the control of the server, so there is not much you can do about it. If you are asking why Facebook still does this, this is not really for security but to protect normal users that do not know javascript from running code (that they don't know how to read) into the console. This is common for sites that promise auto-liker service or other Facebook functionality bots after you do what they ask you to do, where in most cases, they give you a snip of javascript to run in console.
If you don't have as much users as Facebook, then I don't think there's any need to do what Facebook is doing.
Even if you disable Javascript in console, running javascript via address bar is still possible.
and if the browser disables javascript at address bar, (When you paste code to the address bar in Google Chrome, it deletes the phrase 'javascript:') pasting javascript into one of the links via inspect element is still possible.
Inspect the anchor:
Paste code in href:
Bottom line is server-side validation and security should be first, then do client-side after.
When using INTEGER
columns (that can be NULL
) in MySQL, PDO has some (to me) unexpected behaviour.
If you use $stmt->execute(Array)
, you have to specify the literal NULL
and cannot give NULL
by variable reference.
So this won't work:
// $val is sometimes null, but sometimes an integer
$stmt->execute(array(
':param' => $val
));
// will cause the error 'incorrect integer value' when $val == null
But this will work:
// $val again is sometimes null, but sometimes an integer
$stmt->execute(array(
':param' => isset($val) ? $val : null
));
// no errors, inserts NULL when $val == null, inserts the integer otherwise
Tried this on MySQL 5.5.15 with PHP 5.4.1
Is this what you meant to do ?
In [7]: x = pd.DataFrame({'one' : ['one', 'two', 'This is very long string very long string very long string veryvery long string']})
In [8]: x
Out[8]:
one
0 one
1 two
2 This is very long string very long string very...
In [9]: x['one'][2]
Out[9]: 'This is very long string very long string very long string veryvery long string'
Another (much safer) approach is to escape all the characters (and not just a few special ones that we currently know) using the unicode escape format \u{code}
:
function escapeRegExp(text) {
return Array.from(text)
.map(char => `\\u{${char.charCodeAt(0).toString(16)}}`)
.join('');
}
console.log(escapeRegExp('a.b')); // '\u{61}\u{2e}\u{62}'
Please note that you need to pass the u
flag for this method to work:
var expression = new RegExp(escapeRegExp(usersString), 'u');
The Enum
public enum Status { Active = 0, Canceled = 3 };
Setting the drop down values from it
cbStatus.DataSource = Enum.GetValues(typeof(Status));
Getting the enum from the selected item
Status status;
Enum.TryParse<Status>(cbStatus.SelectedValue.ToString(), out status);
In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char *
or const char *
.
However, the difference is that if the pointer is const char *
then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char *
then it does not.
As mentioned originally in this answer by SoBeRich, and in my own answer, as of git 2.4.x
git push --atomic origin <branch name> <tag>
(Note: this actually work with HTTPS only with Git 2.24)
As of git 2.4.1, you can do
git config --global push.followTags true
If set to true enable --follow-tags option by default.
You may override this configuration at time of push by specifying --no-follow-tags.
As noted in this thread by Matt Rogers answering Wes Hurd:
--follow-tags
only pushes annotated tags.
git tag -a -m "I'm an annotation" <tagname>
That would be pushed (as opposed to git tag <tagname>
, a lightweight tag, which would not be pushed, as I mentioned here)
Since git 1.8.3 (April 22d, 2013), you no longer have to do 2 commands to push branches, and then to push tags:
The new "
--follow-tags
" option tells "git push
" to push relevant annotated tags when pushing branches out.
You can now try, when pushing new commits:
git push --follow-tags
That won't push all the local tags though, only the one referenced by commits which are pushed with the git push
.
Git 2.4.1+ (Q2 2015) will introduce the option push.followTags
: see "How to make “git push
” include tags within a branch?".
The nuclear option would be git push --mirror
, which will push all refs under refs/
.
You can also push just one tag with your current branch commit:
git push origin : v1.0.0
You can combine the --tags
option with a refspec like:
git push origin --tags :
(since --tags
means: All refs under refs/tags
are pushed, in addition to refspecs explicitly listed on the command line)
You also have this entry "Pushing branches and tags with a single "git push" invocation"
A handy tip was just posted to the Git mailing list by Zoltán Füzesi:
I use
.git/config
to solve this:
[remote "origin"]
url = ...
fetch = +refs/heads/*:refs/remotes/origin/*
push = +refs/heads/*
push = +refs/tags/*
With these lines added
git push origin
will upload all your branches and tags. If you want to upload only some of them, you can enumerate them.
Haven't tried it myself yet, but it looks like it might be useful until some other way of pushing branches and tags at the same time is added to git push.
On the other hand, I don't mind typing:
$ git push && git push --tags
Beware, as commented by Aseem Kishore
push = +refs/heads/*
will force-pushes all your branches.
This bit me just now, so FYI.
René Scheibe adds this interesting comment:
The
--follow-tags
parameter is misleading as only tags under.git/refs/tags
are considered.
Ifgit gc
is run, tags are moved from.git/refs/tags
to.git/packed-refs
. Afterwardsgit push --follow-tags ...
does not work as expected anymore.
Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.
Setting the passenger.Title
with a value that equals to a title.Value
should work.
View:
<select [(ngModel)]="passenger.Title">
<option *ngFor="let title of titleArray" [value]="title.Value">
{{title.Text}}
</option>
</select>
TypeScript used:
class Passenger {
constructor(public Title: string) { };
}
class ValueAndText {
constructor(public Value: string, public Text: string) { }
}
...
export class AppComponent {
passenger: Passenger = new Passenger("Lord");
titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
new ValueAndText("Lord", "Lord-Text")];
}
Is just casting the value returned by time()
#include <stdio.h>
#include <time.h>
int main(void) {
printf("Timestamp: %d\n",(int)time(NULL));
return 0;
}
what you want?
$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167
To get microseconds since the epoch, from C11 on, the portable way is to use
int timespec_get(struct timespec *ts, int base)
Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime
or gettimeofday
(marked obsolete in POSIX.1-2008, which recommends clock_gettime
).
The code for both functions is nearly identical:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>
int main(void) {
struct timespec tms;
/* The C11 way */
/* if (! timespec_get(&tms, TIME_UTC)) { */
/* POSIX.1-2008 way */
if (clock_gettime(CLOCK_REALTIME,&tms)) {
return -1;
}
/* seconds, multiplied with 1 million */
int64_t micros = tms.tv_sec * 1000000;
/* Add full microseconds */
micros += tms.tv_nsec/1000;
/* round up if necessary */
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return 0;
}
argc
is the number of arguments being passed into your program from the command line and argv
is the array of arguments.
You can loop through the arguments knowing the number of them like:
for(int i = 0; i < argc; i++)
{
// argv[i] is the argument at index i
}
It happened to me for wrong tag. By mistake I add the js file in link
tag.
Example: (The Wrong One)
<link rel="stylesheet" href="plugins/timepicker/bootstrap-timepicker.min.js">
It solved by using the correct tag for javascript
. Example:
<script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>