In Python/Spark we can do:
def quiet_logs( sc ):
logger = sc._jvm.org.apache.log4j
logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )
The after defining Sparkcontaxt 'sc' call this function by : quiet_logs( sc )
This may be due to how Spark computes its classpath. My hunch is that Hadoop's log4j.properties
file is appearing ahead of Spark's on the classpath, preventing your changes from taking effect.
If you run
SPARK_PRINT_LAUNCH_COMMAND=1 bin/spark-shell
then Spark will print the full classpath used to launch the shell; in my case, I see
Spark Command: /usr/lib/jvm/java/bin/java -cp :::/root/ephemeral-hdfs/conf:/root/spark/conf:/root/spark/lib/spark-assembly-1.0.0-hadoop1.0.4.jar:/root/spark/lib/datanucleus-api-jdo-3.2.1.jar:/root/spark/lib/datanucleus-core-3.2.2.jar:/root/spark/lib/datanucleus-rdbms-3.2.1.jar -XX:MaxPermSize=128m -Djava.library.path=:/root/ephemeral-hdfs/lib/native/ -Xms512m -Xmx512m org.apache.spark.deploy.SparkSubmit spark-shell --class org.apache.spark.repl.Main
where /root/ephemeral-hdfs/conf
is at the head of the classpath.
I've opened an issue [SPARK-2913] to fix this in the next release (I should have a patch out soon).
In the meantime, here's a couple of workarounds:
export SPARK_SUBMIT_CLASSPATH="$FWDIR/conf"
to spark-env.sh
./root/ephemeral-hdfs/conf/log4j.properties
.Man, I had the issue in one of my eclipse projects, amazingly the issue was the order of the jars in my .project file. believe it or not!
Try executing your command with sudo(Super User), this worked for me :)
Run : $ sudo your_command
After than enter the super user password. Thats All..
Modify your log4j.properties
file accordingly:
log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog
Change the log levels for each logger depending to your needs.
Hibernate logging has to be also enabled in hibernate configuration.
Add lines
hibernate.show_sql=true
hibernate.format_sql=true
either to
server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml
or to application's persistence.xml
in <persistence-unit><properties>
tag.
Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.
There is an alternative way of using log4jdbc for any kind of sql logging.
The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.
Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:
<logger category="org.hibernate">
<level name="DEBUG"/>
</logger>
Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.
If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.
Solution based on configuration only, with a ThresoldFilter and LevelFilters to keep things really simple to understand :
<configuration>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<encoder>
<pattern>%date %level [%thread] %logger %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<target>System.out</target>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACE</level>
<onMatch>ACCEPT</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>DENY</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
</filter>
<encoder>
<pattern>%date %level [%thread] %logger %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="STDERR" />
</root>
</configuration>
For me it was very simple solution :
I had to add log4j dependancies in my POM.xml and that resolved unnecessary loggings .
<dependency>_x000D_
<groupId>org.apache.logging.log4j</groupId>_x000D_
<artifactId>log4j-api</artifactId>_x000D_
<version>2.6.1</version>_x000D_
</dependency>_x000D_
<dependency>_x000D_
<groupId>org.apache.logging.log4j</groupId>_x000D_
<artifactId>log4j-core</artifactId>_x000D_
<version>2.6.1</version>_x000D_
</dependency>
_x000D_
I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:
# Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender
Try this:
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);
Note that you can also tell logback to periodically scan your config file like this:
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
Write the root logger as below for logging on both console and FILE
log4j.rootLogger=ERROR,console,FILE
And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).
You probably have a log4j.properties file somewhere in the project. In that file you can configure which level of debug output you want. See this example:
log4j.rootLogger=info, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.logger.com.example=debug
The first line sets the log level for the root logger to "info", i.e. only info, warn, error and fatal will be printed to the console (which is the appender defined a little below that).
The last line sets the logger for com.example.* (if you get your loggers via LogFactory.getLogger(getClass())
) will be at debug level, i.e. debug will also be printed.
Here's the list of logger categories:
Category Function
org.hibernate.SQL Log all SQL DML statements as they are executed
org.hibernate.type Log all JDBC parameters
org.hibernate.tool.hbm2ddl Log all SQL DDL statements as they are executed
org.hibernate.pretty Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache Log all second-level cache activity
org.hibernate.transaction Log transaction related activity
org.hibernate.jdbc Log all JDBC resource acquisition
org.hibernate.hql.ast.AST Log HQL and SQL ASTs during query parsing
org.hibernate.secure Log all JAAS authorization requests
org.hibernate Log everything (a lot of information, but very useful for troubleshooting)
Formatted for pasting into a log4j XML configuration file:
<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />
NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.
And a category is specified as such:
<logger name="org.hibernate">
<level value="ALL" />
<appender-ref ref="FILE"/>
</logger>
It must be placed before the root element.
I fully support @Charles Bretana's answer. However, if it's not working, please make sure that there is only one <section>
element AND that configSections
is the first child of the root element:
configsections
must be the first element in your app.Config
after configuration:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
<!-- add log 4 net config !-->
<!-- add others e.g. <startup> !-->
</configuration>
You can disabled the many of the outputs of hibernate setting this props of hibernate (hb configuration) a false:
hibernate.show_sql
hibernate.generate_statistics
hibernate.use_sql_comments
But if you want to disable all console info you must to set the logger level a NONE of FATAL of class org.hibernate
like Juha say.
I think this is more clear than describing it in words
s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'
I don't know why but for me the solution proposed by Marius Stanescu is breaking the specificity of col (a col-md-3 followed by a col-md-4 will take all of the twelve row)
I found another working solution :
.bottom-column
{
display: inline-block;
vertical-align: middle;
float: none;
}
Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore).
Instead, since in your example tag
is the unique key, use:
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;
on duplicate key produces:
Query OK, 0 rows affected (0.07 sec)
Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
If you want to debug and see the value of the password you just read, use:
write-host $pw
To set timeout on a per page level, you could use this simple code:
Page.Server.ScriptTimeout = 60;
Note: 60 means 60 seconds, this time-out applies only if the debug attribute in the compilation element is False.
try:
Cursor cursor = db.rawQuery("select * from table",null);
AND for List<String>
:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.
Use \Q
to autoescape any potentially problematic characters in your variable.
if($text_to_search =~ m/\Q$search_string/) print "wee";
The usual method when not using float
s is to use display: inline-block
: http://www.jsfiddle.net/zygnz/1/
.container div {
display: inline-block;
}
Do note its limitations though: There is a additional space after the first bloc - this is because the two blocks are now essentially inline
elements, like a
and em
, so whitespace between the two counts. This could break your layout and/or not look nice, and I'd prefer not to strip out all whitespaces between characters for the sake of this working.
Floats are also more flexible, in most cases.
I faced this issue a lot. I am not sure if this is the issue, but I think, when xCode saw that there is an app with the same bundle identifier as of the app, I am trying to install, it didn't allow me. So, I had to delete the older one and attempted to install and it worked. However sometimes for testing purpose, I needed multiple version of the same app and in that case, I would change the bundle identifier and try to install. It only works if, I am using an wildcard provisioning profile.
function distRandom(){
do{
x=random(DISTRIBUTION_DOMAIN);
}while(random(DISTRIBUTION_RANGE)>=distributionFunction(x));
return x;
}
You should have set up the Atreides family (either modern, Dune, or ancient, Oedipus Rex) as a testing case. You don't find bugs by using sanitized data as a test case.
I would say that the consultant is right in the theory, and you are right in practice. As the saying goes:
In theory, theory and practice are the same. In practice, they are not.
The Java spec says that System.gc suggests to call garbage collection. In practice, it just spawns a thread and runs right away on the Sun JVM.
Although in theory you could be messing up some finely tuned JVM implementation of garbage collection, unless you are writing generic code intended to be deployed on any JVM out there, don't worry about it. If it works for you, do it.
<?php
$array["a"] = "Thusitha";
$array["b"] = "Sumanadasa";
$array["c"] = "Lakmal";
$array["d"] = "Nanayakkara";
$str = serialize($array);
$strenc = urlencode($str);
print $str . "\n";
print $strenc . "\n";
?>
print $str . "\n";
gives a:4:{s:1:"a";s:8:"Thusitha";s:1:"b";s:10:"Sumanadasa";s:1:"c";s:6:"Lakmal";s:1:"d";s:11:"Nanayakkara";}
and
print $strenc . "\n";
gives
a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A8%3A%22Thusitha%22%3Bs%3A1%3A%22b%22%3Bs%3A10%3A%22Sumanadasa%22%3Bs%3A1%3A%22c%22%3Bs%3A6%3A%22Lakmal%22%3Bs%3A1%3A%22d%22%3Bs%3A11%3A%22Nanayakkara%22%3B%7D
So if you want to pass this $array
through URL to page_no_2.php
,
ex:-
$url ='http://page_no_2.php?data=".$strenc."';
To return back to the original array, it needs to be urldecode()
, then unserialize()
, like this in page_no_2.php:
<?php
$strenc2= $_GET['data'];
$arr = unserialize(urldecode($strenc2));
var_dump($arr);
?>
gives
array(4) {
["a"]=>
string(8) "Thusitha"
["b"]=>
string(10) "Sumanadasa"
["c"]=>
string(6) "Lakmal"
["d"]=>
string(11) "Nanayakkara"
}
again :D
Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.
The best way is not to write any initializing statements. This is because if you write
int a[]=new int[3]
then by default, in Java all the values of array i.e. a[0]
, a[1]
and a[2]
are initialized to 0
! Regarding the local variable hiding a field, post your entire code for us to come to conclusion.
Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:
> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35,
times = 10), rep(45, times = 4)))
$cp
mean s.d. skewness
41.46228 12.47892 0.99527
This probably works better on data that is more skew-normal:
Use NETSTAT on the command-line:
netstat util
This error appear because the compiler could not found "my-upload-key.keystore" file in your project
After you have generated the file you need to paste it into project's andorid/app folder
this worked for me!
Try this:
function welcomeMessage() { var shape1 = new Shape(); //alert(shape1.draw()); alert(shape1.hasOwnProperty("name")); }
When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:
for(i in obj) { ... }
The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:
for(i in obj) { alert("The value of obj." + i + " = " + obj[i]); }
If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:
>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3]))
Take a look Code Like a Pythonista: Idiomatic Python.
Preconditions: adb and wireshark are installed on your computer and you have a rooted android device.
adb push ~/Downloads/tcpdump /sdcard/
adb shell
su root
mv /sdcard/tcpdump /data/local/
cd /data/local/
chmod +x tcpdump
./tcpdump -vv -i any -s 0 -w /sdcard/dump.pcap
Ctrl+C
once you've captured enough data.exit
exit
adb pull /sdcard/dump.pcap ~/Downloads/
Now you can open the pcap file using Wireshark.
As for your question about monitoring specific processes, find the bundle id of your app, let's call it com.android.myapp
ps | grep com.android.myapp
/data/local
using the same way you did for tcpdump
above. cd /data/local
./strace -p 1234 -f -e trace=network -o /sdcard/strace.txt
Now you can look at strace.txt for ip addresses, and filter your wireshark log for those IPs.
for (int i = 0; i < buffer.length; i++)
{
a = (a << 8) | buffer[i];
if (i % 3 == 0)
{
//a is ready
a = 0;
}
}
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
Use the splice method.
ArrayName.splice(indexValueOfArray,1);
This removes 1
item from the array starting at indexValueOfArray
.
I've done something similar with extension methods. Here's my code:
public static class DataExtensions
{
/// <summary>
/// Gets the value.
/// </summary>
/// <typeparam name="T">The type of the data stored in the record</typeparam>
/// <param name="record">The record.</param>
/// <param name="columnName">Name of the column.</param>
/// <returns></returns>
public static T GetColumnValue<T>(this IDataRecord record, string columnName)
{
return GetColumnValue<T>(record, columnName, default(T));
}
/// <summary>
/// Gets the value.
/// </summary>
/// <typeparam name="T">The type of the data stored in the record</typeparam>
/// <param name="record">The record.</param>
/// <param name="columnName">Name of the column.</param>
/// <param name="defaultValue">The value to return if the column contains a <value>DBNull.Value</value> value.</param>
/// <returns></returns>
public static T GetColumnValue<T>(this IDataRecord record, string columnName, T defaultValue)
{
object value = record[columnName];
if (value == null || value == DBNull.Value)
{
return defaultValue;
}
else
{
return (T)value;
}
}
}
To use it, you would do something like
int number = record.GetColumnValue<int>("Number",0)
Using interpolation string & format specifier:
var filename = $"{DateTime.Now:yyyy.dd.M HH-mm-ss}"
Example Output for January 1st, 2020 at 10:40:45AM:
2020.28.01 10-40-45
Or if you want a standard date format:
var filename = $"{DateTime.Now:yyyy.M.dd HH-mm-ss}"
2020.01.28 10-40-45
Note: this feature is available in C# 6 and later versions of the language.
- mvn install
You can write code below in command line or if you're using eclipse builtin maven right click on project -> Run As -> run configurations... -> in left panel right click on Maven Build -> new configuration -> write the code in Goals & in base directory :${project_loc:NameOfYourProject} -> Run
mvn install:install-file
-Dfile=<path-to-file>
-DgroupId=<group-id>
-DartifactId=<artifact-id>
-Dversion=<version>
-Dpackaging=<packaging>
-DgeneratePom=true
Where each refers to:
< path-to-file >: the path to the file to load e.g -> c:\kaptcha-2.3.jar
< group-id >: the group that the file should be registered under e.g -> com.google.code
< artifact-id >: the artifact name for the file e.g -> kaptcha
< version >: the version of the file e.g -> 2.3
< packaging >: the packaging of the file e.g. -> jar
2.After installed, just declares jar in pom.xml.
<dependency>
<groupId>com.google.code</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3</version>
</dependency>
Look there is a far easier solution to your problem:
ImageView imageView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
imageView =(ImageView)findViewById(R.id.your_imageView);
Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_image);
Point screenSize = new Point();
getWindowManager().getDefaultDisplay().getSize(screenSize);
Bitmap temp = Bitmap.createBitmap(screenSize.x, screenSize.x, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(temp);
canvas.drawBitmap(imageBitmap,null, new Rect(0,0,screenSize.x,screenSize.x), null);
imageView.setImageBitmap(temp);
}
First stop IIS from startmenu by typing IIS manager,
Edit c:/wamp/wampmanager.tpl
file so the WAMP menu points to localhost:80
.
Find http://localhost
and change it to htttp://localhost:80
also, if you think something else has already grabbed port 80, that is why its not working..,then,
Run
wampmanager->Apache->Service->Test port 80
This will launch a command window and tell you what is using port 80.
Whatever it is, will need to be re-configured to use another port or for example if its IIS and you dont use IIS it should be un-installed.
Further you can use 'net stop'
command to stop desired service.
Although jQuery Maphilight plugin does the job, it relies on the outdated verbose imagemap in your html. I would prefer to keep the mapcoordinates external. This could be as JS with the jquery imagemap plugin but it lacks hover states. A nice solution is googles geomap visualisation in flash and JS. But the opensource future for this kind of vectordata however is svg, considering svg support accross all modern browsers, and googles svgweb for a flash convert for IE, why not a jquery plugin to add links and hoverstates to a svg map, like the JS demo here? That way you also avoid the complex step of transforming a vectormap to a imagemap coordinates.
select controls are still clickable even on readonly attrib
if you want to still disable the control but you want its value posted. You might consider creating a hidden field. with the same value as your control.
then create a jquery, on select change
$('#your_select_id').change(function () {
$('#your_hidden_selectid').val($('#your_select_id').val());
});
It's hard to answer you without the HTML, but in general you can put:
style="width: 50%;"
On either the table cell, or place a div inside the table cell, and put the style on that.
But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.
Post a copy of your HTML and maybe you'll get a better answer.
I'm going to add my 2 cents in case someone finds himself in a position like mine. I too was looking for an MVC project type and could not see it. All I saw is a "Web Application Project". So I freaked out and rushed into trying all solutions listed on this page.
But.
IT IS ACTUALLY THERE.
Just go with the "Web application" project and it will give you the MVC option on the next step.
$("li").click(function(){
alert($(this).attr("class"));
});
Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:
// say this is some existing structure. And we want to use
// a list. We can tell it that the next pointer
// is apple::next.
struct apple {
int data;
apple * next;
};
// simple example of a minimal intrusive list. Could specify the
// member pointer as template argument too, if we wanted:
// template<typename E, E *E::*next_ptr>
template<typename E>
struct List {
List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }
void add(E &e) {
// access its next pointer by the member pointer
e.*next_ptr = head;
head = &e;
}
E * head;
E *E::*next_ptr;
};
int main() {
List<apple> lst(&apple::next);
apple a;
lst.add(a);
}
Here's also nice way to achieve this via UI.
0) Right click on PowerShell icon when on task bar
1) Shift + right click on Windows PowerShell
2) "Run as different user"
I spent a good amount of time trying to work this out today, and couldn't get things working using line-height or vertical-align. The easiest solution I was able to find was to set the <a/> to be relatively positioned so it would contain absolutes, and the :after to be positioned absolutely taking it out of the flow.
a{
position:relative;
padding-right:18px;
}
a:after{
position:absolute;
content:url(image.png);
}
The after image seemed to automatically center in that case, at least under Firefox/Chrome. Such may be a bit sloppier for browsers not supporting :after, due to the excess spacing on the <a/>.
To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.
public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
public void Add(Tkey key, TValue value){
base.Add(new KeyValuePair<Tkey, TValue>(key, value));
}
}
What this means is that the constructor can be initialized with better syntax::
var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};
I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.
If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple
is a class not a struct like KeyValuePair
this is an interesting distinction).
Curiously enough, the initializer list syntax is available on any IEnumerable
and it allows you to use any Add
method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[]
member as a params object[]
member.
In my case I received this error when I misspelled the module name of the library (dependency) in build.gradle
file.
So remember to check if the name of the module is correct.
build.gradle
dependencies {
compile project(':module-name-of-the-library')
}
Try this code it display current date and time
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa",
Locale.ENGLISH);
String var = dateFormat.format(date));
set newVarNoSpaces=%someVarWithSpaces: =%
I know, I am a little late to the party ... what happen a lot, you just use default settings in your app pool in IIS. In IIS Administration utility, go to app pools->select pool-->advanced settings->Process Model/Identity
and select a user identity which has right permissions. By default it is set to ApplicationPoolIdentity
. If you're developer, you most likely admin on your machine, so you can select your account to run app pool. On the deployment servers, let admins to deal with it.
Here is a filter that will take a date string OR javascript Date() object. It uses Moment.js and can apply any Moment.js transform function, such as the popular 'fromNow'
angular.module('myModule').filter('moment', function () {
return function (input, momentFn /*, param1, param2, ...param n */) {
var args = Array.prototype.slice.call(arguments, 2),
momentObj = moment(input);
return momentObj[momentFn].apply(momentObj, args);
};
});
So...
{{ anyDateObjectOrString | moment: 'format': 'MMM DD, YYYY' }}
would display Nov 11, 2014
{{ anyDateObjectOrString | moment: 'fromNow' }}
would display 10 minutes ago
If you need to call multiple moment functions, you can chain them. This converts to UTC and then formats...
{{ someDate | moment: 'utc' | moment: 'format': 'MMM DD, YYYY' }}
There are two times when you can update a record through a view:
Generally, you should not rely on being able to perform an insert to a view unless you have specifically written an INSTEAD OF trigger for it. Be aware, there are also INSTEAD OF UPDATE triggers that can be written as well to help perform updates.
Lookarounds can be nested.
So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".
Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"
<option data-divider="true" disabled>______________</option>
you can do this one also. it is easy and make divider select drop down list.
it's the same as think the next:
"starting with i = 0, while i is less than 8, and adding one to i at the end of the parenthesis, do the instructions between brackets"
It's also the same as:
while( i < 8 )
{
// instrucctions like:
Console.WriteLine(i);
i++;
}
the For sentences is a basis of coding, and it's as useful as necessary its understanding.
It's the way to repeat n-times the same instrucction, or browse ( or do something with each element) an array
My definitive solution on Eclipse Luna and m2eclipse: Custom Classloader (download and add to your project, 5 classes only) :http://git.eclipse.org/c/jdt/eclipse.jdt.ui.git/plain/org.eclipse.jdt.ui/jar%20in%20jar%20loader/org/eclipse/jdt/internal/jarinjarloader/; this classloader is very best of one-jar classloader and very fast;
<project.mainClass>org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader</project.mainClass>
<project.realMainClass>my.Class</project.realMainClass>
Edit in JIJConstants "Rsrc-Class-Path" to "Class-Path"
mvn clean dependency:copy-dependencies package
is created a jar with dependencies in lib folder with a thin classloader
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*</include>
</includes>
<targetPath>META-INF/</targetPath>
</resource>
<resource>
<directory>${project.build.directory}/dependency/</directory>
<includes>
<include>*.jar</include>
</includes>
<targetPath>lib/</targetPath>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>${project.mainClass}</mainClass>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
<manifestEntries>
<Rsrc-Main-Class>${project.realMainClass} </Rsrc-Main-Class>
<Class-Path>./</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
Hope this makes sense, Check the CPU and Memory utilization and put some threshold value. If the threshold value is crossed,don't allow to create new thread else allow...
Every recovery model lets you back up a whole or partial SQL Server database or individual files or filegroups of the database. Table-level backups cannot be created.
It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.
Here’s how you can find the details of your transaction:
Sign in to your Google Payments account at https://payments.google.com.
On the left menu, select the “Subscriptions and services” page.
On the “Other purchase activity” card, click View purchases.
Click the “Google Play” registration transaction to see your payment method.
You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.
To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).
echo -e "YOURPASSWORD\n" | sudo -S yourcommand
A byte with a value of 0x00
is, on the ASCII table, the special character called NUL
or NULL
. In C, since you shouldn't embed control characters in your source code, this is represented in C strings with an escaped 0, i.e., \0
.
But a true NULL is not a value. It is the absence of a value. For a pointer, it means the pointer has nothing to point to. In a database, it means there is no value in a field (which is not the same thing as saying the field is blank, 0, or filled with spaces).
The actual value a given system or database file format uses to represent a NULL
isn't necessarily 0x00
.
everything working in a batch should work in a cmd; cmd provides some extensions for controlling the environment. also, cmd is executed by in new cmd interpreter and thus should be faster (not noticeable on short files) and stabler as bat runs under the NTVDM emulated 16bit environment
To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:
Given the following function to test, located in module.a_function.to_test.py
:
from some_other.module import SomeOtherClass
def add_results():
my_object = SomeOtherClass('some_contextual_parameters')
result_a = my_object.method_a()
result_b = my_object.method_b()
return result_a + result_b
To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass
by using patch.object()
in combination with sys.modules
:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
mocked_other_class().method_a.return_value = 4
mocked_other_class().method_b.return_value = 7
self.assertEqual(add_results(), 11)
This works no matter the number of methods of SomeOtherClass
you need to patch, with independent results.
Also, using the same patching method, an actual instance of SomeOtherClass
can be returned if need be:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
other_class_instance = SomeOtherClass('some_controlled_parameters')
mocked_other_class.return_value = other_class_instance
...
Assuming you have only one record with null in EndDate column for a given RecordID, something like this should give you desired output :
WITH cte1 AS
(
SELECT recordid, MIN(startdate) as min_start , MAX(enddate) as max_end
FROM tmp
GROUP BY recordid
)
SELECT a.recordid, a.min_start ,
CASE
WHEN b.recordid IS NULL THEN a.max_end
END as max_end
FROM cte1 a
LEFT JOIN tmp b ON (b.recordid = a.recordid AND b.enddate IS NULL)
The common approach is to use the default value as a label, and then remove it when the field gains the focus.
I really dislike this approach as it has accessibility and usability implications.
Instead, I would start by using a standard element next to the field.
Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:
Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.
Whenever the input gains the focus, set that class.
The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).
This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.
First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py
a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path
) to create the module object.
(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path
and other settings. This is exactly what happens with python -m my.module
followed by an import my.module
in the interpreter; there will be two module objects, __main__
and my.module
, both created from the same file on disk, my/module.py
.)
A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:
$ mkdir -p a/b
$ touch a/b/c.py
Ensure that there are no other files under a
. Start a Python 3.4 or later interpreter (e.g., with python3 -i
) and examine the results of the following statements:
import a
a ? <module 'a' (namespace)>
a.b ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b ? <module 'a.b' (namespace)>
a.b.c ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>
Modules a
and a.b
are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c
is not a package. We can demonstrate this by adding another file, a/b.py
to the directory structure above and starting a fresh interpreter:
import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a ? <module 'a' (namespace)>
a.__path__ ? _NamespacePath(['/.../a'])
a.b ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__ ? AttributeError: 'module' object has no attribute '__path__'
Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/
is a directory, and so creates a namespace package a
, and that a/b.py
is a Python source file which it loads and uses to create a (non-package) module a.b
. At this point you cannot have a module a.b.c
because a.b
is not a package, and thus cannot have submodules.
You can also see here that the package module a
has a __path__
attribute (packages must have this) but the non-package module a.b
does not.
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
In .ts :
today: Date;
constructor() {
this.today =new Date();
}
.html:
<input type="date"
[ngModel]="today | date:'yyyy-MM-dd'"
(ngModelChange)="today = $event"
name="dt"
class="form-control form-control-rounded" #searchDate
>
Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:
fetch('http://jsonplaceholder.typicode.com/posts')
.then((response) => { return response.json(); })
.then((myJson) => {
this.setState({data: myJson}); // for example
});
Extension of VolkerK's answer, to make code a little more readable, you can use AS to reference the count, example below:
SELECT COUNT(*) AS c from profile
This makes for much easier reading in some frameworks, for example, i'm using Exponent's (React Native) Sqlite integration, and without the AS statement, the code is pretty ugly.
import java.io.*;
public class Code {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
Process process = builder.start();
StringBuilder out = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line = null;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append("\n");
}
System.out.println(out);
}
}
}
For the first question I think answer would be:
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
or
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:
Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]
My pain point is that every Sign-Up tool allows a different set of special characters. Some might only allow these @#$%&*
while others maybe don't allow *
but do allow other things. Every password generator I've come across is binary when it comes to special characters. It allows you to either include them or not. So I wind up cycling through tons of options and scanning for outliers that don't meet the requirements until I find a password that works. The longer the password the more tedious this becomes. Finally, I have noticed that sometimes Sign-Up tools don't let you repeat the same character twice in a row but password generators don't seem to account for this. It's madness!
I made this for myself so I can just paste in the exact set of special characters that are allowed. I do not pretend this is elegant code. I just threw it together to meet my needs.
Also, I couldn't think of a time when a Sign-Up tool did not allow numbers or wasn't case sensitive so my passwords always have at least one number, one upper case letter, one lower case letter, and one special character. This means the minimum length is 4. Technically I can get around the special character requirement by just entering a letter if need be.
const getPassword = (length, arg) => {_x000D_
length = document.getElementById("lengthInput").value || 16;_x000D_
arg = document.getElementById("specialInput").value || "~!@#$%^&*()_+-=[]{}|;:.,?><";_x000D_
if (length < 4) {_x000D_
updateView("passwordValue", "passwordValue", "", "P", "Length must be at least 4");_x000D_
return console.error("Length must be at least 4")_x000D_
} else if (length > 99) {_x000D_
updateView("passwordValue", "passwordValue", "", "P", "Length must be less then 100");_x000D_
return console.error("Length must be less then 100")_x000D_
}_x000D_
const lowercase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];_x000D_
const uppercase = lowercase.join("").toUpperCase().split("");_x000D_
const specialChars = arg.split("").filter(item => item.trim().length);_x000D_
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]_x000D_
let hasNumber = false;_x000D_
let hasUpper = false;_x000D_
let hasLower = false;_x000D_
let hasSpecial = false;_x000D_
_x000D_
if (Number(length)) {_x000D_
length = Number(length)_x000D_
} else {_x000D_
return console.error("Enter a valid length for the first argument.")_x000D_
}_x000D_
_x000D_
let password = [];_x000D_
let lastChar;_x000D_
for (let i = 0; i < length; i++) {_x000D_
let char = newChar(lowercase, uppercase, numbers, specialChars);_x000D_
if (char !== lastChar) {_x000D_
password.push(char);_x000D_
lastChar = char_x000D_
if (Number(char)) {_x000D_
hasNumber = true_x000D_
}_x000D_
if (lowercase.indexOf(char) > -1) {_x000D_
hasLower = true_x000D_
}_x000D_
if (uppercase.indexOf(char) > -1) {_x000D_
hasUpper = true_x000D_
}_x000D_
if (specialChars.indexOf(char) > -1) {_x000D_
hasSpecial = true_x000D_
}_x000D_
} else {_x000D_
i--_x000D_
}_x000D_
if (i === length - 1 && (!hasNumber || !hasUpper || !hasLower || !hasSpecial)) {_x000D_
hasNumber = false;_x000D_
hasUpper = false;_x000D_
hasLower = false;_x000D_
hasSpecial = false;_x000D_
password = [];_x000D_
i = -1;_x000D_
}_x000D_
}_x000D_
_x000D_
function newChar(lower, upper, nums, specials) {_x000D_
let set = [lower, upper, nums, specials];_x000D_
let pick = set[Math.floor(Math.random() * set.length)];_x000D_
return pick[Math.floor(Math.random() * pick.length)]_x000D_
}_x000D_
updateView("passwordValue", "passwordValue", "", "P", password.join(""));_x000D_
updateView("copyPassword", "copyPassword", "", "button", "copy text");_x000D_
document.getElementById("copyPassword").addEventListener("click", copyPassword);_x000D_
}_x000D_
_x000D_
const copyPassword = () => {_x000D_
let text = document.getElementById("passwordValue").textContent;_x000D_
navigator.clipboard.writeText(text);_x000D_
};_x000D_
_x000D_
const updateView = (targetId, newId, label, element, method = '') => {_x000D_
let newElement = document.createElement(element);_x000D_
newElement.id = newId;_x000D_
let content = document.createTextNode(label + method);_x000D_
newElement.appendChild(content);_x000D_
_x000D_
let currentElement = document.getElementById(targetId);_x000D_
let parentElement = currentElement.parentNode;_x000D_
parentElement.replaceChild(newElement, currentElement);_x000D_
}_x000D_
_x000D_
document.getElementById("getPassword").addEventListener("click", getPassword);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div>_x000D_
<button id="getPassword">Generate Password</button>_x000D_
<input type="number" id="lengthInput" placeholder="Length">_x000D_
<input type="text" id="specialInput" placeholder="Special Characters">_x000D_
<p id="passwordValue"></p>_x000D_
<p id="copyPassword"></p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Differences between
isinstance()
andtype()
in Python?
Type-checking with
isinstance(obj, Base)
allows for instances of subclasses and multiple possible bases:
isinstance(obj, (Base1, Base2))
whereas type-checking with
type(obj) is Base
only supports the type referenced.
As a sidenote, is
is likely more appropriate than
type(obj) == Base
because classes are singletons.
In Python, usually you want to allow any type for your arguments, treat it as expected, and if the object doesn't behave as expected, it will raise an appropriate error. This is known as polymorphism, also known as duck-typing.
def function_of_duck(duck):
duck.quack()
duck.swim()
If the code above works, we can presume our argument is a duck. Thus we can pass in other things are actual sub-types of duck:
function_of_duck(mallard)
or that work like a duck:
function_of_duck(object_that_quacks_and_swims_like_a_duck)
and our code still works.
However, there are some cases where it is desirable to explicitly type-check. Perhaps you have sensible things to do with different object types. For example, the Pandas Dataframe object can be constructed from dicts or records. In such a case, your code needs to know what type of argument it is getting so that it can properly handle it.
So, to answer the question:
isinstance()
and type()
in Python?Allow me to demonstrate the difference:
type
Say you need to ensure a certain behavior if your function gets a certain kind of argument (a common use-case for constructors). If you check for type like this:
def foo(data):
'''accepts a dict to construct something, string support in future'''
if type(data) is not dict:
# we're only going to test for dicts for now
raise ValueError('only dicts are supported for now')
If we try to pass in a dict that is a subclass of dict
(as we should be able to, if we're expecting our code to follow the principle of Liskov Substitution, that subtypes can be substituted for types) our code breaks!:
from collections import OrderedDict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
raises an error!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in foo
ValueError: argument must be a dict
isinstance
But if we use isinstance
, we can support Liskov Substitution!:
def foo(a_dict):
if not isinstance(a_dict, dict):
raise ValueError('argument must be a dict')
return a_dict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
returns OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])
In fact, we can do even better. collections
provides Abstract Base Classes that enforce minimal protocols for various types. In our case, if we only expect the Mapping
protocol, we can do the following, and our code becomes even more flexible:
from collections import Mapping
def foo(a_dict):
if not isinstance(a_dict, Mapping):
raise ValueError('argument must be a dict')
return a_dict
It should be noted that type can be used to check against multiple classes using
type(obj) in (A, B, C)
Yes, you can test for equality of types, but instead of the above, use the multiple bases for control flow, unless you are specifically only allowing those types:
isinstance(obj, (A, B, C))
The difference, again, is that isinstance
supports subclasses that can be substituted for the parent without otherwise breaking the program, a property known as Liskov substitution.
Even better, though, invert your dependencies and don't check for specific types at all.
So since we want to support substituting subclasses, in most cases, we want to avoid type-checking with type
and prefer type-checking with isinstance
- unless you really need to know the precise class of an instance.
Try this recursive version
def mergeList(l1,l2):
l3=[]
Tlen=len(l1)+len(l2)
inf= float("inf")
for i in range(Tlen):
print "l1= ",l1[0]," l2= ",l2[0]
if l1[0]<=l2[0]:
l3.append(l1[0])
del l1[0]
l1.append(inf)
else:
l3.append(l2[0])
del l2[0]
l2.append(inf)
return l3
def main():
l1=[2,10,7,6,8]
print mergeSort(breaklist(l1))
def breaklist(rawlist):
newlist=[]
for atom in rawlist:
print atom
list_atom=[atom]
newlist.append(list_atom)
return newlist
def mergeSort(inputList):
listlen=len(inputList)
if listlen ==1:
return inputList
else:
newlist=[]
if listlen % 2==0:
for i in range(listlen/2):
newlist.append(mergeList(inputList[2*i],inputList[2*i+1]))
else:
for i in range((listlen+1)/2):
if 2*i+1<listlen:
newlist.append(mergeList(inputList[2*i],inputList[2*i+1]))
else:
newlist.append(inputList[2*i])
return mergeSort(newlist)
if __name__ == '__main__':
main()
After hours of searching and testing finally got it just after posting the question!
You can use the "AnchorPane.topAnchor, AnchorPane.bottomAnchor, AnchorPane.leftAnchor, AnchorPane.rightAnchor" fxml commands with the value "0.0" to fit/stretch/align the child elements inside a AnchorPane. So, these commands tell to child element to follow its parent while resizing.
My updated code Main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane fx:id="anchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
<!--<StackPane fx:id="stackPane" ></StackPane>--> <!-- replace with the following -->
<StackPane fx:id="stackPane" AnchorPane.topAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" ></StackPane>
</AnchorPane>
Here is the result:
For api documentation: http://docs.oracle.com/javafx/2/api/javafx/scene/layout/AnchorPane.html
The below answer is good:
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]
But can be updated to:
grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] | mailx -s GREP [email protected]
Which can be more simple.
For the bytes uploaded it is quite easy. Just monitor the xhr.upload.onprogress
event. The browser knows the size of the files it has to upload and the size of the uploaded data, so it can provide the progress info.
For the bytes downloaded (when getting the info with xhr.responseText
), it is a little bit more difficult, because the browser doesn't know how many bytes will be sent in the server request. The only thing that the browser knows in this case is the size of the bytes it is receiving.
There is a solution for this, it's sufficient to set a Content-Length
header on the server script, in order to get the total size of the bytes the browser is going to receive.
For more go to https://developer.mozilla.org/en/Using_XMLHttpRequest .
Example: My server script reads a zip file (it takes 5 seconds):
$filesize=filesize('test.zip');
header("Content-Length: " . $filesize); // set header length
// if the headers is not set then the evt.loaded will be 0
readfile('test.zip');
exit 0;
Now I can monitor the download process of the server script, because I know it's total length:
function updateProgress(evt)
{
if (evt.lengthComputable)
{ // evt.loaded the bytes the browser received
// evt.total the total bytes set by the header
// jQuery UI progress bar to show the progress on screen
var percentComplete = (evt.loaded / evt.total) * 100;
$('#progressbar').progressbar( "option", "value", percentComplete );
}
}
function sendreq(evt)
{
var req = new XMLHttpRequest();
$('#progressbar').progressbar();
req.onprogress = updateProgress;
req.open('GET', 'test.php', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4)
{
//run any callback here
}
};
req.send();
}
If you are using lodash or underscore the _.countBy method will provide an object of aggregate totals keyed by each value in the array. You can turn this into a one-liner if you only need to count one value:
_.countBy(['foo', 'foo', 'bar'])['foo']; // 2
This also works fine on arrays of numbers. The one-liner for your example would be:
_.countBy([1, 2, 3, 5, 2, 8, 9, 2])[2]; // 3
I use this...but have never done any metro app development, so I don't know of any restrictions on libraries available to you. (note, you'll need to mark your classes as with DataContract and DataMember attributes)
public static class JSONSerializer<TType> where TType : class
{
/// <summary>
/// Serializes an object to JSON
/// </summary>
public static string Serialize(TType instance)
{
var serializer = new DataContractJsonSerializer(typeof(TType));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// </summary>
public static TType DeSerialize(string json)
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(TType));
return serializer.ReadObject(stream) as TType;
}
}
}
So, if you had a class like this...
[DataContract]
public class MusicInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Artist { get; set; }
[DataMember]
public string Genre { get; set; }
[DataMember]
public string Album { get; set; }
[DataMember]
public string AlbumImage { get; set; }
[DataMember]
public string Link { get; set; }
}
Then you would use it like this...
var musicInfo = new MusicInfo
{
Name = "Prince Charming",
Artist = "Metallica",
Genre = "Rock and Metal",
Album = "Reload",
AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
Link = "http://f2h.co.il/7779182246886"
};
// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);
// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);
You can have separate configuration file, but you'll have to read it "manually", the ConfigurationManager.AppSettings["key"]
will read only the config of the running assembly.
Assuming you're using Visual Studio as your IDE, you can right click the desired project ? Add ? New item ? Application Configuration File
This will add App.config
to the project folder, put your settings in there under <appSettings>
section. In case you're not using Visual Studio and adding the file manually, make sure to give it such name: DllName.dll.config, otherwise the below code won't work properly.
Now to read from this file have such function:
string GetAppSetting(Configuration config, string key)
{
KeyValueConfigurationElement element = config.AppSettings.Settings[key];
if (element != null)
{
string value = element.Value;
if (!string.IsNullOrEmpty(value))
return value;
}
return string.Empty;
}
And to use it:
Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;
try
{
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception ex)
{
//handle errror here.. means DLL has no sattelite configuration file.
}
if (config != null)
{
string myValue = GetAppSetting(config, "myKey");
...
}
You'll also have to add reference to System.Configuration namespace in order to have the ConfigurationManager class available.
When building the project, in addition to the DLL you'll have DllName.dll.config
file as well, that's the file you have to publish with the DLL itself.
The above is basic sample code, for those interested in a full scale example, please refer to this other answer.
If you want to toggle a class to an element using native solution, you could try this suggestion. I have tasted it in different cases, with or without other classes onto the element, and I think it works pretty much:
(function(objSelector, objClass){
document.querySelectorAll(objSelector).forEach(function(o){
o.addEventListener('click', function(e){
var $this = e.target,
klass = $this.className,
findClass = new RegExp('\\b\\s*' + objClass + '\\S*\\s?', 'g');
if( !findClass.test( $this.className ) )
if( klass )
$this.className = klass + ' ' + objClass;
else
$this.setAttribute('class', objClass);
else
{
klass = klass.replace( findClass, '' );
if(klass) $this.className = klass;
else $this.removeAttribute('class');
}
});
});
})('.yourElemetnSelector', 'yourClass');
git ls-remote | cut -f1 | git cat-file --batch-check >&-
will list everything referenced in any remote that isn't in your repo. To catch remote ref changes to things you already had (e.g. resets to previous commits) takes a little more:
git pack-refs --all
mine=`mktemp`
sed '/^#/d;/^^/{G;s/.\(.*\)\n.* \(.*\)/\1 \2^{}/;};h' .git/packed-refs | sort -k2 >$mine
for r in `git remote`; do
echo Checking $r ...
git ls-remote $r | sort -k2 | diff -b - $mine | grep ^\<
done
My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.
This difference in IDE behavior is one of the key reasons for upgrading to a full version.
eg:
MyPackageName is com.example.demo
MyActivityName is com.example.test.MainActivity
adb shell am start -n com.example.demo/com.example.test.MainActivity
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
Its very easy to do that, react-router-dom provides all.
import React from 'react';_x000D_
import { matchPath, withRouter } from 'react-router';_x000D_
_x000D_
class NavBar extends React.Component {_x000D_
render(){_x000D_
return(_x000D_
<ul className="sidebar-menu">_x000D_
<li className="header">MAIN NAVIGATION</li>_x000D_
<li className={matchPath(this.props.location.pathname, { path: "/dashboard" }) ? 'active' : ''}><Link to="dashboard"><i className="fa fa-dashboard"></i> _x000D_
<span>Dashboard</span></Link></li>_x000D_
<li className={matchPath(this.props.location.pathname, { path: "/email_lists" }) ? 'active' : ''}><Link to="email_lists"><i className="fa fa-envelope-o"></i> _x000D_
<span>Email Lists</span></Link></li>_x000D_
<li className={matchPath(this.props.location.pathname, { path: "/billing" }) ? 'active' : ''}><Link to="billing"><i className="fa fa-credit-card"></i> _x000D_
<span>Buy Verifications</span></Link></li>_x000D_
</ul>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
export default withRouter(NavBar);
_x000D_
Wrapping You Navigation Component with withRouter() HOC will provide few props to your component: 1. match 2. history 3. location
here i used matchPath() method from react-router to compare the paths and decide if the 'li' tag should get "active" class name or not. and Im accessing the location from this.props.location.pathname.
changing the path name in props will happen when our link is clicked, and location props will get updated NavBar also get re-rendered and active style will get applied
it could be also you are trying to index in the wrong way:
a = 'apple'
a(3) ===> 'str' object is not callable
a[3] = l
The java.sql.Timestamp class has no format. Its toString method generates a String with a format.
Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.
First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.
Instant instant = mySqlDate.toInstant() ;
Lose the fraction of a second you don't want.
instant = instant.truncatedTo( ChronoUnit.Seconds );
Assign the time zone to adjust from UTC used by Instant.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generate a String close to your desired output. Replace its T
in the middle with a SPACE.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")
Typically an alternative for fixed size Lists are Java arrays. Lists by default are allowed to grow/shrink in Java. However, that does not mean you cannot have a List of a fixed size. You'll need to do some work and create a custom implementation.
You can extend an ArrayList with custom implementations of the clear, add and remove methods.
e.g.
import java.util.ArrayList;
public class FixedSizeList<T> extends ArrayList<T> {
public FixedSizeList(int capacity) {
super(capacity);
for (int i = 0; i < capacity; i++) {
super.add(null);
}
}
public FixedSizeList(T[] initialElements) {
super(initialElements.length);
for (T loopElement : initialElements) {
super.add(loopElement);
}
}
@Override
public void clear() {
throw new UnsupportedOperationException("Elements may not be cleared from a fixed size List.");
}
@Override
public boolean add(T o) {
throw new UnsupportedOperationException("Elements may not be added to a fixed size List, use set() instead.");
}
@Override
public void add(int index, T element) {
throw new UnsupportedOperationException("Elements may not be added to a fixed size List, use set() instead.");
}
@Override
public T remove(int index) {
throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
}
}
Please start using PDO.
mysql_* is deprecated as of PHP 5.5.0 and will be removed entirely in 7. Let's make it easier to upgrade and start using it now.
$dbh = new \PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT count(*) as total from Students');
$sth->execute();
print_r($sth->fetchColumn());
This code will help you to make a repeating alarm. The repeating time can set by you.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:paddingTop="100dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<EditText
android:id="@+id/ethr"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Hr"
android:singleLine="true" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/etmin"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Min"
android:singleLine="true" />
<EditText
android:id="@+id/etsec"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Sec"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp">
<Button
android:id="@+id/setAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickSetAlarm"
android:text="Set Alarm" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
int hr = 0;
int min = 0;
int sec = 0;
int result = 1;
AlarmManager alarmManager;
PendingIntent pendingIntent;
BroadcastReceiver mReceiver;
EditText ethr;
EditText etmin;
EditText etsec;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ethr = (EditText) findViewById(R.id.ethr);
etmin = (EditText) findViewById(R.id.etmin);
etsec = (EditText) findViewById(R.id.etsec);
RegisterAlarmBroadcast();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public void onClickSetAlarm(View v) {
String shr = ethr.getText().toString();
String smin = etmin.getText().toString();
String ssec = etsec.getText().toString();
if(shr.equals(""))
hr = 0;
else {
hr = Integer.parseInt(ethr.getText().toString());
hr=hr*60*60*1000;
}
if(smin.equals(""))
min = 0;
else {
min = Integer.parseInt(etmin.getText().toString());
min = min*60*1000;
}
if(ssec.equals(""))
sec = 0;
else {
sec = Integer.parseInt(etsec.getText().toString());
sec = sec * 1000;
}
result = hr+min+sec;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
}
private void RegisterAlarmBroadcast() {
mReceiver = new BroadcastReceiver() {
// private static final String TAG = "Alarm Example Receiver";
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
}
};
registerReceiver(mReceiver, new IntentFilter("sample"));
pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0);
alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
}
private void UnregisterAlarmBroadcast() {
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}
}
If you need alarm only for a single time then replace
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
with
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );
Download visual studio c++ express version 2006,2010 etc. then goto create new project and create c++ project select cmd project check empty rename cc with c extension file name
With this query you can execute any stored procedure(With or Without output parameter):
DECLARE @temp varchar(100)
EXEC my_sp
@parameter1 = 1,
@parameter2 = 2,
@parameter3 = @temp output,
@parameter4 = 3,
@parameter5 = 4
PRINT @temp
Here datatype of @temp should be same as @parameter3 within SP.
Hope this helps..
now('milli'); // 120335360.999686
now('micro') ; // 120335360966.583
now('nano') ; // 120335360904333
Known that now
is :
const now = (unit) => {
const hrTime = process.hrtime();
switch (unit) {
case 'milli':
return hrTime[0] * 1000 + hrTime[1] / 1000000;
case 'micro':
return hrTime[0] * 1000000 + hrTime[1] / 1000;
case 'nano':
default:
return hrTime[0] * 1000000000 + hrTime[1];
}
};
The point is semantics. In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.
assertTrue (message, value == false) == assertFalse (message, value);
These are functionally the same, but if you are expecting a value to be false then use assertFalse
. If you are expecting a value to be true, then use assertTrue
.
<string.h>
is the old C header. C++ provides <string>
, and then it should be referred to as std::string
.
While Tats_innit's answer has a nice touch to it, I had to do it a bit differently since I have more than one progress bar on the page.
here's my solution:
JSfiddle: http://jsfiddle.net/vacNJ/
HTML (example):
<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="60"></div>
</div>
<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="50"></div>
</div>
<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="40"></div>
</div>
?
JavaScript:
setTimeout(function(){
$('.progress .bar').each(function() {
var me = $(this);
var perc = me.attr("data-percentage");
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.css('width', (current_perc)+'%');
}
me.text((current_perc)+'%');
}, 50);
});
},300);
@Tats_innit: Using setInterval() to dynamically recalc the progress is a nice solution, thx mate! ;)
EDIT:
A friend of mine wrote a nice jquery plugin for custom twitter bootstrap progress bars. Here's a demo: http://minddust.github.com/bootstrap-progressbar/
Here's the Github repo: https://github.com/minddust/bootstrap-progressbar
select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0)) as total_hours
from hours_t
group by type, craft
order by type, craft
Use \n
in text and css white-space: pre-wrap;
The best way for converting to Numpy Array is using '.to_numpy(self, dtype=None, copy=False)'. It is new in version 0.24.0.Refrence
You can also use '.array'.Refrence
Pandas .as_matrix deprecated since version 0.23.0.
By strange it can seem it works perfectly fine: date_create( '2016-02-01 + 1 day' );
echo date_create( $your_date . ' + 1 day' )->format( 'Y-m-d' );
Should do it
If you want an else
you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value
as the statement instead, and remove the filter from the end:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
Maybe it's the best possiblity to create a TimerTask that sets the received Location to a certain value (null?) regularly. If a new value is received by the GPSListener it will update the location with the current data.
I think that would be a working solution.
add this to you CSS:
html, body
{
height: 100%;
}
when you say to wrap
to be 100%
, 100% of what? of its parent (body), so his parent has to have some height.
and the same goes for body
, his parent his html
. html
parent his the viewport..
so, by setting them both to 100%, wrap
can also have a percentage height.
also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use
*
{
padding: 0;
margin: 0;
}
to disable that.
Look at That Fiddle
Since pip
is an executable and which
returns path of executables or filenames in environment. It is correct. Pip module is installed in site-packages but the executable is installed in bin.
I also was importing the wrong Entity import org.hibernate.annotations.Entity;
It should be import javax.persistence.Entity;
Found the error:
Final xxx-servlet.xml config:
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
Image in src/webapp/resources/logo.png
Works!
Try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Set your date format
String currentData = sdf.format(new Date());
Toast.makeText(getApplicationContext(), ""+currentData,Toast.LENGTH_SHORT ).show();
Sometimes, a textual representation might also help; with this query on the system catalog views, you can get a list of all FK relationships and how the link two tables (and what columns they operate on).
SELECT
fk.name 'FK Name',
tp.name 'Parent table',
cp.name, cp.column_id,
tr.name 'Refrenced table',
cr.name, cr.column_id
FROM
sys.foreign_keys fk
INNER JOIN
sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN
sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN
sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
ORDER BY
tp.name, cp.column_id
Dump this into Excel, and you can slice and dice - based on the parent table, the referenced table or anything else.
I find visual guides helpful - but sometimes, textual documentation is just as good (or even better) - just my 2 cents.....
#!/bin/bash
filename=program.c
name=$(basename "$filename" .c)
echo "$name"
outputs:
program
here's another way just to see the indices in the db:
curl -sG somehost-dev.example.com:9200/_status --user "credentials:password" | sed 's/,/\n/g' | grep index | grep -v "size_in" | uniq
{ "index":"tmpdb"}
{ "index":"devapp"}
If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.
Screenshot Convert ipynb to pdf
If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.
Just as I was thinking that it would be fun to write a streaming JSON parser, I also thought that maybe I should do a quick search to see if there's one already available.
Turns out there is.
Since I just found it, I've obviously not used it, so I can't comment on its quality, but I'll be interested to hear if it works.
It does work consider the following Javascript and _.isString
:
stream.pipe(JSONStream.parse('*'))
.on('data', (d) => {
console.log(typeof d);
console.log("isString: " + _.isString(d))
});
This will log objects as they come in if the stream is an array of objects. Therefore the only thing being buffered is one object at a time.
It's funny such a question can get so many answers, and yet none fit my requirements :) There are so many languages around, a full language agnostic solution is AFAIK not really possible, as others has mentionned that the FormC or FormD are giving issues.
Since the original question was related to French, the simplest working answer is indeed
public static string ConvertWesternEuropeanToASCII(this string str)
{
return Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(str));
}
1251 should be replaced by the encoding code of the input language.
This however replace only one character by one character. Since I am also working with German as input, I did a manual convert
public static string LatinizeGermanCharacters(this string str)
{
StringBuilder sb = new StringBuilder(str.Length);
foreach (char c in str)
{
switch (c)
{
case 'ä':
sb.Append("ae");
break;
case 'ö':
sb.Append("oe");
break;
case 'ü':
sb.Append("ue");
break;
case 'Ä':
sb.Append("Ae");
break;
case 'Ö':
sb.Append("Oe");
break;
case 'Ü':
sb.Append("Ue");
break;
case 'ß':
sb.Append("ss");
break;
default:
sb.Append(c);
break;
}
}
return sb.ToString();
}
It might not deliver the best performance, but at least it is very easy to read and extend. Regex is a NO GO, much slower than any char/string stuff.
I also have a very simple method to remove space:
public static string RemoveSpace(this string str)
{
return str.Replace(" ", string.Empty);
}
Eventually, I am using a combination of all 3 above extensions:
public static string LatinizeAndConvertToASCII(this string str, bool keepSpace = false)
{
str = str.LatinizeGermanCharacters().ConvertWesternEuropeanToASCII();
return keepSpace ? str : str.RemoveSpace();
}
And a small unit test to that (not exhaustive) which pass successfully.
[TestMethod()]
public void LatinizeAndConvertToASCIITest()
{
string europeanStr = "Bonjour ça va? C'est l'été! Ich möchte ä Ä á à â ê é è ë Ë É ï Ï î í ì ó ò ô ö Ö Ü ü ù ú û Û ý Ý ç Ç ñ Ñ";
string expected = "Bonjourcava?C'estl'ete!IchmoechteaeAeaaaeeeeEEiIiiiooooeOeUeueuuuUyYcCnN";
string actual = europeanStr.LatinizeAndConvertToASCII();
Assert.AreEqual(expected, actual);
}
Do it with javascript and add a onClick
-attribute to your object
-element:
<object data="mysvg.svg" type="image/svg+xml" onClick="window.location.href='http://google.at';">
<span>Your browser doesn't support SVG images</span>
</object>
As described by the link I've given in comment, this
$('p[MyTag]').each(function(index) {
document.write(index + ': ' + $(this).text() + "<br>");});
works (playable example).
SUMMARY:
I provide here a no-jQuery cross-browser desktop-and-mobile ability to consistently respond to range/slider interactions, something not possible in current browsers. It essentially forces all browsers to emulate IE11's on("change"...
event for either their on("change"...
or on("input"...
events. The new function is...
function onRangeChange(r,f) {
var n,c,m;
r.addEventListener("input",function(e){n=1;c=e.target.value;if(c!=m)f(e);m=c;});
r.addEventListener("change",function(e){if(!n)f(e);});
}
...where r
is your range input element and f
is your listener. The listener will be called after any interaction that changes the range/slider value but not after interactions that do not change that value, including initial mouse or touch interactions at the current slider position or upon moving off either end of the slider.
Problem:
As of early June 2016, different browsers differ in terms of how they respond to range/slider usage. Five scenarios are relevant:
The following table shows how at least three different desktop browsers differ in their behaviour with respect to which of the above scenarios they respond to:
Solution:
The onRangeChange
function provides a consistent and predictable cross-browser response to range/slider interactions. It forces all browsers to behave according to the following table:
In IE11, the code essentially allows everything to operate as per the status quo, i.e. it allows the "change"
event to function in its standard way and the "input"
event is irrelevant as it never fires anyway. In other browsers, the "change"
event is effectively silenced (to prevent extra and sometimes not-readily-apparent events from firing). In addition, the "input"
event fires its listener only when the range/slider's value changes. For some browsers (e.g. Firefox) this occurs because the listener is effectively silenced in scenarios 1, 4 and 5 from the above list.
(If you truly require a listener to be activated in either scenario 1, 4 and/or 5 you could try incorporating "mousedown"
/"touchstart"
, "mousemove"
/"touchmove"
and/or "mouseup"
/"touchend"
events. Such a solution is beyond the scope of this answer.)
Functionality in Mobile Browsers:
I have tested this code in desktop browsers but not in any mobile browsers. However, in another answer on this page MBourne has shown that my solution here "...appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari)". (Thanks MBourne.)
Usage:
To use this solution, include the onRangeChange
function from the summary above (simplified/minified) or the demo code snippet below (functionally identical but more self-explanatory) in your own code. Invoke it as follows:
onRangeChange(myRangeInputElmt, myListener);
where myRangeInputElmt
is your desired <input type="range">
DOM element and myListener
is the listener/handler function you want invoked upon "change"
-like events.
Your listener may be parameter-less if desired or may use the event
parameter, i.e. either of the following would work, depending on your needs:
var myListener = function() {...
or
var myListener = function(evt) {...
(Removing the event listener from the input
element (e.g. using removeEventListener
) is not addressed in this answer.)
Demo Description:
In the code snippet below, the function onRangeChange
provides the universal solution. The rest of the code is simply an example to demonstrate its use. Any variable that begins with my...
is irrelevant to the universal solution and is only present for the sake of the demo.
The demo shows the range/slider value as well as the number of times the standard "change"
, "input"
and custom "onRangeChange"
events have fired (rows A, B and C respectively). When running this snippet in different browsers, note the following as you interact with the range/slider:
Demo Code:
// main function for emulating IE11's "change" event:_x000D_
_x000D_
function onRangeChange(rangeInputElmt, listener) {_x000D_
_x000D_
var inputEvtHasNeverFired = true;_x000D_
_x000D_
var rangeValue = {current: undefined, mostRecent: undefined};_x000D_
_x000D_
rangeInputElmt.addEventListener("input", function(evt) {_x000D_
inputEvtHasNeverFired = false;_x000D_
rangeValue.current = evt.target.value;_x000D_
if (rangeValue.current !== rangeValue.mostRecent) {_x000D_
listener(evt);_x000D_
}_x000D_
rangeValue.mostRecent = rangeValue.current;_x000D_
});_x000D_
_x000D_
rangeInputElmt.addEventListener("change", function(evt) {_x000D_
if (inputEvtHasNeverFired) {_x000D_
listener(evt);_x000D_
}_x000D_
}); _x000D_
_x000D_
}_x000D_
_x000D_
// example usage:_x000D_
_x000D_
var myRangeInputElmt = document.querySelector("input" );_x000D_
var myRangeValPar = document.querySelector("#rangeValPar" );_x000D_
var myNumChgEvtsCell = document.querySelector("#numChgEvtsCell");_x000D_
var myNumInpEvtsCell = document.querySelector("#numInpEvtsCell");_x000D_
var myNumCusEvtsCell = document.querySelector("#numCusEvtsCell");_x000D_
_x000D_
var myNumEvts = {input: 0, change: 0, custom: 0};_x000D_
_x000D_
var myUpdate = function() {_x000D_
myNumChgEvtsCell.innerHTML = myNumEvts["change"];_x000D_
myNumInpEvtsCell.innerHTML = myNumEvts["input" ];_x000D_
myNumCusEvtsCell.innerHTML = myNumEvts["custom"];_x000D_
};_x000D_
_x000D_
["input", "change"].forEach(function(myEvtType) {_x000D_
myRangeInputElmt.addEventListener(myEvtType, function() {_x000D_
myNumEvts[myEvtType] += 1;_x000D_
myUpdate();_x000D_
});_x000D_
});_x000D_
_x000D_
var myListener = function(myEvt) {_x000D_
myNumEvts["custom"] += 1;_x000D_
myRangeValPar.innerHTML = "range value: " + myEvt.target.value;_x000D_
myUpdate();_x000D_
};_x000D_
_x000D_
onRangeChange(myRangeInputElmt, myListener);
_x000D_
table {_x000D_
border-collapse: collapse; _x000D_
}_x000D_
th, td {_x000D_
text-align: left;_x000D_
border: solid black 1px;_x000D_
padding: 5px 15px;_x000D_
}
_x000D_
<input type="range"/>_x000D_
<p id="rangeValPar">range value: 50</p>_x000D_
<table>_x000D_
<tr><th>row</th><th>event type </th><th>number of events </th><tr>_x000D_
<tr><td>A</td><td>standard "change" events </td><td id="numChgEvtsCell">0</td></tr>_x000D_
<tr><td>B</td><td>standard "input" events </td><td id="numInpEvtsCell">0</td></tr>_x000D_
<tr><td>C</td><td>new custom "onRangeChange" events</td><td id="numCusEvtsCell">0</td></tr>_x000D_
</table>
_x000D_
Credit:
While the implementation here is largely my own, it was inspired by MBourne's answer. That other answer suggested that the "input" and "change" events could be merged and that the resulting code would work in both desktop and mobile browsers. However, the code in that answer results in hidden "extra" events being fired, which in and of itself is problematic, and the events fired differ between browsers, a further problem. My implementation here solves those problems.
Keywords:
JavaScript input type range slider events change input browser compatability cross-browser desktop mobile no-jQuery
I encountered a similar problem. And I found the solution to be totally unrelated to the error. The trick was renaming the assembly name. Solution: VS 2013 -> Project properties -> Application tab -> AssemblyName property changed to new name < 25 chars
toString() is a debug info string. The default implementation returns the class name and the system identity hash. Collections return all elements but arrays not.
Also be aware of NullPointerException
creating the log!
In this case a Arrays.toString()
may help:
Object temp = data.getParameterValue("request");
String log = temp == null ? "null" : (temp.getClass().isArray() ? Arrays.toString((Object[])temp) : temp.toString());
log.info("end " + temp);
You can also use Arrays.asList()
:
Object temp = data.getParameterValue("request");
Object log = temp == null ? null : (temp.getClass().isArray() ? Arrays.asList((Object[])temp) : temp);
log.info("end " + temp);
This may result in a ClassCastException
for primitive arrays (int[]
, ...).
Same basic solution as others, but I personally prefer to use map instead of the list comprehension:
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'
What is better is PDO; it's a less crufty interface and also provides the same features as MySQLi.
Using prepared statements is good because it eliminates SQL injection possibilities; using server-side prepared statements is bad because it increases the number of round-trips.
In my case, it was a small letter f
.
I'm sharing this answer just because this is the first result on google
make sure to write *ngFor
First check the URL it might be wrong, if it is correct then check the request body which you are sending, the possible cause is request that you are sending is missing right syntax.
To elaborate , check for special characters in the request string. If it is (special char) being used this is the root cause of this error.
try copying the request and analyze each and every tags data.
Well, IMHO..
With regards to #1, I have a strongly typed Master View which has a property to access whatever the Session object represents....in my instance the stongly typed Master View is generic which gives me some flexibility with regards to strongly typed View Pages
ViewMasterPage<AdminViewModel>
AdminViewModel
{
SomeImportantObjectThatWasInSession ImportantObject
}
AdminViewModel<TModel> : AdminViewModel where TModel : class
{
TModel Content
}
and then...
ViewPage<AdminViewModel<U>>
The #define
allows you to establish a value in a header that would otherwise compile to size-greater-than-zero. Your headers should not compile to size-greater-than-zero.
// File: MyFile.h
// This header will compile to size-zero.
#define TAX_RATE 0.625
// NO: static const double TAX_RATE = 0.625;
// NO: extern const double TAX_RATE; // WHAT IS THE VALUE?
EDIT: As Neil points out in the comment to this post, the explicit definition-with-value in the header would work for C++, but not C.
you have the print_r function DOC
In addition to Pascal Thivent's correct answer, another way is to save the certificate from Firefox (View Certificate -> Details -> export) or openssl s_client
and import it into the trust store.
You should only do this if you have a way to verify that certificate. Failing that, do it the first time you connect, it will at least give you an error if the certificate changes unexpectedly on subsequent connections.
To import it in a trust store, use:
keytool -importcert -keystore truststore.jks -file servercert.pem
By default, the default trust store should be $JAVA_HOME/jre/lib/security/cacerts
and its password should be changeit
, see JSSE Reference guide for details.
If you don't want to allow that certificate globally, but only for these connections, it's possible to create an SSLContext
for it:
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("/.../truststore.jks");
ks.load(fis, null);
// or ks.load(fis, "thepassword".toCharArray());
fis.close();
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
Then, you need to set it up for Apache HTTP Client 3.x by implementing one if its SecureProtocolSocketFactory
to use this SSLContext
. (There are examples here).
Apache HTTP Client 4.x (apart from the earliest version) has direct support for passing an SSLContext
.
Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.
Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:
window
objectIf the formula already exists in a cell you can fill it down as follows:
On Mac, use CMD instead of CTRL.
An alternative if the formula is in the first cell of a column:
I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.
Encapsulation: Hiding implementation details (NOTE: data AND/OR methods) such that only what is sensibly readable/writable/usable by externals is accessible to them, everything else is "untouchable" directly.
Abstraction: This sometimes refers specifically to a type that cannot be instantiated and which provides a template for other types that can be, usually via subclassing. More generally "abstraction" refers to making/having something that is less detailed, less specific, less granular.
There is some similarity, overlap between the concepts but the best way to remember it is like this: Encapsulation is more about hiding the details, whereas abstraction is more about generalizing the details.
For CMake 3.8 and newer you can use
target_compile_features(target PUBLIC cxx_std_11)
awk '/^[[:space:]]*$/ {++x} END {print x}' "$testfile"
You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
GROUP BY DATE(date_time_column)
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
Since MySQL (8.0.16) and MariaDB (10.2.1) both implemented the CHECK constraint, I would now use
bool_val TINYINT CHECK(bool_val IN(0,1))
You will only be able to store 0
, 1
or NULL
, as well as values which can be converted to 0
or 1
without errors like '1'
, 0x00
, b'1'
or TRUE
/FALSE
.
If you don't want to permit NULLs, add the NOT NULL
option
bool_val TINYINT NOT NULL CHECK(bool_val IN(0,1))
Note that there is virtually no difference if you use TINYINT
, TINYINT(1)
or TINYINT(123)
.
If you want your schema to be upwards compatible, you can also use BOOL
or BOOLEAN
bool_val BOOL CHECK(bool_val IN(TRUE,FALSE))
Here's an alternate
req.hostname
Read about it in the Express Docs.
When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe
I had to choose the following options to get the management Tools:
When I was done I had an option "SQL Server Management Studio" within my Start Menu.
Searching for "Management" pulled it up faster within the Start Menu.
Yesterday Date in PHP:
echo date("Y-m-d", strtotime("yesterday"));
You can use the QuerySetChain
class below. When using it with Django's paginator, it should only hit the database with COUNT(*)
queries for all querysets and SELECT()
queries only for those querysets whose records are displayed on the current page.
Note that you need to specify template_name=
if using a QuerySetChain
with generic views, even if the chained querysets all use the same model.
from itertools import islice, chain
class QuerySetChain(object):
"""
Chains multiple subquerysets (possibly of different models) and behaves as
one queryset. Supports minimal methods needed for use with
django.core.paginator.
"""
def __init__(self, *subquerysets):
self.querysets = subquerysets
def count(self):
"""
Performs a .count() for all subquerysets and returns the number of
records as an integer.
"""
return sum(qs.count() for qs in self.querysets)
def _clone(self):
"Returns a clone of this queryset chain"
return self.__class__(*self.querysets)
def _all(self):
"Iterates records in all subquerysets"
return chain(*self.querysets)
def __getitem__(self, ndx):
"""
Retrieves an item or slice from the chained set of results from all
subquerysets.
"""
if type(ndx) is slice:
return list(islice(self._all(), ndx.start, ndx.stop, ndx.step or 1))
else:
return islice(self._all(), ndx, ndx+1).next()
In your example, the usage would be:
pages = Page.objects.filter(Q(title__icontains=cleaned_search_term) |
Q(body__icontains=cleaned_search_term))
articles = Article.objects.filter(Q(title__icontains=cleaned_search_term) |
Q(body__icontains=cleaned_search_term) |
Q(tags__icontains=cleaned_search_term))
posts = Post.objects.filter(Q(title__icontains=cleaned_search_term) |
Q(body__icontains=cleaned_search_term) |
Q(tags__icontains=cleaned_search_term))
matches = QuerySetChain(pages, articles, posts)
Then use matches
with the paginator like you used result_list
in your example.
The itertools
module was introduced in Python 2.3, so it should be available in all Python versions Django runs on.
In Java 8,
public int sum(int number) {
return (number + "").chars()
.map(digit -> digit % 48)
.sum();
}
Converts the number to a string and then each character is mapped to it's digit value by subtracting ascii value of '0' (48) and added to the final sum.
Use This
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function () {
$("#left_panel").toggle("slide", { direction: "left" }, 1000);
});
});
</script>
In Postgres, you can also use the special DISTINCT ON (expression)
syntax:
SELECT DISTINCT ON (cname)
cname, wmname, avg
FROM
makerar
ORDER BY
cname, avg DESC ;
http://en.wikipedia.org/wiki/Euclidean_distance
If you have the coordinates, use the formula to calculate the distance:
var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
If your platform supports the **
operator, you can instead use that:
const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
I had two problems with using Acrobat Reader for this task.
I stumbled across this blog, that suggests using Foxit Reader. Foxit Reader is free, the API is almost identical to Acrobat Reader, but crucially is documented and does not load the GUI for print jobs.
A word of warning, don't just click through the install process without paying attention, it tries to install unrelated software as well. Why are software vendors still doing this???
Just use the javascript window.open function with the second parameter at "_blank"
<button onClick="javascript:window.open('http://www.facebook.com', '_blank');">facebook</button>
I was using reactive forms and ran into similar problems. What helped me was to make sure that I set up a corresponding FormGroup
in the class.
Something like this:
myFormGroup: FormGroup = this.builder.group({
dob: ['', Validators.required]
});
I reviewed all the answers and all are keeping fixed width and adjust only height. If you wish to adjust also width you can very easily use this method:
so when configuring your text view, set scroll disabled
textView.isScrollEnabled = false
and then in delegate method func textViewDidChange(_ textView: UITextView)
add this code:
func textViewDidChange(_ textView: UITextView) {
let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
textView.frame = CGRect(origin: textView.frame.origin, size: newSize)
}
Outputs:
I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.
If you have lists that are not the same length, you may not want to use zip as per Patricks answer. This works:
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
But with different length lists, zip truncates each item to the length of the shortest list:
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e')]
You can use map with no function to fill empty results with None:
>>> map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)]
zip() is marginally faster though.
I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.
Setting the Accept
header to application/json
in the request worked for me when I faced the same problem.
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
You can use the following approach:
[lower + x*(upper-lower)/length for x in range(length)]
lower and/or upper must be assigned as floats for this approach to work.
For Intellij 14.0.0 the Application server option is available under View > Tools window > Application Server (But if it is enable, i mean if you have any plugin installed)
You can have a pair of extension methods to make this task easier:
public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
return lst.ToDelimitedString(p => p, separator);
}
public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector,
string separator = ", ")
{
return string.Join(separator, lst.Select(selector));
}
So now just:
new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
This is how you can draw a gray line at the end of your view (same idea as b123400's answer)
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.gray.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
Many answers here say the same (order by your auto increment), which is OK, provided you have an autoincremented column that is indexed.
On a side note, if you have such field and it is the primary key, there is no performance penalty for using order by
versus select max(id)
. The primary key is how data is ordered in the database files (for InnoDB at least), and the RDBMS knows where that data ends, and it can optimize order by id + limit 1
to be the same as reach the max(id)
Now the road less traveled is when you don't have an autoincremented primary key. Maybe the primary key is a natural key, which is a composite of 3 fields... Not all is lost, though. From a programming language you can first get the number of rows with
SELECT Count(*) - 1 AS rowcount FROM <yourTable>;
and then use the obtained number in the LIMIT
clause
SELECT * FROM orderbook2
LIMIT <number_from_rowcount>, 1
Unfortunately, MySQL will not allow for a sub-query, or user variable in the LIMIT
clause
Based on software and system engineering experience, I'd summarise the difference as follows:
Simulation: for me, this is always in software - every aspect of the real system is only MODELLED by some code and/or mathematics. Simulation attempts to accurately reproduce the behaviour (or predict it) of the real system, but only approximates it.
Emulation: As opposed to simulation, it does not APPROXIMATE the behaviour of the real system, it COPIES the behaviour of the real system. An emulator may involve hardware. But it may also be entirely in software. E.g. you get these software EMULATORS for old game consoles like the Sega Genesis. That is an emulator because it COPIES the real genesis functionality so much so that you can run the original Genesis code in the emulator. A genesis simulator would not be able to run the original code, it would only APPROXIMATE its behaviour, producing similar results, depending on how good the models of the original system were.
An emulator of a system component can be included in a larger system, completely replacing the component it is emulating - a simulator could not because it is not an accurate enough representation of the original component behaviour.
EDIT: First check, if you did not run out of disk-space, before resolving to the configuration-related resolution.
You seem to have a too low maximum size for your innodb_data_file_path
in your my.cnf
, In this example
innodb_data_file_path = ibdata1:10M:autoextend:max:512M
you cannot host more than 512MB of data in all innodb tables combined.
Maybe you should switch to an innodb-per-table scheme using innodb_file_per_table
.
How to create optional and required delegate methods.
@objc protocol InterViewDelegate:class {
@objc optional func optfunc() // This is optional
func requiredfunc()// This is required
}
Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os
Figuring out what settings to use can be performed automatically, as mentioned in this technote:
/usr/bin/nscurl --ats-diagnostics --verbose https://your-domain.com
Try this:
!unpack file.zip
If its now working or file is 7z try below
!apt-get install p7zip-full
!p7zip -d file_name.tar.7z
!tar -xvf file_name.tar
Or
!pip install pyunpack
!pip install patool
from pyunpack import Archive
Archive(‘file_name.tar.7z’).extractall(‘path/to/’)
!tar -xvf file_name.tar
This was inspired by using Sets as indexers in Delphi, way back when:
/// Example of using a Boolean indexed property
/// to manipulate a [Flags] enum:
public class BindingFlagsIndexer
{
BindingFlags flags = BindingFlags.Default;
public BindingFlagsIndexer()
{
}
public BindingFlagsIndexer( BindingFlags value )
{
this.flags = value;
}
public bool this[BindingFlags index]
{
get
{
return (this.flags & index) == index;
}
set( bool value )
{
if( value )
this.flags |= index;
else
this.flags &= ~index;
}
}
public BindingFlags Value
{
get
{
return flags;
}
set( BindingFlags value )
{
this.flags = value;
}
}
public static implicit operator BindingFlags( BindingFlagsIndexer src )
{
return src != null ? src.Value : BindingFlags.Default;
}
public static implicit operator BindingFlagsIndexer( BindingFlags src )
{
return new BindingFlagsIndexer( src );
}
}
public static class Class1
{
public static void Example()
{
BindingFlagsIndexer myFlags = new BindingFlagsIndexer();
// Sets the flag(s) passed as the indexer:
myFlags[BindingFlags.ExactBinding] = true;
// Indexer can specify multiple flags at once:
myFlags[BindingFlags.Instance | BindingFlags.Static] = true;
// Get boolean indicating if specified flag(s) are set:
bool flatten = myFlags[BindingFlags.FlattenHierarchy];
// use | to test if multiple flags are set:
bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];
}
}
There isn't any direct equivalent to the goto
concept in Java. There are a few constructs that allow you to do some of the things you can do with a classic goto
.
break
and continue
statements allow you to jump out of a block in a loop or switch statement.break <label>
allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block).continue <label>
to continue with the next iteration of an outer loop from an inner loop.return
.None of these Java constructs allow you to branch backwards or to a point in the code at the same level of nesting as the current statement. They all jump out one or more nesting (scope) levels and they all (apart from continue
) jump downwards. This restriction helps to avoid the goto "spaghetti code" syndrome inherent in old BASIC, FORTRAN and COBOL code2.
1- The most expensive part of exceptions is the actual creation of the exception object and its stacktrace. If you really, really need to use exception handling for "normal" flow control, you can either preallocate / reuse the exception object, or create a custom exception class that overrides the fillInStackTrace()
method. The downside is that the exception's printStackTrace()
methods won't give you useful information ... should you ever need to call them.
2 - The spaghetti code syndrome spawned the structured programming approach, where you limited in your use of the available language constructs. This could be applied to BASIC, Fortran and COBOL, but it required care and discipline. Getting rid of goto
entirely was a pragmatically better solution. If you keep it in a language, there is always some clown who will abuse it.
I know this is a very old thread but just incase someone like myself needs this solution but in VB.NET here's what I used base on the answers above.
Private Function ValidateUniquePayroll(PropertyToCheck As String) As Boolean
// Return true if Username is Unique
Dim rtnValue = False
Dim context = New CPMModel.CPMEntities
If (context.Employees.Any()) Then ' Check if there are "any" records in the Employee table
Dim employee = From c In context.Employees Select c.PayrollNumber ' Select just the PayrollNumber column to work with
For Each item As Object In employee ' Loop through each employee in the Employees entity
If (item = PropertyToCheck) Then ' Check if PayrollNumber in current row matches PropertyToCheck
// Found a match, throw exception and return False
rtnValue = False
Exit For
Else
// No matches, return True (Unique)
rtnValue = True
End If
Next
Else
// The is currently no employees in the person entity so return True (Unqiue)
rtnValue = True
End If
Return rtnValue
End Function
In my case, the error was in using angular2-notifications 0.9.8
instead of 0.9.7
I had this error, and I tried to fix for a while until I found the solution.
I made a private method buildRecyclerView, and I called it twice, first on onCreateView and then after my callback (in which I fetch data from an API). This is my method buildRecyclerView in my Fragment:
private void buildRecyclerView(View v) {
mRecyclerView = v.findViewById(R.id.recycler_view_loan);
mLayoutManager = new LinearLayoutManager(getActivity());
((LinearLayoutManager) mLayoutManager).setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new LoanAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
Besides, I have to modify the method get-Item-Count in my adapter, because On on-Create-View the list is null and it through an error. So, my get-Item-Count is the following:
@Override
public int getItemCount() {
try {
return mLoanList.size();
} catch (Exception ex){return 0;}
}
You can also use this script to figure out more info:
EXEC sp_server_info
The result will be something like that:
attribute_id | attribute_name | attribute_value
-------------|-----------------------|-----------------------------------
1 | DBMS_NAME | Microsoft SQL Server
2 | DBMS_VER | Microsoft SQL Server 2012 - 11.0.6020.0
10 | OWNER_TERM | owner
11 | TABLE_TERM | table
12 | MAX_OWNER_NAME_LENGTH | 128
13 | TABLE_LENGTH | 128
14 | MAX_QUAL_LENGTH | 128
15 | COLUMN_LENGTH | 128
16 | IDENTIFIER_CASE | MIXED
? ? ?
? ? ?
? ? ?
You can read it from the input stream:
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = new byte[model.File.ContentLength];
model.File.InputStream.Read(image, 0, image.Length);
// TODO: Do something with the byte array here
}
...
}
And if you intend to directly save the file to the disk you could use the model.File.SaveAs
method. You might find the following blog post useful.
this worked for me in laravel 5.4
$partnerProfileIds = DB::table('partner_profile_extras')->get()->pluck('partner_profile_id');
$partnerProfileIdsArray = $partnerProfileIds->all();
output
array:4 [?
0 => "8219c678-2d3e-11e8-a4a3-648099380678"
1 => "28459dcb-2d3f-11e8-a4a3-648099380678"
2 => "d5190f8e-2c31-11e8-8802-648099380678"
3 => "6d2845b6-2d3e-11e8-a4a3-648099380678"
]
The problem happened because I was trying to bind a HTML element before it was created.
My script was loaded on top of the HTML and it needs to be loaded at the bottom of my HTML code.
Follow these steps, respectively for rename column migration file.
1- Is there Doctrine/dbal library in your project. If you don't have run the command first
composer require doctrine/dbal
2- create update migration file for update old migration file. Warning (need to have the same name)
php artisan make:migration update_oldFileName_table
for example my old migration file name: create_users_table update file name should : update_users_table
3- update_oldNameFile_table.php
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});
'from' my old column name and 'to' my new column name
4- Finally run the migrate command
php artisan migrate
Source link: laravel document
Almost everywhere you look, people refer to the about:config and the security.fileuri.strict_origin_policy. Sometimes also the network.http.refere.XOriginPolicy.
For me, none of these seem to have any effect.
This comment implies there is no built-in way in Firefox to do this (as of 2/8/14).
You can use Caller Information and optional parameters:
public static string WhoseThere([CallerMemberName] string memberName = "")
{
return memberName;
}
This test illustrates this:
[Test]
public void Should_get_name_of_calling_method()
{
var methodName = CachingHelpers.WhoseThere();
Assert.That(methodName, Is.EqualTo("Should_get_name_of_calling_method"));
}
While the StackTrace works quite fast above and would not be a performance issue in most cases the Caller Information is much faster still. In a sample of 1000 iterations, I clocked it as 40 times faster.
Coming on this old thread i wanted to stress that
1°) utility functions may (should?) be added to the rootscope via module.run. There is no need to instanciate a specific root level controller for this purpose.
angular.module('myApp').run(function($rootScope){
$rootScope.isNotString = function(str) {
return (typeof str !== "string");
}
});
2°) If you organize your code into separate modules you should use angular services or factory and then inject them into the function passed to the run block, as follow:
angular.module('myApp').factory('myHelperMethods', function(){
return {
isNotString: function(str) {
return (typeof str !== 'string');
}
}
});
angular.module('myApp').run(function($rootScope, myHelperMethods){
$rootScope.helpers = myHelperMethods;
});
3°) My understanding is that in views, for most of the cases you need these helper functions to apply some kind of formatting to strings you display. What you need in this last case is to use angular filters
And if you have structured some low level helper methods into angular services or factory, just inject them within your filter constructor :
angular.module('myApp').filter('myFilter', function(myHelperMethods){
return function(aString){
if (myHelperMethods.isNotString(aString)){
return
}
else{
// something else
}
}
);
And in your view :
{{ aString | myFilter }}
The best way I found is using keydown
( the keyup
doesn't work well for me).
Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)
$('input').keydown( function( event ) {
if ( event.which === 13 ) {
// Do something
// Disable sending the related form
event.preventDefault();
return false;
}
});
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
It's because $bar is a public property.
$foo->bar = 'test';
There is no need to call the magic method when running the above.
Deleting public $bar;
from your class should correct this.
for those who want some official document to confirm the behavior
Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.
https://www.gnu.org/software/make/manual/html_node/Environment.html
inserting data form one table to another table in different DATABASE
insert into DocTypeGroup
Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType
from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup
-w
is the GCC-wide option to disable warning messages.
Ok found the answer. exchange()
is the best way. Oddly the HttpEntity
class doesn't have a setBody()
method (it has getBody()
), but it is still possible to set the request body, via the constructor.
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("field", "value");
// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);
ResponseEntity<MyModel> response = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);
public void breadthFirstSearch(Node root, Consumer<String> c) {
List<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.remove(0);
c.accept(n.value);
if (n.left != null)
queue.add(n.left);
if (n.right != null)
queue.add(n.right);
}
}
And the Node:
public static class Node {
String value;
Node left;
Node right;
public Node(final String value, final Node left, final Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
Store it either in a cookie (if it's acceptable for your situation), or in a session variable.
session_start();
if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];
I used the following with jQuery $("#submitForm").val("");
where submitForm
is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:
function extractValue() {
var value = $("#submitForm").val().trim();
console.log(value);
};
Also don't forget to include preventDefault();
method to stop the submit type form from refreshing your page!
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
_x000D_
They are simply called objects.
I think you are looking for UPDATE and not insert?
UPDATE `users`
SET `username` = 'Jack', `password` = '123'
WHERE `id` = 1
It's interesting that not a single answer mentioned parallel processing so far, where it might be REQUIRED that the imports are in the function, when the serialized function code is what is being pushed around to other cores, e.g. like in the case of ipyparallel.
I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.
Because of the adds and removes in arbitrary places on the list,
I went with the LinkedList
implementation.
/* traverses tree starting with given node */
private static List<Node> traverse(Node n)
{
return traverse(Arrays.asList(n));
}
/* traverses tree starting with given nodes */
private static List<Node> traverse(List<Node> nodes)
{
List<Node> open = new LinkedList<Node>(nodes);
List<Node> visited = new LinkedList<Node>();
ListIterator<Node> it = open.listIterator();
while (it.hasNext() || it.hasPrevious())
{
Node unvisited;
if (it.hasNext())
unvisited = it.next();
else
unvisited = it.previous();
it.remove();
List<Node> children = getChildren(unvisited);
for (Node child : children)
it.add(child);
visited.add(unvisited);
}
return visited;
}
private static List<Node> getChildren(Node n)
{
List<Node> children = asList(n.getChildNodes());
Iterator<Node> it = children.iterator();
while (it.hasNext())
if (it.next().getNodeType() != Node.ELEMENT_NODE)
it.remove();
return children;
}
private static List<Node> asList(NodeList nodes)
{
List<Node> list = new ArrayList<Node>(nodes.getLength());
for (int i = 0, l = nodes.getLength(); i < l; i++)
list.add(nodes.item(i));
return list;
}
You need the key in dict
idiom for that.
if key in my_dict and not (my_dict[key] is None):
# do something
else:
# do something else
However, you should probably consider using defaultdict
(as dF suggested).
I came across this problem today and solved it with:
SET LOGTIME=%TIME: =0%
It replaces spaces with 0s and basically zero-pads the hour.
After some quick searching I didn't find out if it required command extensions (still worked with SETLOCAL DISABLEEXTENSIONS).
Building on the answer given above with the single line Tree using defaultdict, you can make it a class. This will allow you to set up defaults in a constructor and build on it in other ways.
class Tree(defaultdict):
def __call__(self):
return Tree(self)
def __init__(self, parent):
self.parent = parent
self.default_factory = self
This example allows you to make a back reference so that each node can refer to its parent in the tree.
>>> t = Tree(None)
>>> t[0][1][2] = 3
>>> t
defaultdict(defaultdict(..., {...}), {0: defaultdict(defaultdict(..., {...}), {1: defaultdict(defaultdict(..., {...}), {2: 3})})})
>>> t[0][1].parent
defaultdict(defaultdict(..., {...}), {1: defaultdict(defaultdict(..., {...}), {2: 3})})
>>> t2 = t[0][1]
>>> t2
defaultdict(defaultdict(..., {...}), {2: 3})
>>> t2[2]
3
Next, you could even override __setattr__ on class Tree so that when reassigning the parent, it removes it as a child from that parent. Lots of cool stuff with this pattern.
There is no collision in your example. You use the same key, so the old value gets replaced with the new one. Now, if you used two keys that map to the same hash code, then you'd have a collision. But even in that case, HashMap would replace your value! If you want the values to be chained in case of a collision, you have to do it yourself, e.g. by using a list as a value.
This will return specifically what you are asking.
Dim mySiteUrl = Request.Url.Host.ToString()
I know this is an older question. But I needed the same simple answer and this returns exactly what is asked (without the http://).
Try this:
DELIMITER $$
CREATE TRIGGER occupy_trig
AFTER INSERT ON `OccupiedRoom` FOR EACH ROW
begin
DECLARE id_exists Boolean;
-- Check BookingRequest table
SELECT 1
INTO @id_exists
FROM BookingRequest
WHERE BookingRequest.idRequest= NEW.idRequest;
IF @id_exists = 1
THEN
UPDATE BookingRequest
SET status = '1'
WHERE idRequest = NEW.idRequest;
END IF;
END;
$$
DELIMITER ;
You are using getData() method as void.
You can not return values from void.
For Writing Excel
For Reading Excel
A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.
All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.
You can activate JVM's debugging capability when starting up the java
command with a special option:
java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar
Starting up jar.jar
like that on the command line will:
server=y
) listening on port 8000 (address=8000
)Listening for transport dt_socket at address: 8000
to stdout
andsuspend=y
) until some debugger connects. The debugger acts as the client in this scenario.Common options for selecting a debugger are:
jar.jar
should begin executing.jdb -connect com.sun.jdi.SocketAttach:port=8000
In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:
On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.