Well, to be able to even get some information about why this happens, I did this:
Another cause might be the fact that you're pointing to the wrong port.
Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.
Check the ports and run some query against the db.
I ended up having to open up the port that I was using (8081 by default). On Linux, you can do the following
sudo iptables -A INPUT -p tcp --dport 8081 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 8081 -m conntrack --ctstate ESTABLISHED -j ACCEPT
You can test to see whether you actually need to do this. Just navigate to your dev server in Chrome on your Android device. If it doesn't respond, then this might be what you need. If it does respond, then this won't help you.
This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.
I faced same issue just fallowed some min steps in Android studio:
Manually fallowing steps in android studio
-------------------------------------------------OR-----------------------------------------------------------------------
i had the same issue. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check named pipes is enabled.
Here's a solution where security checking is disabled (for example, conversing with the localhost) Also, some of the solutions I've seen now contain deprecated methods and such.
/**
* @param configFilePath
* @param ipAddress
* @param userId
* @param password
* @throws MalformedURLException
*/
public Upgrade(String aConfigFilePath, String ipAddress, String userId, String password) {
configFilePath = aConfigFilePath;
baseUri = "https://" + ipAddress + ":" + PORT + "/";
restTemplate = new RestTemplate(createSecureTransport(userId, password, ipAddress, PORT));
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
}
ClientHttpRequestFactory createSecureTransport(String username,
String password, String host, int port) {
HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
HttpClient client = HttpClientBuilder.create()
.setSSLHostnameVerifier(nullHostnameVerifier)
.setSSLContext(createContext())
.setDefaultCredentialsProvider(credentialsProvider).build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(client);
return requestFactory;
}
private SSLContext createContext() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
} };
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
SSLContext.setDefault(sc);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return sc;
} catch (Exception e) {
}
return null;
}
To start redis with a config file all you need to do is specifiy the config file as an argument:
redis-server /root/config/redis.rb
Instead of using and killing PID's I would suggest creating an init script for your service
I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start
and service redis_server stop
to control your server.
I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.
Setting spring.datasource.tomcat.testOnBorrow=true
in application.properties didn't work.
Programmatically setting like below worked without any issues.
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
@Bean
public DataSource dataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setUrl(this.properties.getDatabase().getUrl());
poolProperties.setUsername(this.properties.getDatabase().getUsername());
poolProperties.setPassword(this.properties.getDatabase().getPassword());
//here it is
poolProperties.setTestOnBorrow(true);
poolProperties.setValidationQuery("SELECT 1");
return new DataSource(poolProperties);
}
Numpty here used SQL authentication
instead of Windows (correct)
when adding the login to SQL Server, which also gives you this error if you are using Windows auth.
I listen for WifiManager.NETWORK_STATE_CHANGED_ACTION in a broadcast receiver
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals (action)) {
NetworkInfo netInfo = intent.getParcelableExtra (WifiManager.EXTRA_NETWORK_INFO);
if (ConnectivityManager.TYPE_WIFI == netInfo.getType ()) {
I check for netInfo.isConnected (). Then I am able to use
WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String ssid = info.getSSID();
UPDATE
From android 8.0 onwards we wont be getting SSID of the connected network unless GPS is turned on.
Try using inner join in your Query
Query query=session.createQuery("from Product as p INNER JOIN p.catalog as c
WHERE c.idCatalog= :id and p.productName like :XXX");
query.setParameter("id", 7);
query.setParameter("xxx", "%"+abc+"%");
List list = query.list();
also in the hibernate config file have
<!--hibernate.cfg.xml -->
<property name="show_sql">true</property>
To display what is being queried on the console.
I recompiled the package specification, even though the change was only in the package body. This resolved my issue
On top of using a bridged connection, I had to turn on Find Devices and Content on the VM's Windows Server 2012 control panel network settings. Hope this helps somebody as none the other answers worked to ping the VM machine.
I have broken my head over this issue, and finally here's what worked for me:-
Step1 : Uninstall Entity framework using Nuget package manager
Step2: Delete Entityframework element from App.config
Step3: Reinstall desired version of Entity Framework.
Step4: delete Migrations table and Migrations folder.
Step5: Enable Migrations and Add Migration and Update database
Edit: To view your database on an Emulator follow these steps (for actual device, scroll to the bottom):
Download and install SQLiteBrowser.
Copy the database from the device to your PC:
Android Studio versions < 3.0:
Open DDMS via Tools > Android > Android Device Monitor
Click on your device on the left.
You should see your application:
Go to File Explorer (one of the tabs on the right), go to /data/data/databases
Select the database by just clicking on it.
Go to the top right corner of the Android Device Monitor window. Click on the 'pull a file from the device' button:
A window will open asking you where you want to save your database file. Save it anywhere you want on your PC.
Android Studio versions >= 3.0:
Open Device File Explorer via View > Tool Windows > Device File Explorer
Go to data > data > PACKAGE_NAME > database
, where PACKAGE_NAME is the name of your package (it is com.Movie in the example above)
Right click on the database and select Save As...
. Save it anywhere you want on your PC.
Now, open the SQLiteBrowser you installed. Click on 'open database', navigate to the location you saved the database file, and open. You can now view the contents of your database.
Go to this Github repository and follow the instructions in the readme to be able to view your database on your device. What you get is something like this:
That's it. It goes without saying however that you should undo all these steps before publishing your app.
To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.
if the IIS Manager doesn't open that means you need to install it.
So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7
It's much easier if you use Response.raw
and shutil.copyfileobj()
:
import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
This streams the file to disk without using excessive memory, and the code is simple.
Try to specify the port in
conn = DriverManager.getConnection("jdbc:mysql://localhost/mysql?"
+ "user=root&password=onelife");
I think you should have something like this:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?"
+ "user=root&password=onelife");
Also, the port number in my example (3306) is the default port, but you may change it while installing MySQL.
I think that a better way to specify password and user is to separate them from the URL like this:
connection = DriverManager.getConnection(url, login, password);
For what it's worth I found this issue was happening in a batch import command because of a try/catch loop catching an SQL error (with em->flush()
) that I didn't do anything about. In my case it was because I was trying to insert a record with a non-nullable property left as null.
Typically this would cause a critical exception to happen and the command or controller to halt, but I was just logging this problem instead and carrying on. The SQL error had caused the entity manager to close.
Check your dev.log
file for any silly SQL errors like this as it could be your fault. :)
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
I faced the same issue and found it was due to zookeeper cluster nodes needs ports opened to communicate with each other.
server.1=xx.xx.xx.xx:2888:3888
server.2=xx.xx.xx.xx:2888:3888
server.3=xx.xx.xx.xx:2888:3888
once i allowed these ports through aws security group and restarted. All worked fine for me
I am using Spring Boot 2.2.6(Windows) and faced the same issue when I tried the run the application: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
What solved my problem:
Or follow the @evg solution to grant privilegdes from command line in Linux env.
This is more of a rare issue but I have seen this if someone has copied the entire /var/lib/mysql directory as a way of migrating their DB to another server. The reason it doesn't work is because the database was running and using log files. It doesn't work sometimes if there are logs in /var/log/mysql. The solution is to copy the /var/log/mysql files as well.
Killing the tomcat process(forcefully, kill -9 for Linux) and starting it again solves the issue. My guess is, the tomcat instance doesn't get killed properly using shutdown.bat. So, we need to forcefully kill the process and start again.
If the service is running via brew, you can stop it using the following command:
brew services stop mongodb
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
Add "Everyone" under security. If you added the Server and the users logging in to the database, then this is something you are missing. Hope this helps.
Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.
You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/
Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.
This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.
I go with
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
This happened to me when I had a class in one jar trying to access a private method in a class from another jar. I simply changed the private method to public, recompiled and deployed, and it worked ok afterwards.
I found the solution
since MySQL need the Localhost in-order to work.
go to /etc/network/interfaces file and make sure you have the localhost configuration set there:
auto lo
iface lo inet loopback
NOW RESTART the Networking subsystem and the MySQL Services:
sudo /etc/init.d/networking restart
sudo /etc/init.d/mysql restart
Try it now
I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.
The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.
A co-worker of mine had troubles with Git on Windows (7) git status
checkout
and add
were fast, but git commit
took ages.
We are still trying to find the root cause of this, but cloning the repository into a new folder fixed his problem.
mysql>show processlist;
mysql> kill "number from first col";
In order to resolve this issue make all your data flow tasks in one sequence. It means it should not execute parallel. One data flow task sequence should contain only one data flow task and for this another data flow task as sequence.
Ex:-
From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows
from django.contrib import admin
from django.urls import path
from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^posts/$', post_home, name='post_home'),
]
where posts is an application & post_home is a function in views.py
I do recommend BarcodeLibrary
Here is a small piece of code of how to use it.
BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
{
IncludeLabel = true,
Alignment = AlignmentPositions.CENTER,
Width = 300,
Height = 100,
RotateFlipType = RotateFlipType.RotateNoneFlipNone,
BackColor = Color.White,
ForeColor = Color.Black,
};
Image img = barcode.Encode(TYPE.CODE128B, "123456789");
I've experienced the same problem and now I just found my solution to this issue.
#!/usr/bin/python
import sys
import os
os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))
This is the code[1] for my case. When I tried this script I received error message like :
import: command not found
I found people talks about the shebang. As you see there is the shebang in my python code above. I tried these and those trials but didn't find a good solution.
I finally tried to type the shebang my self.
#!/usr/bin/python
and removed the copied one.
And my problem solved!!!
I copied the code from the internet[1].
And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.
I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)
Journeyer
PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.
[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy
I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.
I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:
jQuery.param
JSON.stringify + encodeURIComponent
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.
Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.
function a(a, b) {
return a + b
};
function call_a() {
return a.apply(a, Array.prototype.slice.call(arguments, 0));
}
console.log(call_a(1, 2))
console: 3
With serialize the data as JSON and Base64, dependency jquery.cookie.js :
var putCookieObj = function(key, value) {
$.cookie(key, btoa(JSON.stringify(value)));
}
var getCookieObj = function (key) {
var cookie = $.cookie(key);
if (typeof cookie === "undefined") return null;
return JSON.parse(atob(cookie));
}
:)
You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.
ng update @angular/cli @angular/core --force
For a full list of options, check the docs: https://angular.io/cli/update
Yes, JSON.stringify
, can be found here, it's included in Firefox 3.5.4 and above.
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html
var myJSONText = JSON.stringify(myObject, replacer);
What is “export default” in JavaScript?
In default export the naming of import is completely independent and we can use any name we like.
I will illustrate this line with a simple example.
Let’s say we have three modules and an index.html file:
export function hello() {
console.log("Modul: Saying hello!");
}
export let variable = 123;
export function hello2() {
console.log("Module2: Saying hello for the second time!");
}
export let variable2 = 456;
modul3.js
export default function hello3() {
console.log("Module3: Saying hello for the third time!");
}
<script type="module">
import * as mod from './modul.js';
import {hello2, variable2} from './modul2.js';
import blabla from './modul3.js'; // ! Here is the important stuff - we name the variable for the module as we like
mod.hello();
console.log("Module: " + mod.variable);
hello2();
console.log("Module2: " + variable2);
blabla();
</script>
The output is:
modul.js:2:10 -> Modul: Saying hello!
index.html:7:9 -> Module: 123
modul2.js:2:10 -> Module2: Saying hello for the second time!
index.html:10:9 -> Module2: 456
modul3.js:2:10 -> Module3: Saying hello for the third time!
So the longer explanation is:
'export default' is used if you want to export a single thing for a module.
So the thing that is important is "import blabla from './modul3.js'" - we could say instead:
"import pamelanderson from './modul3.js" and then pamelanderson();
. This will work just fine when we use 'export default' and basically this is it - it allows us to name it whatever we like when it is default.
P.S.: If you want to test the example - create the files first, and then allow CORS in the browser -> if you are using Firefox type in the URL of the browser: about:config -> Search for "privacy.file_unique_origin" -> change it to "false" -> open index.html -> press F12 to open the console and see the output -> Enjoy and don't forget to return the CORS settings to default.
P.S.2: Sorry for the silly variable naming
More information is in link2medium and link2mdn.
Another way is to use an array as a type, e.g.:
Video[] videoArray = gson.fromJson(json, Video[].class);
This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:
List<Video> videoList = Arrays.asList(videoArray);
IMHO this is much more readable.
In Kotlin this looks like this:
Gson().fromJson(jsonString, Array<Video>::class.java)
To convert this array into List, just use .toList()
method
You could use the segmented buttons example from Bootstrap 3:
<form action="" class="navbar-form navbar-right">
<div class="input-group">
<input type="Search" placeholder="Search..." class="form-control" />
<div class="input-group-btn">
<button class="btn btn-info">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
</div>
</form>
If you want to dump the entire db as csv
#!/bin/bash
host=hostname
uname=username
pass=password
port=portnr
db=db_name
s3_url=s3://bxb2-anl-analyzed-pue2/bxb_ump/db_dump/
DATE=`date +%Y%m%d`
rm -rf $DATE
echo 'show tables' | mysql -B -h${host} -u${uname} -p${pass} -P${port} ${db} > tables.txt
awk 'NR>1' tables.txt > tables_new.txt
while IFS= read -r line
do
mkdir -p $DATE/$line
echo "select * from $line" | mysql -B -h"${host}" -u"${uname}" -p"${pass}" -P"${port}" "${db}" > $DATE/$line/dump.tsv
done < tables_new.txt
touch $DATE/$DATE.fin
rm -rf tables_new.txt tables.txt
With **Java 8* there is an alternative that use streams and lambdas:
public static void recursiveFind(Path path, Consumer<Path> c) {
try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
StreamSupport.stream(newDirectoryStream.spliterator(), false)
.peek(p -> {
c.accept(p);
if (p.toFile()
.isDirectory()) {
recursiveFind(p, c);
}
})
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
So this will print all the files recursively:
recursiveFind(Paths.get("."), System.out::println);
And this will search for a file:
recursiveFind(Paths.get("."), p -> {
if (p.toFile().getName().toString().equals("src")) {
System.out.println(p);
}
});
:active Adds a style to an element that is activated
:focus Adds a style to an element that has keyboard input focus
:hover Adds a style to an element when you mouse over it
:lang Adds a style to an element with a specific lang attribute
:link Adds a style to an unvisited link
:visited Adds a style to a visited link
Source: CSS Pseudo-classes
Calling
for /?
in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found).
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only %~dp$PATH:I - searches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found. %~ftzaI - expands %I to a DIR like output line
In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.
There are different letters you can use like f
for "full path name", d
for drive letter, p
for path, and they can be combined. %~
is the beginning for each of those sequences and a number I
denotes it works on the parameter %I
(where %0
is the complete name of the batch file, just like you assumed).
Create a custom Switch and override setChecked to change color:
public class SwitchPlus extends Switch {
public SwitchPlus(Context context) {
super(context);
}
public SwitchPlus(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwitchPlus(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setChecked(boolean checked) {
super.setChecked(checked);
changeColor(checked);
}
private void changeColor(boolean isChecked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int thumbColor;
int trackColor;
if(isChecked) {
thumbColor = Color.argb(255, 253, 153, 0);
trackColor = thumbColor;
} else {
thumbColor = Color.argb(255, 236, 236, 236);
trackColor = Color.argb(255, 0, 0, 0);
}
try {
getThumbDrawable().setColorFilter(thumbColor, PorterDuff.Mode.MULTIPLY);
getTrackDrawable().setColorFilter(trackColor, PorterDuff.Mode.MULTIPLY);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the log
-related stuff) add them.
So, there's a lot of Python code out there that does things like:
fw.write('\n'.join(line_list) + '\n')
or
fw.write(line + '\n' for line in line_list)
Either one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up…
But you should only do this if you can't avoid it.
It's better if you can create/keep the newlines in the first place—as in Greg Hewgill's suggestions:
line_list.append(new_line + "\n")
And it's even better if you can work at a higher level than raw lines of text, e.g., by using the csv module in the standard library, as esuaro suggests.
For example, right after defining fw
, you might do this:
cw = csv.writer(fw, delimiter='|')
Then, instead of this:
new_line = d[looking_for]+'|'+'|'.join(columns[1:])
line_list.append(new_line)
You do this:
row_list.append(d[looking_for] + columns[1:])
And at the end, instead of this:
fw.writelines(line_list)
You do this:
cw.writerows(row_list)
Finally, your design is "open a file, then build up a list of lines to add to the file, then write them all at once". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a csv.writer
, it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once—but once you've moved the open
all the way to the opposite end of the program from the write
, you've pretty much lost any benefits of all-at-once.)
Pardon my ignorance, but why are you using $('.salesperson')
instead of $('#salesperson')
when dealing with an ID?
Marc Gravell's answer but in VB.NET
Public Shared Function ToDataTable(Of T)(data As IList(Of T)) As DataTable
Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
Dim table As New DataTable()
For i As Integer = 0 To props.Count - 1
Dim prop As PropertyDescriptor = props(i)
table.Columns.Add(prop.Name, prop.PropertyType)
Next
Dim values As Object() = New Object(props.Count - 1) {}
For Each item As T In data
For i As Integer = 0 To values.Length - 1
values(i) = props(i).GetValue(item)
Next
table.Rows.Add(values)
Next
Return table
End Function
Aggregated List of Libraries
Use my tool git_remote_branch (you need Ruby installed on your machine). It's built specifically to make remote branch manipulations dead easy.
Each time it does an operation on your behalf, it prints it in red at the console. Over time, they finally stick into your brain :-)
If you don't want grb to run commands on your behalf, just use the 'explain' feature. The commands will be printed to your console instead of executed for you.
Finally, all commands have aliases, to make memorization easier.
Note that this is alpha software ;-)
Here's the help when you run grb help:
git_remote_branch version 0.2.6 Usage: grb create branch_name [origin_server] grb publish branch_name [origin_server] grb rename branch_name [origin_server] grb delete branch_name [origin_server] grb track branch_name [origin_server] Notes: - If origin_server is not specified, the name 'origin' is assumed (git's default) - The rename functionality renames the current branch The explain meta-command: you can also prepend any command with the keyword 'explain'. Instead of executing the command, git_remote_branch will simply output the list of commands you need to run to accomplish that goal. Example: grb explain create grb explain create my_branch github All commands also have aliases: create: create, new delete: delete, destroy, kill, remove, rm publish: publish, remotize rename: rename, rn, mv, move track: track, follow, grab, fetch
I have employed a slightly different technique in my aspnet MVC 4 site:
_ViewStart.cshtml:
@using System.Web.Caching
@using System.Web.Hosting
@{
Layout = "~/Views/Shared/_Layout.cshtml";
PageData.Add("scriptFormat", string.Format("<script src=\"{{0}}?_={0}\"></script>", GetDeployTicks()));
}
@functions
{
private static string GetDeployTicks()
{
const string cacheKey = "DeployTicks";
var returnValue = HttpRuntime.Cache[cacheKey] as string;
if (null == returnValue)
{
var absolute = HostingEnvironment.MapPath("~/Web.config");
returnValue = File.GetLastWriteTime(absolute).Ticks.ToString();
HttpRuntime.Cache.Insert(cacheKey, returnValue, new CacheDependency(absolute));
}
return returnValue;
}
}
Then in the actual views:
@Scripts.RenderFormat(PageData["scriptFormat"], "~/Scripts/Search/javascriptFile.min.js")
You can override bean definitions with mocks with spring-reinject https://github.com/sgri/spring-reinject/
JSON Schema is not intended to be feature equivalent with XML Schema. There are features in one but not in the other.
In general you can create a mapping from XML to JSON and back again, but that is not the case for XML schema and JSON schema.
That said, if you have mapped a XML file to JSON, it is quite possible to craft an JSON Schema that validates that JSON in nearly the same way that the XSD validates the XML. But it isn't a direct mapping. And it is not possible to guarantee that it will validate the JSON exactly the same as the XSD validates the XML.
For this reason, and unless the two specs are made to be 100% feature compatible, migrating a validation system from XML/XSD to JSON/JSON Schema will require human intervention.
This error occur because of path of project. Change your project path wiht way which dont contain nonAscii character.
Jeff Atwood has a recent blog post about this: The Great Newline Schism
Here is the essence from Wikipedia:
The sequence CR+LF was in common use on many early computer systems that had adopted teletype machines, typically an ASR33, as a console device, because this sequence was required to position those printers at the start of a new line. On these systems, text was often routinely composed to be compatible with these printers, since the concept of device drivers hiding such hardware details from the application was not yet well developed; applications had to talk directly to the teletype machine and follow its conventions. The separation of the two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in one-character time. That is why the sequence was always sent with the CR first. In fact, it was often necessary to send extra characters (extraneous CRs or NULs, which are ignored) to give the print head time to move to the left margin. Even after teletypes were replaced by computer terminals with higher baud rates, many operating systems still supported automatic sending of these fill characters, for compatibility with cheaper terminals that required multiple character times to scroll the display.
Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form
Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Show()
TextBox1.Select()
End Sub
If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this
. In our case we use applicationContext
.
So in Utility class you can define all extension functions.
Utility.kt
fun Context.loadJSONFromAssets(fileName: String): String {
return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
reader.readText()
}
}
MainActivity.kt
You can define private function for load JSON data from assert like this:
lateinit var facilityModelList: ArrayList<FacilityModel>
private fun bindJSONDataInFacilityList() {
facilityModelList = ArrayList<FacilityModel>()
val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
for (i in 0 until facilityJsonArray.length()){
val facilityModel = FacilityModel()
val facilityJSONObject = facilityJsonArray.getJSONObject(i)
facilityModel.Facility = facilityJSONObject.getString("Facility")
facilityModel.District = facilityJSONObject.getString("District")
facilityModel.Province = facilityJSONObject.getString("Province")
facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
facilityModel.code = facilityJSONObject.getInt("code")
facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")
facilityModelList.add(facilityModel)
}
}
You have to pass facilityModelList
in your ListView
FacilityModel.kt
class FacilityModel: Serializable {
var District: String = ""
var Facility: String = ""
var Province: String = ""
var Subdistrict: String = ""
var code: Int = 0
var gps_latitude: Double= 0.0
var gps_longitude: Double= 0.0
}
In my case JSON response start with JSONArray
[
{
"code": 875933,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Amabele Clinic",
"gps_latitude": -32.6634,
"gps_longitude": 27.5239
},
{
"code": 455242,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Burnshill Clinic",
"gps_latitude": -32.7686,
"gps_longitude": 27.055
}
]
You could try this:
SELECT * INTO foo FROM foo_bk
After spending hours, this neatly helped me to solve my problem:
For Oracle 12c:
ID NUMBER GENERATED as IDENTITY
For H2:
ID BIGINT GENERATED as auto_increment
Also make:
@Column(insertable = false)
@ variables are instance variables, without are local variables.
Read more at http://ruby.about.com/od/variables/a/Instance-Variables.htm
In order to use async within the constructor and ensure the data is available when you instantiate the class, you can use this simple pattern:
class FooClass : IFooAsync
{
FooClass
{
this.FooAsync = InitFooTask();
}
public Task FooAsync { get; }
private async Task InitFooTask()
{
await Task.Delay(5000);
}
}
The interface:
public interface IFooAsync
{
Task FooAsync { get; }
}
The usage:
FooClass foo = new FooClass();
if (foo is IFooAsync)
await foo.FooAsync;
The mechanism I tend to use is a combination of readelf -V
to dump the .gnu.version
information from libstdc++, and then a lookup table that matches the largest GLIBCXX_
value extracted.
readelf -sV /usr/lib/libstdc++.so.6 | sed -n 's/.*@@GLIBCXX_//p' | sort -u -V | tail -1
if your version of sort
is too old to have the -V
option (which sorts by version number) then you can use:
tr '.' ' ' | sort -nu -t ' ' -k 1 -k 2 -k 3 -k 4 | tr ' ' '.'
instead of the sort -u -V
, to sort by up to 4 version digits.
In general, matching the ABI version should be good enough.
If you're trying to track down the libstdc++.so.<VERSION>
, though, you can use a little bash like:
file=/usr/lib/libstdc++.so.6
while [ -h $file ]; do file=$(ls -l $file | sed -n 's/.*-> //p'); done
echo ${file#*.so.}
so for my system this yielded 6.0.10
.
If, however, you're trying to get a binary that was compiled on systemX to work on systemY, then these sorts of things will only get you so far. In those cases, carrying along a copy of the libstdc++.so that was used for the application, and then having a run script that does an:
export LD_LIBRARY_PATH=<directory of stashed libstdc++.so>
exec application.bin "$@"
generally works around the issue of the .so that is on the box being incompatible with the version from the application. For more extreme differences in environment, I tend to just add all the dependent libraries until the application works properly. This is the linux equivalent of working around what, for windows, would be considered dll hell.
Like thousands of people, I'm looking for this question:
Can run multiple queries simultaneously, and if there was one error, none would run
I went to this page everywhere
But although the friends here gave good answers, these answers were not good for my problem
So I wrote a function that works well and has almost no problem with sql Injection.
It might be helpful for those who are looking for similar questions so I put them here to use
function arrayOfQuerys($arrayQuery)
{
$mx = true;
$conn->beginTransaction();
try {
foreach ($arrayQuery AS $item) {
$stmt = $conn->prepare($item["query"]);
$stmt->execute($item["params"]);
$result = $stmt->rowCount();
if($result == 0)
$mx = false;
}
if($mx == true)
$conn->commit();
else
$conn->rollBack();
} catch (Exception $e) {
$conn->rollBack();
echo "Failed: " . $e->getMessage();
}
return $mx;
}
for use(example):
$arrayQuery = Array(
Array(
"query" => "UPDATE test SET title = ? WHERE test.id = ?",
"params" => Array("aa1", 1)
),
Array(
"query" => "UPDATE test SET title = ? WHERE test.id = ?",
"params" => Array("bb1", 2)
)
);
arrayOfQuerys($arrayQuery);
and my connection:
try {
$options = array(
//For updates where newvalue = oldvalue PDOStatement::rowCount() returns zero. You can use this:
PDO::MYSQL_ATTR_FOUND_ROWS => true
);
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password, $options);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error connecting to SQL Server: " . $e->getMessage();
}
Note:
This solution helps you to run multiple statement together,
If an incorrect a statement occurs, it does not execute any other statement
How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.
I think the more important thing you need to decide is if null
is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach
loop, that is a sign that there is a bug somewhere else in your code.
After read all Answers I came up with elegant way:
public class MyActivity extends ActionBarActivity {
Fragment fragment ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getSupportFragmentManager();
fragment = fm.findFragmentByTag("myFragmentTag");
if (fragment == null) {
FragmentTransaction ft = fm.beginTransaction();
fragment =new MyFragment();
ft.add(android.R.id.content,fragment,"myFragmentTag");
ft.commit();
}
}
basically you don't need to add a frameLayout as container of your fragment instead you can add straight the fragment into the android root View container
IMPORTANT: don't use replace fragment as most of the approach shown here, unless you don't mind to lose fragment variable instance state during onrecreation process.
Option 1:
You can set CMake variables at command line like this:
cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt
See this to learn how to create a CMake cache entry.
Option 2:
In your shell script build_ios.sh
you can set environment variables CC
and CXX
to point to your C and C++ compiler executable respectively, example:
export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt
Option 3:
Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project()
or enable_language()
command)
set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")
See this to learn how to use set
command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.
Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler
getClass().getResource(path)
loads resources from the classpath, not from a filesystem path.
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
You can also use the following syntax:-
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
From here
From what I gather, Matz does not like the construct
begin
<multiple_lines_of_code>
end while <cond>
because, it's semantics is different than
<single_line_of_code> while <cond>
in that the first construct executes the code first before checking the condition, and the second construct tests the condition first before it executes the code (if ever). I take it Matz prefers to keep the second construct because it matches one line construct of if statements.
I never liked the second construct even for if statements. In all other cases, the computer executes code left-to-right (eg. || and &&) top-to-bottom. Humans read code left-to-right top-to-bottom.
I suggest the following constructs instead:
if <cond> then <one_line_code> # matches case-when-then statement
while <cond> then <one_line_code>
<one_line_code> while <cond>
begin <multiple_line_code> end while <cond> # or something similar but left-to-right
I don't know if those suggestions will parse with the rest of the language. But in any case I prefere keeping left-to-right execution as well as language consistency.
The issue is incompatible web application version with the targeted server. So project facets needs to be changed. In most of the cases the "Dynamic Web Module" property. This should be the value of the servlet-api version supported by the server.
In my case,
I tried changing the web_app value in web.xml. It did not worked.
I tried changing the project facet by right clicking on project properties(as mentioned above), did not work.
What worked is: Changing "version" value as in jst.web to right version from
org.eclipse.wst.common.project.facet.core.xml file. This file is present in the .setting folder under your project root directory.
You may also look at this
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) */
Javascript does not have interfaces. But it can be duck-typed, an example can be found here:
http://reinsbrain.blogspot.com/2008/10/interface-in-javascript.html
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
This method is slightly faster, and slightly more annoying, than the random.choice() method Ignacio posted.
It takes advantage of the nature of pseudo-random algorithms, and banks on bitwise and and shift being faster than generating a new random number for each character.
# must be length 32 -- 5 bits -- the question didn't specify using the full set
# of uppercase letters ;)
_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
def generate_with_randbits(size=32):
def chop(x):
while x:
yield x & 31
x = x >> 5
return ''.join(_ALPHABET[x] for x in chop(random.getrandbits(size * 5))).ljust(size, 'A')
...create a generator that takes out 5 bit numbers at a time 0..31 until none left
...join() the results of the generator on a random number with the right bits
With Timeit, for 32-character strings, the timing was:
[('generate_with_random_choice', 28.92901611328125),
('generate_with_randbits', 20.0293550491333)]
...but for 64 character strings, randbits loses out ;)
I would probably never use this approach in production code unless I really disliked my co-workers.
edit: updated to suit the question (uppercase and digits only), and use bitwise operators & and >> instead of % and //
Not perfect but close:
newcol<-sapply(rownames(t), function(rn){z[match(rn, rownames(z)), 5]})
cbind(data.frame(t), newcol)
When you start up or just join a project based on webapplications, the design of interface is maybe good. Otherwise this should be changed. In order to Web 2.0 applications you will work with dynamic contents, many effects and other stuff. All these things are fine, but no one thought about to style up the JavaScript alert and confirm boxes. Here is the they way,.. completely dynamic, JS and CSS driven Create simple html file
<html>
<head>
<title>jsConfirmSyle</title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script type="text/javascript" src="jsConfirmStyle.js"></script>
<script type="text/javascript">
function confirmation() {
var answer = confirm("Wanna visit google?")
if (answer){
window.location = "http://www.google.com/";
}
}
</script>
<style type="text/css">
body {
background-color: white;
font-family: sans-serif;
}
#jsconfirm {
border-color: #c0c0c0;
border-width: 2px 4px 4px 2px;
left: 0;
margin: 0;
padding: 0;
position: absolute;
top: -1000px;
z-index: 100;
}
#jsconfirm table {
background-color: #fff;
border: 2px groove #c0c0c0;
height: 150px;
width: 300px;
}
#jsconfirmtitle {
background-color: #B0B0B0;
font-weight: bold;
height: 20px;
text-align: center;
}
#jsconfirmbuttons {
height: 50px;
text-align: center;
}
#jsconfirmbuttons input {
background-color: #E9E9CF;
color: #000000;
font-weight: bold;
width: 125px;
height: 33px;
padding-left: 20px;
}
#jsconfirmleft{
background-image: url(left.png);
}
#jsconfirmright{
background-image: url(right.png);
}
< /style>
</head>
<body>
<p><br />
<a href="#"
onclick="javascript:showConfirm('Please confirm','Are you really really sure to visit google?','Yes','http://www.google.com','No','#')">JsConfirmStyled</a></p>
<p><a href="#" onclick="confirmation()">standard</a></p>
</body>
</html>
Then create simple js file name jsConfirmStyle.js. Here is simple js code
ie5=(document.getElementById&&document.all&&document.styleSheets)?1:0;
nn6=(document.getElementById&&!document.all)?1:0;
xConfirmStart=800;
yConfirmStart=100;
if(ie5||nn6) {
if(ie5) cs=2,th=30;
else cs=0,th=20;
document.write(
"<div id='jsconfirm'>"+
"<table>"+
"<tr><td id='jsconfirmtitle'></td></tr>"+
"<tr><td id='jsconfirmcontent'></td></tr>"+
"<tr><td id='jsconfirmbuttons'>"+
"<input id='jsconfirmleft' type='button' value='' onclick='leftJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
" "+
"<input id='jsconfirmright' type='button' value='' onclick='rightJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
"</td></tr>"+
"</table>"+
"</div>"
);
}
document.write("<div id='jsconfirmfade'></div>");
function leftJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=leftJsConfirmUri;
}
function rightJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=rightJsConfirmUri;
}
function confirmAlternative() {
if(confirm("Scipt requieres a better browser!")) document.location.href="http://www.mozilla.org";
}
leftJsConfirmUri = '';
rightJsConfirmUri = '';
/**
* Show the message/confirm box
*/
function showConfirm(confirmtitle,confirmcontent,confirmlefttext,confirmlefturi,confirmrighttext,con firmrighturi) {
document.getElementById("jsconfirmtitle").innerHTML=confirmtitle;
document.getElementById("jsconfirmcontent").innerHTML=confirmcontent;
document.getElementById("jsconfirmleft").value=confirmlefttext;
document.getElementById("jsconfirmright").value=confirmrighttext;
leftJsConfirmUri=confirmlefturi;
rightJsConfirmUri=confirmrighturi;
xConfirm=xConfirmStart, yConfirm=yConfirmStart;
if(ie5) {
document.getElementById("jsconfirm").style.left='25%';
document.getElementById("jsconfirm").style.top='35%';
}
else if(nn6) {
document.getElementById("jsconfirm").style.top='25%';
document.getElementById("jsconfirm").style.left='35%';
}
else confirmAlternative();
}
I had the same issue, and the solution is very simple, just change to git bash from cmd or other windows command line tools. Windows sometimes does not work well with git npm dependencies.
I found that I can run this command:
notepad $((Split-Path $profile -Parent) + "\profile.ps1")
and it opens my default powershell profile (at least when using Terminal for Windows). I found that here.
Then add an alias. For example, here is my alias of jn
for jupyter notebook
(I hate typing out the cumbersome jupyter notebook
every time):
Set-Alias -Name jn -Value C:\Users\words\Anaconda3\Scripts\jupyter-notebook.exe
Somewhat OT: If you're using Rails, the standard formatting of webpages may be different. For data entry forms text
boxes are scrollable, but character varying
(Rails string
) boxes are one-line. Show views are as long as needed.
Other answers create a new copy of the array, if you want to modify the array in place you can use:
arr.splice(_.findIndex(arr, { id: 3 }), 1);
But that assumes that the element will always be found inside the array (because if is not found it will still remove the last element). To be safe you can use:
var index = _.findIndex(arr, { id: 3 });
if (index > -1) {
arr.splice(index, 1);
}
Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it:
unsigned char buffer[10];
FILE *ptr;
ptr = fopen("test.bin","rb"); // r for read, b for binary
fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer
You said you can read it, but it's not outputting correctly... keep in mind that when you "output" this data, you're not reading ASCII, so it's not like printing a string to the screen:
for(int i = 0; i<10; i++)
printf("%u ", buffer[i]); // prints a series of bytes
Writing to a file is pretty much the same, with the exception that you're using fwrite()
instead of fread()
:
FILE *write_ptr;
write_ptr = fopen("test.bin","wb"); // w for write, b for binary
fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer
Since we're talking Linux.. there's an easy way to do a sanity check. Install hexdump
on your system (if it's not already on there) and dump your file:
mike@mike-VirtualBox:~/C$ hexdump test.bin
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000010 0001 003e 0001 0000 0000 0000 0000 0000
...
Now compare that to your output:
mike@mike-VirtualBox:~/C$ ./a.out
127 69 76 70 2 1 1 0 0 0
hmm, maybe change the printf
to a %x
to make this a little clearer:
mike@mike-VirtualBox:~/C$ ./a.out
7F 45 4C 46 2 1 1 0 0 0
Hey, look! The data matches up now*. Awesome, we must be reading the binary file correctly!
*Note the bytes are just swapped on the output but that data is correct, you can adjust for this sort of thing
AutoPostBack property:
Asp.net controls which cannot submit the Form (PostBack) on their own and hence ASP.Net has provided a feature using
AutoPostBack = "true"
: which controls like DropDownList, CheckBoxList, RadioButtonList, etc. can perform PostBack(when clicked on it).
And
AutoPostBack = "false"
It is the by default state of controls which can perform Postback on button submit.
I think this is a best practice (You may be have many Tomcat instance in same computer, you want per Tomcat instance use other Java Runtime Environment):
This is manual inside file: catalina.sh
# JRE_HOME Must point at your Java Runtime installation.
# Defaults to JAVA_HOME if empty. If JRE_HOME and JAVA_HOME
# are both set, JRE_HOME is used.
<!DOCTYPE html>
<html>
<head>
<script>
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>
This should work for you :) Yes var should be used
First you need to start karma server with
karma start
Then, you can use grep to filter a specific test or describe block:
karma run -- --grep=testDescriptionFilter
I had the same problem and then wrote this shell script which kills all of the existing node processes:
#!/bin/bash
echo "The following node processes were found:"
ps aux | grep " node " | grep -v grep
nodepids=$(ps aux | grep " node " | grep -v grep | cut -c10-15)
echo "OK, so we will stop these process/es now..."
for nodepid in ${nodepids[@]}
do
echo "Stopping PID :"$nodepid
kill -9 $nodepid
done
echo "Done"
After this is saved as a shell script (xxx.sh) file you might want to add it to your PATH as described here.
(Please note that this will kill all of the processes with " node " in it's name except grep's own, so I guess in some cases it may also kill some other processes with a similar name)
The Accepted Answer is not working for me, This is what works for me
WebSettings webSetting = webView.getSettings();
webSetting.setBuiltInZoomControls(true);
webView1.setWebViewClient(new WebViewClient());
webView.loadUrl("file:///android_asset/index.html");
Make it dataType
instead of datatype
.
And add below code in php as your ajax request is expecting json and will not accept anything, but json.
header('Content-Type: application/json');
Correct Content type for JSON and JSONP
The response visible in firebug is text data. Check Content-Type
of the response header to verify, if the response is json. It should be application/json
for dataType:'json'
and text/html
for dataType:'html'
.
You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
document.write(rs.fields(1));
rs.movenext;
}
rs.close;
connection.close;
A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.
And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)
I don't know why you should make it so complicated as the others.
The following code is much simpler to understand and about 25% faster than the other solutions who uses the log function (called the function 20 Mio. times with different parameters)
function formatBytes($bytes, $precision = 2) {
$units = ['Byte', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'];
$i = 0;
while($bytes > 1024) {
$bytes /= 1024;
$i++;
}
return round($bytes, $precision) . ' ' . $units[$i];
}
To find the point where to add the -lm in Eclipse-IDE is really horrible, so it took me some time.
If someone else also uses Edlipse, here's the way how to add the command:
Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Miscelleaneous -> Linker flags: in this field add the command -lm
Aha!
This can be done with the following PHP function:
error_log('Some message here.');
Found the answer here: Print something in PHP built-in web server
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo;
wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
ssid = wifiInfo.getSSID();
}
Remember every time user disconnect or connect to new SSID or any wifi state change then you need to initialize WifiInfo i.e wifiInfo = wifiManager.getConnectionInfo();
Font awesome use SVG icons. So, you can resize it for your requirment.
just use CSS class for that,
.large-icon{
font-size:10em;
//or
font-size:200%;
//or
font-size:50px;
}
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
To use the Like Button and have the Open Graph inspect your website, you need an application.
So you need to associate the Like Button with a fb:app_id
If you want other users to see the administration page for your website on Facebook you add fb:admins
. So if you are the developer of the application and the website owner there is no need to add fb:admins
This one worked for me:
\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St)\.?
The source: https://www.codeproject.com/Tips/989012/Validate-and-Find-Addresses-with-RegEx
An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.
For anyone seeking a solution that does not use the command line: ctrl+shift+t
VBA uses a garbage collector which is implemented by reference counting.
There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook
creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.
Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)
The apps UI only works for panels.
The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.
Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.
Alternatively you can also draw the button somewhere else and insert it as an image.
More info: https://developers.google.com/apps-script/guides/menus
using System.Text;
...
..
static void Main(String[] args){
var driver = new InternetExplorerDriver(@"C:\Users\PathToTheFolderContainingIEDriver.exe");
driver.Navigate().GoToUrl("https://www.google.com/");
Console.Read();
}
You need not include the .exe file. The path to the folder containing the .exe worked for me
To create a read-only user, you have to setup a different user than the one owning the tables you want to access.
If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:
ALTER SESSION SET CURRENT_SCHEMA=XYZ
CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1
So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL
SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER
SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS');
You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.
Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt
) such as /mnt/c/Users/yourusername/files
within WSL. These files stay synced between WSL and Windows.
For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/
allow from all
will not work along with Require local
. Instead, try Require ip xxx.xxx.xxx.xx
For Example:
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
Require ip 10.0.0.1
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
To be short, please use fmt.Printf("%T", var1)
or its other variants in the fmt package.
I've dealt with this for as long as Visual Studio existed. And yes, even in the current version it still fails (especially for large projects.)
I want to share small free tool that my friend and I wrote to address this exact same issue. You basically close your solution, drag its folder into the icon for this tool and it will reset all intermediary files for you. (Read the text manual inside if you want to know which ones. It's not just one file.)
I use it to clean up all my VS projects. So here you go:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
std::string input = "abc,def, ghi";
std::istringstream ss(input);
std::string token;
size_t pos=-1;
while(ss>>token) {
while ((pos=token.rfind(',')) != std::string::npos) {
token.erase(pos, 1);
}
std::cout << token << '\n';
}
}
The first answer is a very good one. In order to get to the Expert level, you should do a PhD with some of the Experts themselves.
I suggest you to visit the Haskell page: http://haskell.org. There you have a lot of material, and a lot of references to the most up-to-date stuff in Haskell, approved by the Haskell community.
I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum and then use this code to retrieve it:
public static string GetDescription<T>(this object enumerationValue)
where T : struct
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
As an example:
public enum Cycle : int
{
[Description("Daily Cycle")]
Daily = 1,
Weekly,
Monthly
}
This code nicely caters for enums where you don't need a "Friendly name" and will return just the .ToString() of the enum.
The three ways are:
//NSArray
NSArray *arrData = @[@1,@2,@3,@4];
// 1.Classical
for (int i=0; i< [arrData count]; i++){
NSLog(@"[%d]:%@",i,arrData[i]);
}
// 2.Fast iteration
for (id element in arrData){
NSLog(@"%@",element);
}
// 3.Blocks
[arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"[%lu]:%@",idx,obj);
// Set stop to YES in case you want to break the iteration
}];
Set the data as a vector and then place in the function.
None of these other answers worked for me. Here's what I had to do to run a procedure in SQL Developer 3.2.20.10:
SET serveroutput on;
DECLARE
testvar varchar(100);
BEGIN
testvar := 'dude';
schema.MY_PROC(testvar);
dbms_output.enable;
dbms_output.put_line(testvar);
END;
And then you'd have to go check the table for whatever your proc was supposed to do with that passed-in variable -- the output will just confirm that the variable received the value (and theoretically, passed it to the proc).
NOTE (differences with mine vs. others):
:
prior to the variable name.package.
or .packages.
between the schema name and the procedure name&
in the variable's value.print
anywherevar
to declare the variableAll of these problems left me scratching my head for the longest and these answers that have these egregious errors out to be taken out and tarred and feathered.
The angular2-moment library has pipes like {{myDate | amTimeAgo}} to use in .html files.
Those same pipes can also be accessed as Typescript functions within a component class (.ts) file. First install the library as instructed:
npm install --save angular2-moment
In the node_modules/angular2-moment will now be ".pipe.d.ts" files like calendar.pipe.d.ts, date-format.pipe.d.ts and many more.
Each of those contains the Typescript function name for the equivalent pipe, for example, DateFormatPipe() is the function for amDateFormatPipe.
To use DateFormatPipe in your project, import and add it to your global providers in app.module.ts:
import { DateFormatPipe } from "angular2-moment";
.....
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ...., DateFormatPipe]
Then in any component where you want to use the function, import it on top, inject into the constructor and use:
import { DateFormatPipe } from "angular2-moment";
....
constructor(......., public dfp: DateFormatPipe) {
let raw = new Date(2015, 1, 12);
this.formattedDate = dfp.transform(raw, 'D MMM YYYY');
}
To use any of the functions follow this process. It would be nice if there was one way to gain access to all the functions, but none of the above solutions worked for me.
Method distinct is an intermediate operation that filters the stream and allows only distinct values (by default using the Object::equals method) to pass to the next operation.
I wrote an example below for your case,
// Create the list with duplicates.
List<String> listAll = Arrays.asList("CO2", "CH4", "SO2", "CO2", "CH4", "SO2", "CO2", "CH4", "SO2");
// Create a list with the distinct elements using stream.
List<String> listDistinct = listAll.stream().distinct().collect(Collectors.toList());
// Display them to terminal using stream::collect with a build in Collector.
String collectAll = listAll.stream().collect(Collectors.joining(", "));
System.out.println(collectAll); //=> CO2, CH4, SO2, CO2, CH4 etc..
String collectDistinct = listDistinct.stream().collect(Collectors.joining(", "));
System.out.println(collectDistinct); //=> CO2, CH4, SO2
A few ways to extend String.prototype
, or use ES2015 template literals.
var result = document.querySelector('#result');_x000D_
// -----------------------------------------------------------------------------------_x000D_
// Classic_x000D_
String.prototype.format = String.prototype.format ||_x000D_
function () {_x000D_
var args = Array.prototype.slice.call(arguments);_x000D_
var replacer = function (a){return args[a.substr(1)-1];};_x000D_
return this.replace(/(\$\d+)/gm, replacer)_x000D_
};_x000D_
result.textContent = _x000D_
'hello $1, $2'.format('[world]', '[how are you?]');_x000D_
_x000D_
// ES2015#1_x000D_
'use strict'_x000D_
String.prototype.format2 = String.prototype.format2 ||_x000D_
function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); };_x000D_
result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]');_x000D_
_x000D_
// ES2015#2: template literal_x000D_
var merge = ['[good]', '[know]'];_x000D_
result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;
_x000D_
<pre id="result"></pre>
_x000D_
For url like https://myapp.com/user/666/read?age=23 use
import { combineLatest } from 'rxjs';
// ...
combineLatest( [this.route.paramMap, this.route.queryParamMap] )
.subscribe( ([pathParams, queryParams]) => {
let userId = pathParams.get('userId'); // =666
let age = queryParams.get('age'); // =23
// ...
})
In case when you use this.router.navigate([someUrl]);
and your query parameters are embedded in someUrl
string then angular encodes a URL and you get something like this https://myapp.com/user/666/read%3Fage%323 - and above solution will give wrong result (queryParams will be empty, and path params can be glued to last path param if it is on the path end). In this case change the way of navigation to this
this.router.navigateByUrl(someUrl);
If the value is <0, the serlet is instantiated when the request comes, else >=0 the container will load in the increasing order of the values. if 2 or more servlets have the same value, then the order of the servlets declared in the web.xml.
The most recent version of Sublime has fixed this issue, click on Preferences, click on Theme select Adaptive.sublime-theme. This will change the sidebar to a dark colored background.
In general, when you need a character that is "special" in regexes, just prefix it with a \
. So a literal [
would be \[
.
Regarding some points mentioned in previous answers, and to improve readability:
No need for data.loc or query, but I do think it is a bit long.
The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.
I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.
q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time
df.loc[q_product & q_start & q_end, c('Time,Product')]
# c is just a convenience
c = lambda v: v.split(',')
I got same problem if i understand your question correctly, I want to know the last inserted id after every insert performance in SQLite operation. i tried the following statement:
select * from table_name order by id desc limit 1
The id is the first column and primary key of the table_name, the mentioned statement show me the record with the largest id.
But the premise is u never deleted any row so the numbers of id equal to the numbers of rows.
Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.
// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');
// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';
// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;
// see what you get
var_dump($sql);
Update: (a short version and update missing comma)
$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';
You could use the stopifnot()
function if you want the program to produce an error:
foo <- function(x) {
stopifnot(x > 500)
# rest of program
}
None of the above answers were complete for me.
If your field is named field
, so the selector should be the following one:
IFNULL(`field`,0) AS field
For example in a SELECT query:
SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`
Hope this can help someone to not waste time.
Here is a real world example. In this it is necessary to initialize the array foundFiles
first to zero length.
(As emphasized in other answers: This initializes not an element and especially not an element with index zero because that would mean the array had length 1. The array has zero length after this line!).
If the part = string[0]
is omitted, there is a compiler error!
This is because of the catch block without rethrow. The C# compiler recognizes the code path, that the function Directory.GetFiles()
can throw an Exception, so that the array could be uninitialized.
Before anyone says, not rethrowing the exception would be bad error handling: This is not true. Error handling has to fit the requirements.
In this case it is assumed that the program should continue in case of a directory which cannot be read, and not break- the best example is a function traversing through a directory structure. Here the error handling is just logging it. Of course this could be done better, e.g. collecting all directories with failed GetFiles(Dir)
calls in a list, but this will lead too far here.
It is enough to state that avoiding throw
is a valid scenario, and so the array has to be initialized to length zero. It would be enough to do this in the catch block, but this would be bad style.
The call to GetFiles(Dir)
resizes the array.
string[] foundFiles= new string[0];
string dir = @"c:\";
try
{
foundFiles = Directory.GetFiles(dir); // Remark; Array is resized from length zero
}
// Please add appropriate Exception handling yourself
catch (IOException)
{
Console.WriteLine("Log: Warning! IOException while reading directory: " + dir);
// throw; // This would throw Exception to caller and avoid compiler error
}
foreach (string filename in foundFiles)
Console.WriteLine("Filename: " + filename);
Since --with-ssl is not recognized anymore I just installed the libssl-dev
.
For debian based systems:
sudo apt-get install libssl-dev
For CentOS and RHEL
sudo yum install openssl-devel
To restart the make first clean up by:
make clean
Then start again and execute the following commands one after the other:
./configure
make
make test
make install
For further information on OpenSSL visit the Ubuntu Help Page on OpenSSL.
much easier:
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm" />
You should know more about java.lang.Math.max
:
java.lang.Math.max(arg1,arg2)
only accepts 2 arguments but you are
writing 3 arguments in your code.double
,int
,long
and float
but your are
writing String
arguments in Math.max function. You need to parse them in the required type.You code will produce compile time error because of above mismatches.
Try following updated code, that will solve your purpose:
import java.lang.Math;
import java.util.Scanner;
public class max {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please input 3 integers: ");
int x = Integer.parseInt(keyboard.nextLine());
int y = Integer.parseInt(keyboard.nextLine());
int z = Integer.parseInt(keyboard.nextLine());
int max = Math.max(x,y);
if(max>y){ //suppose x is max then compare x with z to find max number
max = Math.max(x,z);
}
else{ //if y is max then compare y with z to find max number
max = Math.max(y,z);
}
System.out.println("The max of three is: " + max);
}
}
This post describes it very nicely.
In short: utf8_unicode_ci
uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci
is a more simple sort order which results in "less accurate" sorting results.
In viewDidLoad swift 4.2 The code like this
let viewTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard))
view.addGestureRecognizer(viewTap)
@objc func dismissKeyboard() {
view.endEditing(true)
}
Based on Cobbal's answer, here's what I did:
In my JavaScript
I put the following:
setInterval(function() {
if(window.clear) {
window.clear();
console.log("this is highly repeated code");
}
}, 10);
The conditional code won't run until you ASSIGN window.clear (meaning your log is empty until you do so). IN THE DEBUG CONSOLE TYPE:
window.clear = clear;
Mac OS 10.6.8 - Chrome 15.0.874.106
For Linux
On the old machine:
code --list-extensions > vscode-extensions.list
On the new machine:
cat vscode-extensions.list | xargs -L 1 code --install-extension
Try using "/" instead of "\" for the path to your image. Some comments here seem to come from people that do not understand some of us are simply learning web development which in many cases is best done locally. So instead of using src=C:\Pics\H.gif use src="C:/Pics/H.gif" for an absolute path or just src="Pics/H.gif" for a relative path if your Pics are in a sub-directory of your html page's location). Note also, it is good practice to surround your path with quotes. otherwise you will have problems with paths that include spaces and other odd characters.
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
In scala , for string Interpolation we have $ that saves the day and make our life much easy:
For Example: You want to define a function that takes input name and age and says Hello With the name and says its age. That can be written like this:
def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is $age"
Hence , When you call this function: like this :
funcStringInterpolationDemo("Shivansh",22)
Its output would be :
Hey ! my name is Shivansh and my age is 22
You can write the code to change it in the same line, like if you want to add 10 years to the age !
then function could be :
def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is ${age+10}"
And now the output would be :
Hey ! my name is Shivansh and my age is 32
in my case i click on recent apps shortcut on my cell phone and close all apps. This solution always work for me, because this error not related to code.
I only change/remove the class:
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
I explored another two ways to accomplish this task. It may be helpful for someone.
The first one is easy:
In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']
And the second one use map
and lambda
function. It may be appropriate for more complex tasks:
In [36]: s = 'foobar12'
In [37]: a = map(lambda c: c, s)
In [38]: a
Out[38]: ['f', 'o', 'o', 'b', 'a', 'r', '1', '2']
For example
# isdigit, isspace or another facilities such as regexp may be used
In [40]: a = map(lambda c: c if c.isalpha() else '', s)
In [41]: a
Out[41]: ['f', 'o', 'o', 'b', 'a', 'r', '', '']
See python docs for more methods
You can use a special designated object as the null object in case of references as follows:
class SomeClass
{
public:
int operator==(SomeClass &object)
{
if(this == &object)
{
return true;
}
return false;
}
static SomeClass NullObject;
};
SomeClass SomeClass::NullObject;
void print(SomeClass &val)
{
if(val == SomeClass::NullObject)
{
printf("\nNULL");
}
else
{
printf("\nNOT NULL");
}
}
Putting *args
and/or **kwargs
as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
def my_sum(*args):
return sum(args)
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them args
and kwargs
, that’s just a convention. It’s the *
and **
that do the magic.
The official Python documentation has a more in-depth look.
I really had high hopes for dompdf (it is a cool idea) but the positioning issue are a major factor in my using fpdf. Though it is tedious as every element has to be set; it is powerful as all get out.
I lay an image underneath my workspace in the document to put my layout on top of to fit. Its always been sufficient even for columns (requires a tiny bit of php string calculation, but nothing too terribly heady).
Good luck.
$_SERVER['REQUEST_URI']
For more details on what info is available in the $_SERVER array, see the PHP manual page for it.
If you also need the query string (the bit after the ?
in a URL), that part is in this variable:
$_SERVER['QUERY_STRING']
On windows, I have observed that this issue shows up if you do not have administrative rights (i.e., you are not a local administrator) on the machine.
As someone else suggested, the solution seems to be to install locally by not using the -g
hint.
You can also just use:
Write-Host "";
Or, to put it in terms of your specific question:
$str = ""
foreach($line in $file){
if($line -Match $review){ #Special condition
$str += Write-Host ""
$str += ANSWER #looking for ANSWER
}
#code.....
}
Unfortunately, I believe that is already the best way (although list()
is slightly better than listFiles()
, since it doesn't construct File
objects).
Another solution: https://datatables.net/blog/2014-12-18
with 2 JavaScript libraries:
then only this :
$(document).ready(function() {
$.fn.dataTable.moment( 'DD/MM/YYYY' );
$('#example').DataTable();
});
I am not sure if this is pythonic, but seems to work
def alternate_list(a):
return a[::2], a[1::2]
key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))
you can use Dependency Walker to view the function name. you can see the function's parameters only if it's decorated. read the following from the FAQ:
How do I view the parameter and return types of a function? For most functions, this information is simply not present in the module. The Windows' module file format only provides a single text string to identify each function. There is no structured way to list the number of parameters, the parameter types, or the return type. However, some languages do something called function "decoration" or "mangling", which is the process of encoding information into the text string. For example, a function like int Foo(int, int) encoded with simple decoration might be exported as _Foo@8. The 8 refers to the number of bytes used by the parameters. If C++ decoration is used, the function would be exported as ?Foo@@YGHHH@Z, which can be directly decoded back to the function's original prototype: int Foo(int, int). Dependency Walker supports C++ undecoration by using the Undecorate C++ Functions Command.
The only way to see more is to start saving them before the user's tweet count hits 3200. Services which show more than 3200 tweets have saved them in their own dbs. There's currently no way to get more than that through any Twitter API.
https://dev.twitter.com/discussions/276
Note from that second link: "…the 3,200 limit is for browsing the timeline only. Tweets can always be requested by their ID using the GET statuses/show/:id method."
>>> x='$120'
>>> import string
>>> a=string.maketrans('','')
>>> ch=a.translate(a, string.digits)
>>> int(x.translate(a, ch))
120
If you use find
from GNU fileutils:
size=$( find . -maxdepth 1 -type f -name filename -printf '%s' )
Unfortunately, other implementations of find
usually don't support -maxdepth
, nor -printf
. This is the case for e.g. Solaris and macOS find
.
Changing the Navbar color is different (and a little easier) in Bootstrap 4. You can create a custom navbar class, and then reference it to change the navbar without impacting other Bootstrap navs..
<nav class="navbar navbar-custom">...</nav>
Bootstrap 4.3+
The CSS required to change the Navbar is much less in Bootstrap 4...
.navbar-custom {
background-color: #ff5500;
}
/* change the brand and text color */
.navbar-custom .navbar-brand,
.navbar-custom .navbar-text {
color: rgba(255,255,255,.8);
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
color: rgba(255,255,255,.5);
}
/* change the color of active or hovered links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:hover .nav-link {
color: #ffffff;
}
Bootstrap 4 Custom Navbar Demo
Changing the active/hover link background color also works with the same CSS, but you must adjust the padding if you want the bg color to fill the full height of the link...
py-0
to remove vertical padding from the entire navbar...
<nav class="navbar navbar-expand-sm navbar-custom py-0">..</nav>
/* change the link color and padding */
.navbar-custom .navbar-nav .nav-link {
color: rgba(255,255,255,.5);
padding: .75rem 1rem;
}
/* change the color and background color of active links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:hover .nav-link {
color: #ffffff;
background-color: #333;
}
Bootstrap 4 Change Link and Background Color Demo
Also see: Bootstrap 4 Change Hamburger Toggler Color
<nav class="navbar navbar-custom">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">...
</button>
<a class="navbar-brand" href="#">Title</a>
</div>
...
</nav>
.navbar-custom {
background-color:#229922;
color:#ffffff;
border-radius:0;
}
.navbar-custom .navbar-nav > li > a {
color:#fff;
}
.navbar-custom .navbar-nav > .active > a {
color: #ffffff;
background-color:transparent;
}
.navbar-custom .navbar-nav > li > a:hover,
.navbar-custom .navbar-nav > li > a:focus,
.navbar-custom .navbar-nav > .active > a:hover,
.navbar-custom .navbar-nav > .active > a:focus,
.navbar-custom .navbar-nav > .open >a {
text-decoration: none;
background-color: #33aa33;
}
.navbar-custom .navbar-brand {
color:#eeeeee;
}
.navbar-custom .navbar-toggle {
background-color:#eeeeee;
}
.navbar-custom .icon-bar {
background-color:#33aa33;
}
If the Navbar has dropdowns, add the following to change dropdown color(s):
/* for dropdowns only */
.navbar-custom .navbar-nav .dropdown-menu {
background-color: #33aa33;
}
.navbar-custom .navbar-nav .dropdown-menu>li>a {
color: #fff;
}
.navbar-custom .navbar-nav .dropdown-menu>li>a:hover,.navbar-custom .navbar-nav .dropdown-menu>li>a:focus {
color: #33aa33;
}
If you want to change the theme colors all together (beyond the navbar), see this answer
If you are in an ATL/MFC environment, You can use the ATL conversion macro:
#include <atlbase.h>
#include <atlconv.h>
. . .
string myStr("My string");
CA2W unicodeStr(myStr);
You can then use unicodeStr as an LPCWSTR. The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.
Try the following one-liner (display top-20 biggest files):
ls -1Rs | sed -e "s/^ *//" | grep "^[0-9]" | sort -nr | head -n20
or (human readable sizes):
ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20
Works fine under Linux/BSD/OSX in comparison to other answers, as find's
-printf
option doesn't exist on OSX/BSD andstat
has different parameters depending on OS. However the second command to work on OSX/BSD properly (assort
doesn't have-h
), installsort
fromcoreutils
or remove-h
fromls
and usesort -nr
instead.
So these aliases are useful to have in your rc files:
alias big='du -ah . | sort -rh | head -20'
alias big-files='ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20'
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
First I think you need to fix your lists, as the first node of a <ul>
must be a <li>
(stackoverflow ref). Once that is setup you can do this:
// note this array has outer scope
var phrases = [];
$('.phrase').each(function(){
// this is inner scope, in reference to the .phrase element
var phrase = '';
$(this).find('li').each(function(){
// cache jquery var
var current = $(this);
// check if our current li has children (sub elements)
// if it does, skip it
// ps, you can work with this by seeing if the first child
// is a UL with blank inside and odd your custom BLANK text
if(current.children().size() > 0) {return true;}
// add current text to our current phrase
phrase += current.text();
});
// now that our current phrase is completely build we add it to our outer array
phrases.push(phrase);
});
// note the comma in the alert shows separate phrases
alert(phrases);
Working jsfiddle.
One thing is if you get the .text()
of an upper level li
you will get all sub level text with it.
Keeping an array will allow for many multiple phrases to be extracted.
EDIT:
This should work better with an empty UL
with no LI
:
// outer scope
var phrases = [];
$('.phrase').each(function(){
// inner scope
var phrase = '';
$(this).find('li').each(function(){
// cache jquery object
var current = $(this);
// check for sub levels
if(current.children().size() > 0) {
// check is sublevel is just empty UL
var emptyULtest = current.children().eq(0);
if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
phrase += ' -BLANK- '; //custom blank text
return true;
} else {
// else it is an actual sublevel with li's
return true;
}
}
// if it gets to here it is actual li
phrase += current.text();
});
phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);
POJO stands for Plain Old Java Object, and would be used to describe the same things as a "Normal Class" whereas a JavaBean follows a set of rules. Most commonly Beans use getters and setters to protect their member variables, which are typically set to private and have a no-argument public constructor. Wikipedia has a pretty good rundown of JavaBeans: http://en.wikipedia.org/wiki/JavaBeans
POJO is usually used to describe a class that doesn't need to be a subclass of anything, or implement specific interfaces, or follow a specific pattern.
You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields
In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.
The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.
This is working for me:
from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
Then in your model class, you would use it like this (field being the module where you put the above code):
size = fields.IntegerRangeField(min_value=1, max_value=50)
OR for a range of negative and positive (like an oscillator range):
size = fields.IntegerRangeField(min_value=-100, max_value=100)
What would be really cool is if it could be called with the range operator like this:
size = fields.IntegerRangeField(range(1, 50))
But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...
You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.
Out of curiosity, I wanted to see how Value
performed against Value2
. After about 12 trials of similar processes, I could not see any significant differences in speed so I would always recommend using Value
. I used the below code to run some tests with various ranges.
If anyone sees anything contrary regarding performance, please post.
Sub Trial_RUN()
For t = 0 To 5
TestValueMethod (True)
TestValueMethod (False)
Next t
End Sub
Sub TestValueMethod(useValue2 As Boolean)
Dim beginTime As Date, aCell As Range, rngAddress As String, ResultsColumn As Long
ResultsColumn = 5
'have some values in your RngAddress. in my case i put =Rand() in the cells, and then set to values
rngAddress = "A2:A399999" 'I changed this around on my sets.
With ThisWorkbook.Sheets(1)
.Range(rngAddress).Offset(0, 1).ClearContents
beginTime = Now
For Each aCell In .Range(rngAddress).Cells
If useValue2 Then
aCell.Offset(0, 1).Value2 = aCell.Value2 + aCell.Offset(-1, 1).Value2
Else
aCell.Offset(0, 1).Value = aCell.Value + aCell.Offset(-1, 1).Value
End If
Next aCell
Dim Answer As String
If useValue2 Then Answer = " using Value2"
.Cells(Rows.Count, ResultsColumn).End(xlUp).Offset(1, 0) = DateDiff("S", beginTime, Now) & _
" seconds. For " & .Range(rngAddress).Cells.Count & " cells, at " & Now & Answer
End With
End Sub
Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.
if (DetailTable != null && DetailTable.Rows.Count>0)
Several of the answers above will work around the lack of a direct reference to a specific row, but will not work if changes occur to the other rows in a table. That is my criteria for which answers fall technically short.
A common use of Oracle's ROWID is to provide a (somewhat) stable method of selecting rows and later returning to the row to process it (e.g., to UPDATE it). The method of finding a row (complex joins, full-text searching, or browsing row-by-row and applying procedural tests against the data) may not be easily or safely re-used to qualify the UPDATE statement.
The SQL Server RID seems to provide the same functionality, but does not provide the same performance. That is the only issue I see, and unfortunately the purpose of retaining a ROWID is to avoid repeating an expensive operation to find the row in, say, a very large table. Nonetheless, performance for many cases is acceptable. If Microsoft adjusts the optimizer in a future release, the performance issue could be addressed.
It is also possible to simply use FOR UPDATE and keep the CURSOR open in a procedural program. However, this could prove expensive in large or complex batch processing.
Caveat: Even Oracle's ROWID would not be stable if the DBA, between the SELECT and the UPDATE, for example, were to rebuild the database, because it is the physical row identifier. So the ROWID device should only be used within a well-scoped task.
In ES6 use:
import path from 'path';
const __dirname = path.resolve();
also available when node is called with --experimental-modules
Here is another approach.
class orbisius_custom_string {
/**
* The reverse of nl2br. Handles <br/> <br/> <br />
* usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
* @param str $buff
* @return str
* @author Slavi Marinov | http://orbisius.com
*/
public static function br2nl($buff = '') {
$buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
$buff = trim($buff);
return $buff;
}
}
Well this is the MSDN page that deals with IntPtr
.
The first line reads:
A platform-specific type that is used to represent a pointer or a handle.
As to what a pointer or handle is the page goes on to state:
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
A pointer is a reference to an area of memory that holds some data you are interested in.
A handle can be an identifier for an object and is passed between methods/classes when both sides need to access that object.
Once you opened the mongo CLI, connected and authorized on the right database.
The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:
db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})
You can do this with PowerShell:
$process = Start-Process "javaw" "-jar start.jar" -PassThru
taskkill /pid $process.Id
The taskkill
command will graceful close the application.
A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:
$ curl -I https://atmosphere.meteor.com HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive
However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.
<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script>
If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.
And using fork to date
command implie delay, there is a simple and more efficient way using pure bash built-in:
printf -v tznow '%(%z %s)T' -1
TZ=${tznow% *} printf -v yesterday '%(%Y-%m-%d)T' $(( ${tznow#* } - 86400 ))
echo $yesterday
This is a lot quicker on more system friendly than having to fork to date
.
From bash V>=5.0, there is a new variable $EPOCHSECONDS
printf -v tz '%(%z)T' -1
TZ=$tz printf -v yesterday '%(%Y-%m-%d)T' $(( EPOCHSECONDS - 86400 ))
echo $yesterday
If you are migrating to 1.0.0 you need to change the following properties.
In the Project's build.gradle file you need to replace minifyEnabled.
Hence your new build type should be
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Also make sure that gradle version is 1.0.0 like
classpath 'com.android.tools.build:gradle:1.0.0'
in the build.gradle file.
This should solve the problem.
Source: http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0
I tried changing /etc/environment
:
JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
on the slave node, it works.
Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/
Have you enabled 'unknown sources' from security and restrictions settings?
To retrieve text of an auto generated span value just do this :
var al = $("#id-span-name").text();
alert(al);
I came up with a solution similar to Christians but without depending on the Community MSBuild tasks, this is not an option for me as I do not want to install these tasks for all of our developers.
I am generating code and compiling to an Assembly and want to auto-increment version numbers. However, I can not use the VS 6.0.* AssemblyVersion trick as it auto-increments build numbers each day and breaks compatibility with Assemblies that use an older build number. Instead, I want to have a hard-coded AssemblyVersion but an auto-incrementing AssemblyFileVersion. I've accomplished this by specifying AssemblyVersion in the AssemblyInfo.cs and generating a VersionInfo.cs in MSBuild like this,
<PropertyGroup>
<Year>$([System.DateTime]::Now.ToString("yy"))</Year>
<Month>$([System.DateTime]::Now.ToString("MM"))</Month>
<Date>$([System.DateTime]::Now.ToString("dd"))</Date>
<Time>$([System.DateTime]::Now.ToString("HHmm"))</Time>
<AssemblyFileVersionAttribute>[assembly:System.Reflection.AssemblyFileVersion("$(Year).$(Month).$(Date).$(Time)")]</AssemblyFileVersionAttribute>
</PropertyGroup>
<Target Name="BeforeBuild">
<WriteLinesToFile File="Properties\VersionInfo.cs" Lines="$(AssemblyFileVersionAttribute)" Overwrite="true">
</WriteLinesToFile>
</Target>
This will generate a VersionInfo.cs file with an Assembly attribute for AssemblyFileVersion where the version follows the schema of YY.MM.DD.TTTT with the build date. You must include this file in your project and build with it.
Added for reference to future people who find this via google: You might want to look at the {% overextend %} tag provided by the mezzanine library for cases like this.
Rather than preg_replace
, you could always use PHP's filter functions using the filter_var()
function with FILTER_SANITIZE_STRING
.
public int getReverseNumber(int number)
{
int reminder = 0, result = 0;
while (number !=0)
{
if (number >= 10 || number <= -10)
{
reminder = number % 10;
result = result + reminder;
result = result * 10;
number = number / 10;
}
else
{
result = result + number;
number /= 10;
}
}
return result;
}
// The above code will work for negative numbers also
raw_input()
takes exactly what the user typed and passes it back as a string.
input()
first takes the raw_input()
and then performs an eval()
on it as well.
The main difference is that input()
expects a syntactically correct python statement where raw_input()
does not.
raw_input()
was renamed to input()
so now input()
returns the exact string.input()
was removed. If you want to use the old input()
, meaning you need to evaluate a user input as a python statement, you have to do it manually by using eval(input())
.
Using the function above, you would do:
var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);
Of course, the following would also work:
var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];
since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object)
would also get you all its functions, etc., but that might be enough depending on your needs.
Just declare the variable at class or script scope, then access it from inside your methods or closures. Without an example, it's hard to be more specific for your particular problem though.
However, global variables are generally considered bad form.
Why not return the variable from one function, then pass it into the next?
I've concluded this is some kind of Visual Studio bug. Perhaps C Johnson is right - perhaps the build process keeps the file locked.
I do have a workaround which works - each time this happens - I change the Target Name of the executable under the Project's properties (right click the project, then Properties\Configuration Properties\General\Target Name).
In this fashion VS creates a new executable and the problem is worked around. Every few times I do this I return to the original name, thus cycling through ~3 names.
If someone will find the reason for this and a solution, please do answer and I may move the answer to yours, as mine is a workaround.
Select lines which you want to Comment
Then press Ctrl + / to make selected lines comment
And to uncomment:
Select the commented lines you which want to uncomment
First press Ctrl + K then Ctrl + Uto make commented lines uncomment
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])
Generally it means:
127 - command not found
but it can also mean that the command is found,
but a library that is required by the command is NOT found.
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
<url-pattern>/*</url-pattern>
The /*
on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /*
on a Filter
only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter()
.
<url-pattern>/</url-pattern>
The /
doesn't override any other servlet. It only replaces the servletcontainer's builtin default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's builtin default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's builtin JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp
.
<url-pattern></url-pattern>
Then there's also the empty string URL pattern
. This will be invoked when the context root is requested. This is different from the <welcome-file>
approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern
and the slash URL pattern /
be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.
In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html
, *.do
, /pages/*
, /app/*
, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*
, /static/*
, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a builtin static resource servlet, so that's why you could map its front controller on /
if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?
In my case I was committing transaction when persist method was used. On changing persist to save method , it got resolved.
Use
GROUP BY year, month DESC";
Instead of
GROUP BY MONTH(t.summaryDateTime) DESC";
For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.
This will stash all changes in {0}
key and instantly drop it from {0}
git stash && git stash drop
This solution seems not working for me.
select {
border: 0px;
outline: 0px;
}
But you may set select
border to the background color of the container and it will work.
Remove conn.commit from Register.java
In your jsp change action to :<form name="registrationform" action="Register" method="post">
Why use another markup language? (I Agree with @c z above).
One goal of Markdown is to make the documents readable even in a plain text editor.
The code
Sample code
5th position in an really ugly code
5th position in a clear an readable code
Again using non-breaking spaces :)
The result
Sample code
5th position in an really ugly code
5th position in a clear an readable code
Again using non-breaking spaces :)
The visual representation of a non-breaking space (or hard space) is usually a normal space " ", however, its Unicode representation is U+00A0.
The Unicode representation of the ordinary space is U+0020 (32 in the ASCII Table).
Thus, text processors may behave differently while the visual representation remains the same.
| OS | Input method |
|===========| ==================================|
| macOS | OPTION+SPACE (ALT+SPACE) |
| Linux | Compose Space Space or AltGr+Space|
| Windows | Alt+0+1+6+0 |
Some text editor use Ctrl+Shift+Space.
Some text editors can convert hard spaces to common spaces in copying and pasting operations, so be careful.
The easiest way according to me will be using SDWebImage
Add this to your pod file
pod 'SDWebImage', '~> 4.0'
Run pod install
Now import SDWebImage
import SDWebImage
Now for setting image from url
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage
The location of the Temporary Internet Files
folder depends on your version of Windows and whether or not you are using user profiles.
If you have Windows Vista, then temporary Internet files are in these locations (note that on your PC they can be on some drive other than C):
C:\Users[username]\AppData\Local\Microsoft\Windows\Temporary Internet Files\ C:\Users[username]\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\
Note that you will have to change the settings of Windows Explorer to show all kinds of files (including the protected system files) in order to access these folders.
If you have Windows XP or Windows 2000, then temporary Internet files are in this location (note that on your PC they can be on some drive other than C):
C:\Documents and Settings[username]\Local Settings\Temporary Internet Files\
If you have only one user account, then replace [username] with Administrator to get the path of the Temporary Internet Files
folder.
If you have Windows Me, Windows 98, Windows NT or Windows 95, then index.dat
files are in these locations:
C:\Windows\Temporary Internet Files\
C:\Windows\Profiles[username]\Temporary Internet Files\
Note that on your computer, the Windows directory may not be C:\Windows
but some other directory. If you don't have a Profiles
directory in your Windows
directory, don't worry — this just means that you are not using user profiles.
Based on vSync's answer, the pure javascript method is lightning fast for large amount of objects. Here is the Fiddle: https://jsfiddle.net/xeyq2d5r/8/
[1]: https://jsfiddle.net/xeyq2d5r/8/ "JSFiddle"
I received favorable tests for the 3rd method proposed, that uses the native javascript vs HTML Canvas
Google was pretty competive for option 1 and 3, 2 bombed.
FireFox 48:
Method 1 took 938.895 milliseconds.
Method 2 took 1536.355 milliseconds.
Method 3 took 135.91499999999996 milliseconds.
Edge 11
Method 1 took 4895.262839793865 milliseconds.
Method 2 took 6746.622271896686 milliseconds.
Method 3 took 1020.0315412885484 milliseconds.
Google Chrome: 52
Method 1 took 336.4399999999998 milliseconds.
Method 2 took 2271.71 milliseconds.
Method 3 took 333.30499999999984 milliseconds.
This issue occurred after Visual Studio 2012 installation. The issue resolved by replacing the cvtres.exe from VS2010 with the one from VS2012.
Thank you to "social.msdn"!
Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.
@Throws(IOException::class)
fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
.also {
if (!it.exists()) {
it.outputStream().use { cache ->
context.assets.open(fileName).use { inputStream ->
inputStream.copyTo(cache)
}
}
}
}
Get the path to the file like:
val filePath = getFileFromAssets(context, "fileName.extension").absolutePath
It's easy
// MARK: - Gradient
extension CAGradientLayer {
enum Point {
case topLeft
case centerLeft
case bottomLeft
case topCenter
case center
case bottomCenter
case topRight
case centerRight
case bottomRight
var point: CGPoint {
switch self {
case .topLeft:
return CGPoint(x: 0, y: 0)
case .centerLeft:
return CGPoint(x: 0, y: 0.5)
case .bottomLeft:
return CGPoint(x: 0, y: 1.0)
case .topCenter:
return CGPoint(x: 0.5, y: 0)
case .center:
return CGPoint(x: 0.5, y: 0.5)
case .bottomCenter:
return CGPoint(x: 0.5, y: 1.0)
case .topRight:
return CGPoint(x: 1.0, y: 0.0)
case .centerRight:
return CGPoint(x: 1.0, y: 0.5)
case .bottomRight:
return CGPoint(x: 1.0, y: 1.0)
}
}
}
convenience init(start: Point, end: Point, colors: [CGColor], type: CAGradientLayerType) {
self.init()
self.startPoint = start.point
self.endPoint = end.point
self.colors = colors
self.locations = (0..<colors.count).map(NSNumber.init)
self.type = type
}
}
Use like this:-
let fistColor = UIColor.white
let lastColor = UIColor.black
let gradient = CAGradientLayer(start: .topLeft, end: .topRight, colors: [fistColor.cgColor, lastColor.cgColor], type: .radial)
gradient.frame = yourView.bounds
yourView.layer.addSublayer(gradient)
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
not equals
. See here for a list of conditions
What's probably happening is that React thinks that only one MyInput
(unemployment-duration
) is added between the renders. As such, the job-title
never gets replaced with the unemployment-reason
, which is also why the predefined values are swapped.
When React does the diff, it will determine which components are new and which are old based on their key
property. If no such key is provided in the code, it will generate its own.
The reason why the last code snippet you provide works is because React essentially needs to change the hierarchy of all elements under the parent div
and I believe that would trigger a re-render of all children (which is why it works). Had you added the span
to the bottom instead of the top, the hierarchy of the preceding elements wouldn't change, and those element's wouldn't re-render (and the problem would persist).
Here's what the official React documentation says:
The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a key.
When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
You should be able to fix this by providing a unique key
element yourself to either the parent div
or to all MyInput
elements.
For example:
render(){
if (this.state.employed) {
return (
<div key="employed">
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div key="notEmployed">
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
OR
render(){
if (this.state.employed) {
return (
<div>
<MyInput key="title" ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<MyInput key="reason" ref="unemployment-reason" name="unemployment-reason" />
<MyInput key="duration" ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
Now, when React does the diff, it will see that the divs
are different and will re-render it including all of its' children (1st example). In the 2nd example, the diff will be a success on job-title
and unemployment-reason
since they now have different keys.
You can of course use any keys you want, as long as they are unique.
Update August 2017
For a better insight into how keys work in React, I strongly recommend reading my answer to Understanding unique keys in React.js.
Update November 2017
This update should've been posted a while ago, but using string literals in ref
is now deprecated. For example ref="job-title"
should now instead be ref={(el) => this.jobTitleRef = el}
(for example). See my answer to Deprecation warning using this.refs for more info.
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to #abc
the following css:
display:flex;
align-items:center;
Original question demo updated
Simple Example:
.vertical-align-content {_x000D_
background-color:#f18c16;_x000D_
height:150px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
/* Uncomment next line to get horizontal align also */_x000D_
/* justify-content:center; */_x000D_
}
_x000D_
<div class="vertical-align-content">_x000D_
Hodor!_x000D_
</div>
_x000D_
Call back vs Callback Function
A Callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.
What is a Callback Function?
otherFunction
) as a parameter, and the callback function is called (or executed) inside the otherFunction
. function action(x, y, callback) {
return callback(x, y);
}
function multiplication(x, y) {
return x * y;
}
function addition(x, y) {
return x + y;
}
alert(action(10, 10, multiplication)); // output: 100
alert(action(10, 10, addition)); // output: 20
In SOA, callback allows the Plugin Modules to access services from the container/environment.
The correct API to use is UIView systemLayoutSizeFittingSize:
, passing either UILayoutFittingCompressedSize
or UILayoutFittingExpandedSize
.
For a normal UIView
using autolayout this should just work as long as your constraints are correct. If you want to use it on a UITableViewCell
(to determine row height for example) then you should call it against your cell contentView
and grab the height.
Further considerations exist if you have one or more UILabel's in your view that are multiline. For these it is imperitive that the preferredMaxLayoutWidth
property be set correctly such that the label provides a correct intrinsicContentSize
, which will be used in systemLayoutSizeFittingSize's
calculation.
EDIT: by request, adding example of height calculation for a table view cell
Using autolayout for table-cell height calculation isn't super efficient but it sure is convenient, especially if you have a cell that has a complex layout.
As I said above, if you're using a multiline UILabel
it's imperative to sync the preferredMaxLayoutWidth
to the label width. I use a custom UILabel
subclass to do this:
@implementation TSLabel
- (void) layoutSubviews
{
[super layoutSubviews];
if ( self.numberOfLines == 0 )
{
if ( self.preferredMaxLayoutWidth != self.frame.size.width )
{
self.preferredMaxLayoutWidth = self.frame.size.width;
[self setNeedsUpdateConstraints];
}
}
}
- (CGSize) intrinsicContentSize
{
CGSize s = [super intrinsicContentSize];
if ( self.numberOfLines == 0 )
{
// found out that sometimes intrinsicContentSize is 1pt too short!
s.height += 1;
}
return s;
}
@end
Here's a contrived UITableViewController subclass demonstrating heightForRowAtIndexPath:
#import "TSTableViewController.h"
#import "TSTableViewCell.h"
@implementation TSTableViewController
- (NSString*) cellText
{
return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}
#pragma mark - Table view data source
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
return 1;
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
return 1;
}
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
static TSTableViewCell *sizingCell;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
});
// configure the cell
sizingCell.text = self.cellText;
// force layout
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
// get the fitting size
CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));
return s.height;
}
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];
cell.text = self.cellText;
return cell;
}
@end
A simple custom cell:
#import "TSTableViewCell.h"
#import "TSLabel.h"
@implementation TSTableViewCell
{
IBOutlet TSLabel* _label;
}
- (void) setText: (NSString *) text
{
_label.text = text;
}
@end
And, here's a picture of the constraints defined in the Storyboard. Note that there are no height/width constraints on the label - those are inferred from the label's intrinsicContentSize
:
Try it the other way:
var start_date = $("#fit_start_time").val(); //05-09-2013
var end_date = $("#fit_end_time").val(); //10-09-2013
var format='dd-MM-y';
var result= compareDates(start_date,format,end_date,format);
if(result==1)/// end date is less than start date
{
alert('End date should be greater than Start date');
}
OR:
if(new Date(start_date) >= new Date(end_date))
{
alert('End date should be greater than Start date');
}
There are lots of different things about static and dynamic languages. For me, the main difference is that in dynamic languages the variables don't have fixed types; instead, the types are tied to values. Because of this, the exact code that gets executed is undetermined until runtime.
In early or naïve implementations this is a huge performance drag, but modern JITs get tantalizingly close to the best you can get with optimizing static compilers. (in some fringe cases, even better than that).
Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.
With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:
width: calc(100% - 200px);
Would work as expected with the strict math option enabled.
However, note that Strict Math is applied globally, not only inside calc()
. That means, if you have:
font-size: 12px + 2px;
The math will no longer be processed by Less -- it will output font-size: 12px + 2px
which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:
font-size: (12px + 2px);
Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.
It only works for three-digit numbers, but it works
a = int(input())
print(a // 100 + a // 10 % 10 + a % 10)
In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:
const tampax = require('tampax');
const yamlString = `
dude:
name: Arthur
weapon:
favorite: Excalibur
useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;
const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);
// output : "Arthur use Excalibur. The goal is to kill Mordred."
Editor's Note: poster is also the author of this package.
The Android Asset Packaging Tool (aapt
) has become very strict in its latest release and is now used for all Android versions. The aapt-error you're getting is generated because it no longer allows non-positional format specifiers.
Here are a few ideas how you can include the %-symbol in your resource strings.
If you don't need any format specifiers or substitutions in your string you can simply make use of the formatted
attribute and set it to false
:
<string formatted="false">%a + %a == 2%a</string>
In this case the string is not used as a format string for the Formatter
so you don't have to escape your %-symbols. The resulting string is "%a + %a == 2%a".
If you omit the formatted="false"
attribute, the string is used as a format string and you have to escape the %-symbols. This is correctly done with double-%:
<string>%%a + %%a == 2%%a</string>
Now aapt
gives you no errors but depending on how you use it, the resulting string can be "%%a + %%a == 2%%a" if a Formatter
is invoked without any format arguments:
Resources res = context.getResources();
String s1 = res.getString(R.string.str);
// s1 == "%%a + %%a == 2%%a"
String s2 = res.getString(R.string.str, null);
// s2 == "%a + %a == 2%a"
Without any xml and code it is difficult to say what exactly your problem is but hopefully this helps you understand the mechanisms a little better.
First add the collections and then apply lookup on these collections. Don't use $unwind
as unwind will simply separate all the documents of each collections. So apply simple lookup and then use $project
for projection.
Here is mongoDB query:
db.userInfo.aggregate([
{
$lookup: {
from: "userRole",
localField: "userId",
foreignField: "userId",
as: "userRole"
}
},
{
$lookup: {
from: "userInfo",
localField: "userId",
foreignField: "userId",
as: "userInfo"
}
},
{$project: {
"_id":0,
"userRole._id":0,
"userInfo._id":0
}
} ])
Here is the output:
/* 1 */ {
"userId" : "AD",
"phone" : "0000000000",
"userRole" : [
{
"userId" : "AD",
"role" : "admin"
}
],
"userInfo" : [
{
"userId" : "AD",
"phone" : "0000000000"
}
] }
Thanks.
The best safe way is: <%= sanitize @x %>
It will avoid XSS!
1) Put =Left(E1,5)
in F1
2) Copy F1
, then select entire F
column and paste.
If your cron job is running on Mac OS X only, you may want to use launchd instead.
From Scheduling Timed Jobs (official Apple docs):
Note: Although it is still supported, cron is not a recommended solution. It has been deprecated in favor of launchd.
You can find additional information (such as the launchd Wikipedia page) with a simple web search.
In intellij click .xsd file -> WebServices ->Generate Java code from Xml Schema JAXB then give package path and package name ->ok
If you are just looking for a lightweight way to save some or all of your current working copy changes and then reapply them later at will, consider a patch file:
# save your working copy changes
git diff > some.patch
# re-apply it later
git apply some.patch
Every now and then I wonder if I should be using stashes for this and then I see things like the insanity above and I'm content with what I'm doing :)
Ruby is v2.0 now. Programs like Jekyll (and I am sure many others) require it. I just ran:
sudo apt-get install ruby2.0
check version
ruby --version
Hope that helps
Window > Show view > Server
or right click on the server in "Servers" view, select "Properties".You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.
The answers are partially correct because @@ is actually a class variable which is per class hierarchy meaning it is shared by a class, its instances and its descendant classes and their instances.
class Person
@@people = []
def initialize
@@people << self
end
def self.people
@@people
end
end
class Student < Person
end
class Graduate < Student
end
Person.new
Student.new
puts Graduate.people
This will output
#<Person:0x007fa70fa24870>
#<Student:0x007fa70fa24848>
So there is only one same @@variable for Person, Student and Graduate classes and all class and instance methods of these classes refer to the same variable.
There is another way of defining a class variable which is defined on a class object (Remember that each class is actually an instance of something which is actually the Class class but it is another story). You use @ notation instead of @@ but you can't access these variables from instance methods. You need to have class method wrappers.
class Person
def initialize
self.class.add_person self
end
def self.people
@people
end
def self.add_person instance
@people ||= []
@people << instance
end
end
class Student < Person
end
class Graduate < Student
end
Person.new
Person.new
Student.new
Student.new
Graduate.new
Graduate.new
puts Student.people.join(",")
puts Person.people.join(",")
puts Graduate.people.join(",")
Here, @people is single per class instead of class hierarchy because it is actually a variable stored on each class instance. This is the output:
#<Student:0x007f8e9d2267e8>,#<Student:0x007f8e9d21ff38>
#<Person:0x007f8e9d226158>,#<Person:0x007f8e9d226608>
#<Graduate:0x007f8e9d21fec0>,#<Graduate:0x007f8e9d21fdf8>
One important difference is that, you cannot access these class variables (or class instance variables you can say) directly from instance methods because @people in an instance method would refer to an instance variable of that specific instance of the Person or Student or Graduate classes.
So while other answers correctly state that @myvariable (with single @ notation) is always an instance variable, it doesn't necessarily mean that it is not a single shared variable for all instances of that class.
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS
$(document).ready(function(){
$("#a").mouseover(function(){
$("#b").css("background-color", "red");
});
});