text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Codeigniter's URL Rewriting
I'm using the following htaccess script so that I can hide index.php from the URI.
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|assets|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
But I'm facing a major problem :(
I have a directory named assets beside my index.php file and it should be there. When I browse the directory by browser, then Codeigniter’s not found page displays. I can't browse the file /assets/image.jpg but it displays when I call it from an <img> tag
What can I do now?
Note that it is working in my local server (localhost) but not in the live server.
A:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*)$ /index.php/$1 [NC,L]
That'll pass any request that Apache wouldn't serve off to CodeIgniter. This way you're free to create directories all over without updating your rewrite rules, and you don't need to setup 404 handling in Apache (even inside your image/resource directories).
Credit goes to the Zend Framework authors that recommend this bit in their user guide. This version is slightly modified for CodeIgniter.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to merge rows with the same rowname into one
I have the dataframe below:
product<-c("ab","ab","ab","ac","ac")
HD<-c("12","","","","")
HS<-c("","23","","","")
HR<-c("","","34","","")
HO<-c("","","","23","")
DF<-c("","","","","24")
store22<-data.frame(product,HD,HS,HR,HO,DF)
product HD HS HR HO DF
1 ab 12
2 ab 23
3 ab 34
4 ac 23
5 ac 24
I would likr to transform it in a way that I will keep only the unique values of the product and as a result bring the values in the same line like this:
product HD HS HR HO DF
1 ab 12 23 34
2 ac 23 24
A:
We can use max on character variables:
library(dplyr)
store22 %>%
group_by(product) %>%
summarize_all(~max(as.character(.)))
Output:
# A tibble: 2 x 6
product HD HS HR HO DF
<fct> <chr> <chr> <chr> <chr> <chr>
1 ab 12 23 34 "" ""
2 ac "" "" "" 23 24
| {
"pile_set_name": "StackExchange"
} |
Q:
Struts2 and Comet url pattern conflict
I am trying to integrate comet chat into my struts2+hibernate application .First I have tested comet chat in separate web application. It works fine .Ihave download it from http://skillshared.blogspot.in/2012/10/facebook-similar-chat-for-your-java-web.html after then I try to implement in my application
My problem in web.xml here is my web.xml file
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
<display-name>Cometd Test WebApp</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Portability Filter, needed only to run on non Jetty
or non Servlet-3.0 containers like Tomcat-->
<filter>
<filter-name>continuation</filter-name>
<filter-class>org.eclipse.jetty.continuation.ContinuationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>continuation</filter-name>
<url-pattern>/cometd/*</url-pattern>
</filter-mapping>
<!-- Cometd Servlet -->
<servlet>
<servlet-name>cometd</servlet-name>
<servlet-class>org.cometd.annotation.AnnotationCometdServlet</servlet-class>
<init-param>
<param-name>timeout</param-name>
<param-value>20000</param-value>
</init-param>
<init-param>
<param-name>interval</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>maxInterval</param-name>
<param-value>10000</param-value>
</init-param>
<init-param>
<param-name>maxLazyTimeout</param-name>
<param-value>5000</param-value>
</init-param>
<init-param>
<param-name>long-polling.multiSessionInterval</param-name>
<param-value>2000</param-value>
</init-param>
<init-param>
<param-name>logLevel</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>transports</param-name>
<param-value>org.cometd.websocket.server.WebSocketTransport</param-value>
</init-param>
<init-param>
<param-name>services</param-name>
<param-value>com.semika.cometd.ChatService</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cometd</servlet-name>
<url-pattern>/cometd/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
from above code application works fine but chat not working. I saw so posts regarding this problem , I have a solution
<URL-pattern>*.action</URL-pattern>
when I am trying to do this chat works fine but application doesn't work. When I have place application only working.
<url-pattern>/*</url-pattern>
I have tried this one also in struts.xml but no use.
<constant name="struts.action.excludePattern" value="/cometd/*,/cometd/.*"/>
What can be the cause of the problem ?
A:
The whole thing depends on your Struts version. If you have an old version, you should migrate to a new version for many reasons, especially security fixes.
However, considering that:
With Struts >= 2.1.3, the FilterDispatcher is deprecated, and the new StrutsPrepareAndExecuteFilter must be used. Read more
With Struts <= 2.1.6, the struts.action.excludePattern doesn't exist. Read more
your code can't possibly work ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I escape formatting characters in Slack?
Slack uses various characters for its own markdown formatting.
How can I enter a message with those reserved characters escaped?
e.g. Is it possible to send a message exactly like this:
*I don't want this to be bold*
A:
Solution
Copy and paste the text below and change the word in the asterisks for your own needs:
*bold*
It will not be rendered as bold text when you post your Slack message. Note: There are hidden characters either side of the asterisks which will prevent Slack from formatting your word(s) between the asterisks.
Explanation
This is a variation of ShaneB's answer that seems to work better. Instead of adding (invisible) space to the asterisk's "attached" side:
There is *|no|* spoon // '|' = vertical tab
consider removing space on the "detached" side by inserting (invisible) non-space:
There is |*no*| spoon // '|' = e.g. soft hyphen (­, U+00AD)
This "embeds" the asterisk and thus renders it inactive. Soft hyphen seems like a good character here.
A:
For the current WYSIWYG editor, hit Ctrl+Z immediately after conversion happened. For example:
abc *def* ghi
will result in
abc def ghi
On the other hand,
abc *def*<CTRL+Z> ghi
will result in
abc *def* ghi
This works for formatting only, not for Slack Emojis.
A:
I just tested and a single back-tick will escape upcoming formatting characters for the rest of the message.
`*I don't want this to be bold*`
That will be formatted as code
`*I don't want this to be bold*
That will be formatted normally but both asterisks will appear instead of making the text bold.
| {
"pile_set_name": "StackExchange"
} |
Q:
Access Properties in Javascript
In use of the qooxdoo framework, in a class:
(in the .xml file activeRow is defined as an object_iterate: )
<object_literal name="activeRow" scope="static" constructor="false" deprecated="false" private="false" protected="false" ignored="true" internal="false" type="Object">
<property name="nullable" scope="static" constructor="false" deprecated="false" private="false" protected="false" ignored="true" internal="false" type="Boolean">
</property>
<property name="check" scope="static" constructor="false" deprecated="false" private="false" protected="false" ignored="true" internal="false" type="String">
</property>
</object_literal>
this DOES work:
properties: {
activeRow: {
nullable: true,
check: "Object"
},
...
this.setActiveRow(123);
var x = this.getActiveRow();
this DOES NOT work:
properties: {
activeRow: {
nullable: true,
check: "Object",
init: {test1: null, test2: null}
},
...
this.setActiveRow({test1: 123, test2: 123 });
var y = this.getActiveRow().test1;
Does anyone know which part of the syntax is wrong?
Thank you in advance!
Addition containing discussion below:
alert(typeof this.getActiveRow); returns: function
alert(this.getActiveRow);
returns:
function(){
return qx.core.Property.executeOptimizedGetter(this, bI, name, "get");
}
A:
Take a look at this more complete Playground example (where you can also experiment with the code). Here is the code itself:
qx.Class.define("Foo", {
extend: qx.core.Object,
properties: {
activeRow: {
nullable : true,
check: "Object"
},
activeRowInit: {
nullable : true,
check: "Object",
init: {test1: null, test2: null}
}
},
members : {
setAndGet : function () {
this.setActiveRow({a:1,b:2});
/*this.setActiveRow(123);*/
var x = this.getActiveRow();
return x;
},
setAndGetMember : function () {
this.setActiveRowInit({test1: 123, test2: 123 });
var y = this.getActiveRowInit().test1;
return y;
}
}
});
var f = new Foo();
alert(f.setAndGet());
alert(f.setAndGetMember());
It captures your code snippets, with a property with and one without 'init', and with getting the whole property, or just a member of the property's object. For me, it all works as expected. If you use this.setActiveRow(123) in the "setAndGet" method, you get a reasonable error message saying something like "expected value of type object but got 123" (in the log pane).
| {
"pile_set_name": "StackExchange"
} |
Q:
Why am I receiving an error when I try to sum multiple columns in pandas dataframe?
df=pd.read_excel('Canada.xlsx',sheet_name='Canada by Citizenship',skiprows=range(20),skipfooter=2)
df['Total']=df.iloc[:,'1980':'2013'].sum(axis=1)
Here is the error I received:
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [1980] of <class 'str'>
I received the dataset from this link
A:
The columns are integers. You can slice with:
df.loc[:, range(1980, 2014)].sum(1)
# or
df.iloc[:, df.columns.get_loc(1980):df.columns.get_loc(2013)+1].sum(1)
0 58639
1 15699
2 69439
3 6
4 15
...
190 97146
191 2
192 2985
193 1677
194 8598
Length: 195, dtype: int64
| {
"pile_set_name": "StackExchange"
} |
Q:
reversing scale colour gradient in ggplot2 in R?
I am using ggplot2's scale_colour_gradient2 to have a color gradient scale for numbers from 1 to 20 using:
geom_line(aes(x=x, y=y, colour=c)) +
scale_colour_gradient2(lims=c(1, 20), high="red", low="grey")
The problem is that this puts value at 1 as white, and values at 20 as red, and I'd like to reverse this (smaller values in the c column for colour are more red than higher values. How can I do this? If I reverse low and high in scale_colour_gradient2 it just gives a purpose gradient which is not what I intended. thanks.
A:
Try:
scale_colour_gradient(low = "red", high = "white")
scale_colour_gradient2 is for a symmetrical gradient.
| {
"pile_set_name": "StackExchange"
} |
Q:
Travis CI Fails to Build with a Code Signing Error
Travis CI fails to build my app because the Xcode project is set up to require code signing and Travis doesn't have my certificates. I could fix this by disabling code signing, but then sandboxing and entitlements won't work. I know when building from the command line ordinarily, you can pass CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO to xcodebuild to disable the code signing, but how do you do this in Travis CI?
Here's my .travis.yml:
language: objective-c
xcode_workspace: "Mac Linux USB Loader.xcworkspace"
xcode_scheme: "Mac Linux USB Loader"
And here's the error (I've code out many previous lines referring to Cocoapods, as they're not relevant:
Check dependencies
Code Sign error: No code signing identities found: No valid signing identities (i.e. certificate and private key pair) matching the team ID “T47PR9EQY5” were found.
A:
Did you try to add this on you travis.yml:
language: objective-c
script:
- xcodebuild [DEFAULT_OPTIONS] CODE_SIGNING_REQUIRED=NO
Or import a development (and distribution if you are going to use on your build) cert/key to the keychain and copy your team provisioning profile, to make the code signing work. Like this:
language: objective-c
before_script:
- ./scripts/add-key.sh
script:
- xcodebuild [DEFAULT_OPTIONS] CODE_SIGNING_REQUIRED=NO
add-key.sh
#!/bin/sh
KEY_CHAIN=ios-build.keychain
security create-keychain -p travis $KEY_CHAIN
# Make the keychain the default so identities are found
security default-keychain -s $KEY_CHAIN
# Unlock the keychain
security unlock-keychain -p travis $KEY_CHAIN
# Set keychain locking timeout to 3600 seconds
security set-keychain-settings -t 3600 -u $KEY_CHAIN
# Add certificates to keychain and allow codesign to access them
security import ./scripts/certs/dist.cer -k $KEY_CHAIN -T /usr/bin/codesign
security import ./scripts/certs/dev.cer -k $KEY_CHAIN -T /usr/bin/codesign
security import ./scripts/certs/dist.p12 -k $KEY_CHAIN -P DISTRIBUTION_KEY_PASSWORD -T /usr/bin/codesign
security import ./scripts/certs/dev.p12 -k $KEY_CHAIN -P DEVELOPMENT_KEY_PASSWORD -T /usr/bin/codesign
echo "list keychains: "
security list-keychains
echo " ****** "
echo "find indentities keychains: "
security find-identity -p codesigning ~/Library/Keychains/ios-build.keychain
echo " ****** "
# Put the provisioning profile in place
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
cp "./scripts/profiles/iOSTeam_Provisioning_Profile_.mobileprovision" ~/Library/MobileDevice/Provisioning\ Profiles/
cp "./scripts/profiles/DISTRIBUTION_PROFILE_NAME.mobileprovision" ~/Library/MobileDevice/Provisioning\ Profiles/
A:
Please find my .travis.yml file below, which fixes this error message and others, when using an Xcode 7 project + Swift + iOS 9 + the continuous integration tool available on travis-ci.org:
# http://docs.travis-ci.com/user/languages/objective-c/
# https://github.com/facebook/xctool
language: objective-c
osx_image: xcode7
# xcode_project: SampleNotifcations/SampleNotifcations.xcodeproj
# xcode_workspace: SampleNotifcations/SampleNotifcations.xcworkspace
# xcode_scheme: SampleNotifcationsTests
podfile: SampleNotifcations/Podfile
# xcode_sdk: iphonesimulator9.0
script:
xctool
-workspace SampleNotifcations/SampleNotifcations.xcworkspace
-scheme SampleNotifcationsTests
-sdk iphonesimulator
-destination 'platform=iOS Simulator,name=iPhone 6 Plus'
build
test
ONLY_ACTIVE_ARCH=NO
CODE_SIGN_IDENTITY=""
CODE_SIGNING_REQUIRED=NO
before_install:
- brew update
- brew uninstall xctool && brew install --HEAD xctool
Sources:
XCTool issue where people talk about that and where a solution is given at the end of the page.
See Travis CI fix for an example.
A:
If you don't need to build for iphoneos, e.g. if you just want to know if the project builds or your unit tests pass. You can specify the iphonesimulator sdk. By doing this, xctool will not sign the code.
script: xctool -sdk iphonesimulator -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} build test
| {
"pile_set_name": "StackExchange"
} |
Q:
What is intrinsic in Capitalism which leads to accumulation of wealth with a minority?
I know this is a broad question some would recommend me reading Marx or other critics of capitalism to find the answer. But my question is, in almost all western world, there are left wing entities in government which try to 'amend' the system but despite all those measures by 'left wing' entities (consider these left entities as spectrum from center left to extreme left), one thing in which systems in western nations have failed miserably i.e. stop the accumulation of wealth. Yes, the quality of life of ordinary man has gone better as compared to one century before, but from Korea to US, Germany to Australia, gap between rich and poor is getting wider and wider. I want to ask, is this polarization of wealth a natural corollary of capitalism? If yes then what is that thing which despite 'measures' by center-left/socialist/left parties - this problem- instead of receding, is getting worse and worse?
A:
Very roughly, a Marxist viewpoint would hold that inequality is intrinsic to capitalism since capitalism is a system in which the means of production are privately owned and are used to make profits for their owners. Profits derive from selling the products of labour, employed to operate the means of production, at a higher price than is paid to that labour : this is the extraction of surplus value. A far more refined and nuanced statement is possible and I leave this to others. What I want to suggest here, basing myself on the work of Geoffrey Hughes, is that there are sources of inequality in capitalism, turning on 'complexity', which apply independently of a Marxist analysis.
Capitalism, complexity, and inequality
Capitalism is a social formation in which markets and commodity production are
pervasive, including capital markets and labor markets. ... Its driving logic involves the expansion and diversification of multiple markets. As it expands, corporations seek ever-new opportunities
for trade and gain. As competition intensifies within particular markets, profit-seeking
corporations innovate and diversify their products in unceasing creation of new market
niches (Chamberlin 1933; Rueschemeyer 1986). The competitive pursuit of profit pressures firms to invest in new technology or new skills. In this quest for innovation, the
frontiers of science and technology are advanced, leading to new fields of knowledge
and enquiry. Services are generally more diverse than manufactured goods; hence,
diversity also increases with the increasing relative size of the service sector. New and varied organizational forms are devised to increase productivity and to manage an
exponentially expanding number of products and processes.
Accordingly, there is a long-run tendency in capitalist economic systems toward
greater complexity, driven by powerful economic forces and leading to the widening of markets and greater product diversification (Warsh 1985). There are several meanings
of complexity and the definition of complexity is problematic (Pryor 1996; Rosser
199-9), but we can make an outline attempt. Complexity is not the same as variety
(Saviotti 1996). Variety refers to a diversity of types. Complexity exists only when such
variety exists within a structured system. In short, complexity in the sense used here is
systemically interconnected and interactive variety. By this definition, increasing economic
complexity means a growing diversity of interactions between human beings and
between people and their technology...
The increasing diversity of products and tasks, along with the growing sophistication of knowledge, is likely to be paralleled with an increasing variety of skills and occupations. As complexity grows within the economic system, it is likely that there will be demands for higher and higher levels of skill in particular specialisms. New specialisms
emerge to deal with the multiplying facets of the increasingly complex capitalist system.
Workers with advanced and transferable skills, and with enhanced capacities to rapidly
learn and adapt, are more and more at a premium. We have a scenario of enhanced
skills and growing knowledge intensity.
Some skills and professions will become obsolete. At the same time, for each individual worker, it becomes more difficult and costly to transfer readily from one specialism to another. A skills escalator can emerge, where frequent retraining is required to
relocate in the more skilled and more highly remunerative jobs. Retraining is easier and
less risky for those that already have acquired high skill levels. Without remedial policies
and subsidies, some may never get onto the skills escalator. A further widening of inequality can result. (Geoffrey M. Hodgson, 'Capitalism, Complexity, and Inequality', Journal of Economic Issues, Vol. 37, No. 2 (Jun., 2003), pp. 471-478 : 471-2, 474-5.)
Introducing increasing complexity into the picture fits both with Marxist analysis and with an explanation independent of Marxism.
References
Chamberlin, Edward H. The Theory of Monopolistic Competition. Cambridge, Mass.: Harvard University Press, 1933.
Hodgson, Geoffrey M. 'Capitalism, Complexity, and Inequality', Journal of Economic Issues, Vol. 37, No. 2 (Jun., 2003), pp. 471-478.
Pryor, Frederic L. Economic Evolution and Structure: The Impact of Complexity on the U.S. Economic System. Cambridge and New York: Cambridge University Press, 1996.
Pryor, Frederic L., and David L. Schafer. Who's Not Working and Why. Cambridge: Cambridge UniveTsity Press, 1999.
Rosser, J. Barkley, Jr. "On the Complexities of Complex Economic Dynamics." Journal of Economic Perspectives, 13, no. 4 (fall 1999): 169-192.
Rueschemeyer, Dietrich. Power and the Division of Labor. Stanford, Calif.: Stanford University Press, 1986.
Saviotti, Pier Paolo. Technological Evolution, Variety, and the Economy. Aldershot, U.K.: Edward Elgar, 1996.
A:
If you don't want to read my long-winded response, here's a summary:
Instead of searching for a problem that's intrinsic in capitalism, look for something that is NOT intrinsic in capitalism, namely 1) a moral foundation, and 2) a system of checks and balances.
The key word here is power. The acquisition and use of power is what politics is all about, and money is one of the most potent forms of power.
In this spirit, consider the maxim "Power corrupts, and absolute power corrupts absolutely."
Though it might not be considered a scientific principle, there's a lot of truth in those words.
To further put it in perspective, consider historical patterns. People have been waging war and political intrigue for thousands of years in order to create city states, kingdoms and empires. Forever, those empires have been generally getting bigger, from the Greek empire to the Roman empire, which was exceeded by the European colonial empires, now replaced by the United States' de facto empire.
Of course, control of the global economy is an important keystone of the U.S. empire.
Capitalism can be thought of as a tool that helps the rich become richer, and they generally become richer by exploiting everyone else.
Narrowing the focus to "what is intrinsic in capitalism" is a little more difficult. There are apparently just two major economic systems today - capitalism and socialism.
It could be argued that socialism is by design a moral system. That is, its creators intended for it to impart some fairness to economic systems. But whether or not it actually works depends on the state. It could be judged successful in Cuba and Libya, but it was a different story in the Soviet Union.
In contract, there's nothing inherently moral about capitalism. That doesn't necessarily make it "evil." One could argue that it's simply a tool, similar to a hammer - a neutral system that's no better than the state or regime it serves.
So rather than searching for something intrinsic in capitalism, we might instead search for something that is NOT intrinsic in capitalism. That something could actually be described as two things: a lack of a moral foundation, and a lack of checks and balances.
People with more wealth than others are obviously going to have more power, and a lack of checks and balances (e.g. regulation) will obviously make it easier of them to get still richer.
One note...
You refer to the inability of "left wing" entities to fix the problem. Historically, those in power have been very good at maintaining their power. It is simply very hard for dissidents to reform the system.
But it's also important to note that many apparent left wing entities aren't really left wing. Rather, they're examples of "controlled opposition." In plain English, they're actors, pretending to be left wing.
I live in Seattle, one of America's most famously liberal/progressive cities. I've been politically active for two decades, and I don't think I've ever met a genuine socialist or reformer in this city. In fact, the lack of true left wingers is so extreme, it almost defies belief.
Also, your assertion that the lives of ordinary citizens have improved is debatable. Technology has given us the printing press, electricity and hot running water and other cool things, but that technology was hardly dependent on capitalism. There's also a flip side to technology (e.g. global warming).
In fact, there are millions, if not billions, of people who are living in grinding poverty (not to mention human rights abuses) in countries exploited by the U.S. and its allies. Moreover, the quality of life will only continue to decline as the rich get richer, the global population grows, resources dwindle, etc., etc.
EDIT
Let's also remember that wealth was concentrated among minorities long before the birth of capitalism. Again, this tends to discredit the notion that there's something "intrinsic" in capitalism that makes the richer richer.
Rather, capitalism does nothing to discourage the greed and accumulation of power that appear to be an integral part of humanity.
| {
"pile_set_name": "StackExchange"
} |
Q:
Не получается придать ID объекту, прежде чем загнать его в Local Storage
Здравствуйте, я учу JS сейчас наткнулся на проблему, которую не могу решить. Надеюсь на помощь + объяснения или ссылку на обучающий материал.
спасибо.
Из полей в HTML получаем данные и загоняем их в переменные a,b,c
после этого данные загоняются в объект и объект уходит в local Storage
для того что бы различать объекты в Storage, мне нужно придать каждому следующему свой ID. ID я получаю, он динамический, но привязать его к объекту у меня не получается. в чем ошибка?
var notesData = {
text: c,
date: a,
time: b
}
notesData.setAttribute("ID", newMemberID);
localStorage.setItem('notesData', JSON.stringify(notesData));
var retrievedObject = localStorage.getItem('notesData');
console.log('retrievedObject: ', JSON.parse(retrievedObject));`
A:
В JS свойство к объекту добавляется не так. Свойства добавляются следующим образом:
myObject.key = value
или
myObject['key'] = value
В вашем случае можно записать так:
notesData["ID"] = newMemberID;
Функция "setAttribute" - задает атрибут DOM элементу.
Прочитать подробнее про объекты и DOM можете тут и тут
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom UITableViewCell in edit mode does not move my UILabels
This is doing my head in:-)
I have a fully functional CoreData Populated UITableView inside a UIViewController and I have successfully implemented the "Swipe to Delete option" (which is easy) and I can also delete single instances with an edit button where the red circle thingy comes up.
My problem is, and I think it is because I have a CustomCell, that when I press the edit button the UILabels do not move to the right.
I have tried using -(void)layoutSubViews and a few others, but nothing works.
I have posted my code for my cellForRowAtIndexPath. This is part of a note section in my app. This code works, I just need to know How to move the labels when I go into Edit mode??
Thank you for the tips and advice:-)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
MNCustomCell *cell = [_mainTableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[MNCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//cell.textLabel.text = [_tableArray objectAtIndex:indexPath.row];
MNotes *mnotes = [[self fetchedResultsController] objectAtIndexPath:indexPath];
cell.noteTitle.text = mnotes.noteTitleString;
cell.noteSummary.text = mnotes.mainNoteString;
mnotes.createDate = [[NSDate alloc] init];
SORelativeDateTransformer *relativeDateTransformer = [[SORelativeDateTransformer alloc] init];
NSString *relativeDate = [relativeDateTransformer transformedValue:mnotes.createDate];
cell.noteDate.text = relativeDate;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-
//This is the Custom Cell
@interface MNCustomCell : UITableViewCell
{
}
@property (strong, nonatomic) IBOutlet UILabel *noteTitle;
@property (strong, nonatomic) IBOutlet UILabel *noteDate;
@property (strong, nonatomic) IBOutlet UITextView *noteSummary;
@end
-
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self.contentView addSubview:_noteTitle];
[self.contentView addSubview:_noteSummary];
[self.contentView addSubview:_noteDate];
}
return self;
}
A:
The other solution will probably work but this way will do the animation automatically for you.
MNCustomCell is not going to re-layout the view depending on the current state of the cell, but if you add your label to the contentView of the cell, it will.
The following example will move the label so it doesn't interfere with the delete button.
MNCustomCell.m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)]];
mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:mainLabel];
| {
"pile_set_name": "StackExchange"
} |
Q:
Approximation of $T10$ for integral $\int_0^1\sin(x^2) dx$ Trapezoid Approximation
I got through most of the work with finding the approximation of $T10$ which comes out to be $=.3111708111$, I also found the error of $Et10$ when I plugged into the formula of $K(b-a)^3/12(n)^2$ . My question is how do i find the smallest value of $n$ so that the approximation of $Tn$ is accurate to within $0.00001$? Thank You
A:
Since you have an upper bound for the error $E\leq\frac{K(b-a)^3}{12n^2}$, and you desire $E<10^{-5}$, you can ensure this is true by making
$$
\frac{K(b-a)^3}{12n^2}<10^{-5}.
$$
You now need to solve this inequality for $n$.
The solution is $\displaystyle n>\sqrt{\frac{K(b-a)^3}{12\times10^{-5}}}$ and you can substitute in the appropriate values for $K$, $a$ and $b$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Iterating and executing Awk function over multiple input files and producing different output files
I have hundreds of large text files as test1, test2, test3, ....., test100 in a folder.
Each of these test files has text entries. My job is to read each text file and then split each test$i files on every blank line in each text files and create various new text files.
For example: If test1.txt has 3 blank lines then the number of files generated will be 4 text files with names of each new files as test1.1, test1.2, test1.3, test1.4 { Reference = Splitting large text file on every blank line}
I did this for a single file and it perfectly works and I get various files as test1.1, test1.2, test1.3, test1.4
awk -v RS= '{print > ("test1." NR ".txt")}' test1
But when I tried doing this for multiple files in loop,
for i in {1..100}; do awk -v RS= '{print > ("test" $i "." NR ".txt")}' test$i; done
It does not work. I am wondering, why the values of $i does not passes into the awk function and it does not print the different empty separated individual files as test1.1, test1.2, test1.3...... test2.1, test2.2 ... so on...
One issue, which I am seeing is: "File name too long".
Reference Link: Limit on file name length in bash
Kindly help me to understand and fix it or some better approach for this task.
A:
Using awk only:
$ awk -v RS= '{f=(FILENAME "." FNR ".txt"); print > f; close(f)}' test*
| {
"pile_set_name": "StackExchange"
} |
Q:
How to move control with keyboard only in Interface Builder
I'm accessing my Mac remotely with TeamViewer. I can't seem to be able to move a control with the mouse only.
What are the keyboard combinations to do so?
A:
Double click on your object in the sidebar and use the arrow keys.
To move faster, hold the shift key.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add more than one space in a string
I would like to add more than one space to a string in a shell script, but apparently only one is added. Here is what I've tried:
$ abc="string"
$ abc=$abc" at 2 spaces"
$ echo $abc
string at 2 spaces
How can I add those 2 spaces to my string so that they won't be trimmed?
A:
You need to quote when echoing:
echo "$abc"
See another example:
$ abc="he llo"
$ echo "$abc"
he llo
$ echo $abc
he llo
| {
"pile_set_name": "StackExchange"
} |
Q:
What are recommendable GIF screencast recorders?
Asking out of curiosity, I seek alternatives to Peek to directly record a screencast in a .gif format.
Are there other software that run well on Ubuntu 16.x that you can recommend me to take a look at?
A:
There is a command line tool called byzanz available in the official Ubuntu universe repository :
byzanz:
Installed: (none)
Candidate: 0.3.0+git20160107-1
Version table:
0.3.0+git20160107-1 500
500 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages
To install byzanz, just open a terminal and execute this command : sudo apt install byzanz
byzanz-record is a desktop recorder tool, which allows you to record the current desktop or parts of it to an animated GIF. Here are the instructions and application options from the Ubuntu Wiki how to use the tool : Creating Screencasts - Making a GIF screencast
| {
"pile_set_name": "StackExchange"
} |
Q:
Do philosophers recognize a deeper problem behind issues like the Problem of the Criterion or the Munchausen Trilemma?
First off, I would like to make it clear that I'm not implying I discovered some secret knowledge about the problems mentioned in the title that has alluded other philosophers for the past 2000+ years. I'm merely asking if a problem that I see is recognized as a genuine problem if I'm misguided. Because it seems the more research I do, no one even raises the concern.
Anyway, here's my question: From the philosophical pondering I've done, it seems that fascinating, epistemological, and related issues like the Problem of the Criterion and the Munchausen Trilemma concerning theories or justification are really hard to answer, at least in a satisfactory manner. Why? Because to even begun answering the issues, you have to assume you have a solution.
For the Problem of the Criterion, you have to assume you have knowledge that logical principals work in order to argue for a certain view, when whether or not we have knowledge of logical principals is under question. How else would you even begin offering an argument against skepticism? A similar paradoxical issues can be raised when trying to answer the Munchausen Trilemma.
Please note careful what I'm asking here. I'm not asking whether a particular answer to the issues mention above is correct. I don't mind researching answers myself, that I can do. My problem arises when in the process of doing this research, it strikes me as pretty weird that it seems no one in the literature acknowledges how were suppose to even begin debating solutions, without assuming we have an answer.
Of course, my problem could simply be my ignorance. Maybe someone has raised this concern and at least has acknowledged it or tried to address it. Maybe my concern is misplaced and I don't understand something. Either way, I would be grateful if someone could answer my question.
A:
I think you're puzzled, because you're specifically applying the Munchaussen trilemma to justifying the laws of logic. I don't think that's usually the target of philosophers when talking about "justification".
I think most philosophers are foundationalist about logic, because as you said, to even state the trilemma, you need to make use of logic.
There are philosophers questioning the laws of logic, but I'm not sure it's being done in the context of the Munchaussen trilemma. Regardless, the same problem appears... how do you make any argument without reinforcing the laws of logic?
I'm certain philosophers know about the seemingly self-refuting nature of these kinds of arguments, but just seem to carry on. It's very common in philosophhy of language and mind. I see the same type of issue with regards to eliminative materialism or meaning-skepticism. Philosophers ask "what is the meaning of meaning?"... doesn't the very act of asking the question show that you already know what it is?
I'm not sure how you get around it. You want to question your conceptual apparatus... but to question it you have no choice but to employ that very same conceptual apparatus. We're stuck.
| {
"pile_set_name": "StackExchange"
} |
Q:
Все приложение только портретной ориентации и последний экран только ландшафт
Все приложение только портретной ориентации и последний экран только ландшафт? как реализовать ландшафт(xcode)
A:
Вот мой ответ на stackoverflow, как раз то, что вы ищете:
Portrait orientation in all view controllers except in modal view controller
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding a file in Vb.net and UnauthorizedAccessException problems
I am trying to search a drive letter (C drive) for a file in Vb.Net 2010. After I find the file path I want to run the executable. This is the code I am trying to use to find the file:
path = Convert.ToString(IO.Directory.GetFiles("C:\", "wswc.exe", System.IO.SearchOption.AllDirectories))
This throws an UnauthorizedAccessException when my code tries to search a recycle bin (or some other file that I don't have access to) and I have searched the internet and people have suggested to use Try...Catch...End Try but this will not work for me since I am not using a loop and I don't know how to change my code to function as a loop. I have seen where is was suggested to use the GetAccessControl method to test for permissions before searching the directory but I was not sure how use use it with my current code.
I have not been able to test the Convert.ToString(...) because of the UnauthorizedAccessException so if there is something wrong with this or any of the rest of the code please let me know.
I am fairly new to VB.Net so try to keep your explanation simple.
Thank you.
A:
try to see this thread
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvb/thread/255be857-9d1e-4c80-9ae2-5c8b48697943/
Regards.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I debug code running in a delayed_job task in the IRB console?
I have a background task that runs using delayed_job.
I can see that it does run from the logging statements. It does not seem to have the correct result, compared to running it in the foreground, so I want to debug it in the IRB console.
I am running the background task with
rake jobs:work
and it does not trigger the debugger statement.
How can I load the debugger?
A:
Start a standard rails console
ruby script/console
And start a worker inside here, this will see and trigger the debugger statement.
worker = Delayed::Worker.new
worker.start
A:
I use pry as my console and remote debugger. Pry website here, Pry rails gem here. In your code, you add binding.pry statements to have your app stop executing and open the console. It works the same with delayed_job as it does with your rails app. Make sure you are running delayed_job in the foreground though, so it is still attached to the terminal. E.g., start delayed_job with:
rake jobs:work
| {
"pile_set_name": "StackExchange"
} |
Q:
python multiple inputs and multiple outputs
I have written a script in python, which works on a single file. I couldn't find an answer to make it run on multiple files and to give output for each file separately.
out = open('/home/directory/a.out','w')
infile = open('/home/directory/a.sam','r')
for line in infile:
if not line.startswith('@'):
samlist = line.strip().split()
if 'I' or 'D' in samlist[5]:
match = re.findall(r'(\d+)I', samlist[5]) # remember to chang I and D here aswell
intlist = [int(x) for x in match]
## if len(intlist) < 10:
for indel in intlist:
if indel >= 10:
## print indel
###intlist contains lengths of insertions in for each read
#print intlist
read_aln_start = int(samlist[3])
indel_positions = []
for num1, i_or_d, num2, m in re.findall('(\d+)([ID])(\d+)?([A-Za-z])?', samlist[5]):
if num1:
read_aln_start += int(num1)
if num2:
read_aln_start += int(num2)
indel_positions.append(read_aln_start)
#print indel_positions
out.write(str(read_aln_start)+'\t'+str(i_or_d) + '\t'+str(samlist[2])+ '\t' + str(indel) +'\n')
out.close()
I would like my script to take multiple files with names like a.sam, b.sam, c.sam and for each file give me the output : aout.sam, bout.sam, cout.sam
Can you please pass me either a solution or a hint.
Regards,
Irek
A:
Loop over filenames.
input_filenames = ['a.sam', 'b.sam', 'c.sam']
output_filenames = ['aout.sam', 'bout.sam', 'cout.sam']
for infn, outfn in zip(input_filenames, output_filenames):
out = open('/home/directory/{}'.format(outfn), 'w')
infile = open('/home/directory/{}'.format(infn), 'r')
...
UPDATE
Following code generate output_filenames from given input_filenames.
import os
def get_output_filename(fn):
filename, ext = os.path.splitext(fn)
return filename + 'out' + ext
input_filenames = ['a.sam', 'b.sam', 'c.sam'] # or glob.glob('*.sam')
output_filenames = map(get_output_filename, input_filenames)
A:
I'd recommend wrapping that script in a function, using the def keyword, and passing the names of the input and output files as parameters to that function.
def do_stuff_with_files(infile, outfile):
out = open(infile,'w')
infile = open(outfile,'r')
# the rest of your script
Now you can call this function for any combination of input and output file names.
do_stuff_with_files('/home/directory/a.sam', '/home/directory/a.out')
If you want to do this for all files in a certain directory, use the glob library. To generate the output filenames, just replace the last three characters ("sam") with "out".
import glob
indir, outdir = '/home/directory/', '/home/directory/out/'
files = glob.glob1(indir, '*.sam')
infiles = [indir + f for f in files]
outfiles = [outdir + f[:-3] + "out" for f in files]
for infile, outfile in zip(infiles, outfiles):
do_stuff_with_files(infile, outfile)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I access the first attempt's yarn log?
If I use _attemptid postfix am I getting the given attempt's log? Like this:
yarn logs -applicationId application_11112222333333_444444_1
Strangely I didn't find an answer for this on the web.
UPDATE:
Let me rephrase my question:
How can I access a given attempt's yarn log?
A:
Here's a bit ugly but working solution in several steps (for hadoop-2.6). Basically each attempt executes in it's container. To get logs for specific container need to know applicationId, containerId, and node manager address. For example you need to get logs for appattempt_1:
To get info about appattempt (containerId, host url):
yarn applicationattempt -list application_ID_1. You'll got something like this:
======================== ======== ==================== ===========================
ApplicationAttempt-Id State AM-Container-Id Tracking-URL
======================== ======== ==================== ===========================
appattempt_1 FAILED container_1 https://host1:8090/blabla
appattempt_2 KILLED container_2 https://host2:8090/blabla
======================== ======== ==================== ===========================
To convert tracking-URL to node address:
$ yarn node -list -all | grep host1 | awk '{print $1}'
host1:8041
yarn logs -applicationId application_ID_1 -containerId container_1 -nodeAddress host1:8041
In hadoop-2.7 you can just use:
yarn logs -applicationId [OPTIONS]
general options are:
-am Prints the AM Container logs for
this application. Specify
comma-separated value to get logs
for related AM Container. For
example, If we specify -am 1,2,
we will get the logs for the
first AM Container as well as the
second AM Container. To get logs
for all AM Containers, use -am
ALL. To get logs for the latest
AM Container, use -am -1. By
default, it will print all
available logs. Work with
-log_files to get only specific
logs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Maximize $\det X$, subject to $X_{ii}\leq P_i$, where $X>0$
Given $P_1,P_2,\cdots,P_N$.
\begin{array}{ll} \text{maximize} & \det X\\ \text{subject to} & \mathrm X_{ii}\leq P_i \\\forall i=1,2,\cdots,n\end{array}
$X\in\mathbb{R}^{n\times n}$, $X>0$ (i.e. positive definite).
For $n=2$, maximum is achieved when $X_{ii}=P_i$ and $X$ is diagonal matrix.
Then for $n=3$, Let $X=\begin{bmatrix}X_1 & X_2\\X_2^T &x_3\end{bmatrix}$, where $X_1\in\mathbb{R}^{2\times2}$.
$\det(X)=\det(X_1)\times \det(x_3-X_2^TX_1^{-1}X_2)\leq \det(X_1)\times x_3\leq P_1P_2P_3$.
Then following same logic my conjecture is $\max\{ \det X\}=P_1\cdots P_n$, when $X_{ii}=P_i$.
Is it correct? If not, can you please point my mistake or give me counter example? Thanks
A:
Your problem is equivalent to maximizing $\log \det X$ such that $X_{ii} \leq P_i$ and $X$ is positive definite. That is convenient, because now you have a convex optimization problem that satisfies the Slater condition, so the KKT conditions are necessary and sufficient. The Lagrangian is
$$L(X,\lambda) = \log\det X - \sum_i \lambda_i (X_{ii} - P_i)$$
The derivative of $\log\det X$ is $(X^{-1})^T$, so the KKT conditions are:
$$(X^{-1})_{ii} - \lambda_i = 0$$
$$(X^{-1})_{ij} = 0 \quad (i \neq j)$$
$$\lambda_i (X_{ii} - P_i)=0$$
$$X_{ii} \leq P_i$$
$$\lambda \geq 0.$$
The point you found satisfies these conditions and is therefore optimal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Inconsistent behavior of Renderscript
I've written following renderscript:
ushort* curve_hth;
ushort* curve_hts;
ushort* curve_htv;
ushort* curve_sth;
ushort* curve_sts;
ushort* curve_stv;
ushort* curve_vth;
ushort* curve_vts;
ushort* curve_vtv;
uchar4 RS_KERNEL transform(uchar4 in, uint32_t x, uint32_t y)
{
if(!isSelected(x, y)) return in;
ushort3 in_rgb = { (ushort) in.r, (ushort) in.g, (ushort) in.b };
ushort3 in_hsv = rgb_to_hsv(in_rgb);
ushort in_h = in_hsv.r;
ushort in_s = in_hsv.g;
ushort in_v = in_hsv.b;
ushort out_h, out_s, out_v;
rsDebug("out1", out_s);
if(curve_hth != NULL) out_h += curve_hth[in_h]; else out_h += in_h;
rsDebug("out2", out_s);
if(curve_hts != NULL) out_s += curve_hts[in_h];
rsDebug("out3", out_s);
if(curve_htv != NULL) out_v += curve_htv[in_h];
rsDebug("out4", out_s);
if(curve_sth != NULL) out_h += curve_sth[in_s];
rsDebug("out5", out_s);
if(curve_sts != NULL) out_s += curve_sts[in_s]; else out_s += in_s;
rsDebug("out6", out_s);
if(curve_stv != NULL) out_v += curve_stv[in_s];
rsDebug("out7", out_s);
if(curve_vth != NULL) out_h += curve_vth[in_v];
rsDebug("out8", out_s);
if(curve_vts != NULL) out_s += curve_vts[in_v];
rsDebug("out9", out_s);
if(curve_vtv != NULL) out_v += curve_vtv[in_v]; else out_v += in_v;
rsDebug("out10", out_s);
out_h = min((float) out_h, (float) 360);
out_s = min((float) out_s, (float) 100);
out_v = min((float) out_v, (float) 100);
ushort3 out_hsv = { out_h, out_s, out_v };
ushort3 out_rgb = hsv_to_rgb(out_hsv);
uchar4 out = { out_rgb.r, out_rgb.g, out_rgb.b, in.a };
return out;
}
When I run that script, I get in logcat:
D/RenderScript: out1 0 0x0
D/RenderScript: out2 0 0x0
D/RenderScript: out3 255 0xff
D/RenderScript: out4 255 0xff
D/RenderScript: out5 255 0xff
D/RenderScript: out6 255 0xff
D/RenderScript: out7 255 0xff
D/RenderScript: out8 255 0xff
D/RenderScript: out9 255 0xff
D/RenderScript: out10 255 0xff
It surprised me a lot, because all the curve_?t? pointers should be null, I don't bind them in Java code. It was strange, so I modified the debugging part of script and I got:
if(curve_hth != NULL) out_h += curve_hth[in_h]; else out_h += in_h;
rsDebug("out1", out_s);
rsDebug("out2", curve_hts == NULL);
if(curve_hts != NULL)
{
out_s += curve_hts[in_h];
rsDebug("out3", 1);
}
rsDebug("out4", out_s);
if(curve_htv != NULL) out_v += curve_htv[in_h];
if(curve_sth != NULL) out_h += curve_sth[in_s];
if(curve_sts != NULL) out_s += curve_sts[in_s]; else out_s += in_s;
if(curve_stv != NULL) out_v += curve_stv[in_s];
if(curve_vth != NULL) out_h += curve_vth[in_v];
if(curve_vts != NULL) out_s += curve_vts[in_v];
if(curve_vtv != NULL) out_v += curve_vtv[in_v]; else out_v += in_v;
rsDebug("out5", out_s);
The result in logcat was:
D/RenderScript: out1 0 0x0
D/RenderScript: out2 1 0x1
D/RenderScript: out4 25004 0x61ac
D/RenderScript: out5 25004 0x61ac
out2 is 1, so curve_hts is NULL. There is no out3 log, the if instruction doesn't get called, so how out_s changes its value?
A:
Local variable out_h, out_s, out_v are not initialized, so the behavior is undefined.
ushort out_h, out_s, out_v;
If you initialize them to be 0, I think the problem should be gone.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove by a combinatorial argument that ${n \choose r}{r \choose s}={n \choose s} {n-s \choose r-s} $
Prove by a combinatorial argument that ${n \choose r}{r \choose s}={n \choose s} {n-s \choose r-s} $
Is a little hard for me solve this problem.
I see we need to use the multiplication principle. But is a little hard to me finding the idea for prove this...
Can someone give me a hint?
A:
For sake of variety, here's an algebraic proof:
$$\begin{align*}
{n \choose r}{r \choose s}
&=\frac{n!}{r!(n-r)!}\frac{r!}{s!(r-s)!}\\\\
&=\frac{n!}{(n-r)!\cdot s!\cdot(r-s)!}\\\\
&=\frac{n!}{s!\color{red}{(n-s)!}}\frac{\color{red}{(n-s)!}}{(r-s)!(n-r)!}\\\\
&=\frac{n!}{s!(n-s)!}\frac{(n-s)!}{(r-s)!(n-s-(r-s))!}\\\\
&={n \choose s}{n-s \choose r-s}
\end{align*}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Separating classes using IDs
I have two picture on which a DIV shows upon hovering, showing some user info. The looks of it is as intended, but I can't figure how to only show the info on the hovered image.
How can I do this?
Here's a live working example of the code:
http://jsfiddle.net/uvHw4/
Raw javascript code:
$(document).ready(function() {
$('.start_profile_container_text').hide();
$('.start_profile_container').mouseenter(function() {
$('.start_profile_container_text').show('slide', { direction: "down"} ,'fast');
});
$('.start_profile_container').mouseout(function() {
$('.start_profile_container_text').hide('slide', { direction: "down"} ,'fast');
});
});
A:
Change your script to this:
$(document).ready(function () {
$('.start_profile_container_text').hide();
$('.start_profile_container').mouseenter(function () {
$('.start_profile_container_text', this).show('slide', {
direction: "down"
}, 'fast');
});
$('.start_profile_container').mouseout(function () {
$('.start_profile_container_text', this).hide('slide', {
direction: "down"
}, 'fast');
});
});
The difference to your code is simply adding a this to the show/hide function to relate to the actual element.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do something just after symfony2 login success and before redirect?
I'm searching for a while now, for any info, on how to do something after authentication success in symfony2. I want to rehash user password to use bcrypt just after successful authentication using old hash. I need to do this when I still have valid plain password so it should be just after credentials check and before redirect.
Any clues how to achieve that?
I found something about event dispatcher in Symfony but I can't find if there is any event after successful authentication.
Please correct me if I'm trying to do this wrong way and suggest some better approach.
//EDIT
Ok I found event fired just after auth success, it's called security.authentication.success. So i can now attach to this event but now I'm not sure where in my boundle code should I attach my event listener? Should I do that in my /src/Pkr/BlogUserBundle/DependencyInjection/PkrBlogUserExtension.php in load() method?
A:
You can specify a login success handler to be executed on successful login.
For example, your security.yml
firewalls:
main:
pattern: ^/
form_login:
success_handler: my.security.login_handler
Now create the class which implements Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface and on successful login, you can do whatever you need and handle the redirect as you see fit.
/**
*
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
// handle it and return a response
}
Then create a service with that name in your services.xml for your bundle, or in your config.yml using the newly created handler.
I originally found out how to do this following this tutorial:
http://www.reecefowell.com/2011/10/26/redirecting-on-loginlogout-in-symfony2-using-loginhandlers/
| {
"pile_set_name": "StackExchange"
} |
Q:
Differenza tra 'di Russia' e 'della Russia'
Ciao a tutti,
C'è qualche differenza tra 'di Russia' e 'della Russia'? Ho letto da qualche parte che con i paesi vicini all'Italia si usa 'di' e con quelli lontani si usa 'di + articolo'. È vero?
Grazie!
A:
Non credo sia una regola generale.
Vi sono molti stati contemporanei il cui nome non è preceduto da alcun articolo. Queste sono spesso di isole o città-stato.
Assedio di Cipro
Isole di Capo Verde
Console di San Marino
Come vedi la distanza dall'Italia è irrilevante.
La netta sensazione è che più che una funzione della distanza ciò che veramente faccia la differenza sia l'entità geografica alla quale ci si sta riferendo.
Per indicare sovrani (anche contemporanei) di nazioni femminili si usa semplicemente "di"
Re di Svezia
Scià di Persia
Zar di Russia
Regina d'Inghilterra
Negus d'Etiopia
La stessa cosa non succede per nazioni di genere maschile
Re del Belgio
Re del Botswana
Ci sono notevoli eccezioni. Si trovano casi di entità statali maschili in cui la tendenza sembra cambiata col tempo. Ad esempio, sembra che un tempo fosse più in voga "Re di Marocco" rispetto a "Re del Marocco".
È importante inoltre ricordare che il nome di molte di queste entità statali è spesso espresso tramite sineddoche. Quindi nella fattispecie
Vladimir Putin, presidente della Federazione Russa -> Putin, presidente della Russia
Angela Merkel, Cancelliera della Repubblica Federale di Germania-> Merkel, Cancelliera della Germania
Come vedi dunque, nessuna relazione alla distanza.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to prove this inequality with $a,b,c\in [1,3]$
let $a,b,c\in [1,3]$,show that
$$3\left(\dfrac{1}{a}+\dfrac{1}{b}+\dfrac{1}{c}\right)+\dfrac{45}{a+b+c}\ge 16\left(\dfrac{1}{a+b}+\dfrac{1}{b+c}+\dfrac{1}{c+a}\right)$$
I had found this simaler problem,https://artofproblemsolving.com/community/c6h615194
I can't prove this it
A:
WLOG, assume that $c = \max(a,b,c) = 3$. The inequality becomes
$$\frac{3}{a} - \frac{16}{a+3} + \frac{3}{b} - \frac{16}{b+3} + 1 - \frac{16}{a+b} + \frac{45}{a+b+3} \ge 0.$$
Let $f(x) = \frac{3}{x} - \frac{16}{x+3}$.
We have $f''(x) = \frac{6}{x^3} - \frac{32}{(x+3)^3}$.
For $x\in [1,3]$, we have $(x+3)^3/x^3 = (1 + 3/x)^3 \ge 2^3 > 32/6$
and hence $f''(x) > 0$.
Thus, $f(x)$ is convex on $[1,3]$.
We have
$f(a) + f(b) \ge 2 f(\frac{a+b}{2})$. It suffices to prove that
$$\frac{12}{a+b} - \frac{64}{a+b+6} + 1 - \frac{16}{a+b} + \frac{45}{a+b+3} \ge 0$$
or
$$\frac{(a+b-2)(a+b-6)^2}{(a+b)(a+b+3)(a+b+6)}\ge 0.$$
We are done.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the workaround for WMI remote connection failure with Access Denied error when client runs with Local System account?
What is the workaround for WMI remote connection failure with Access Denied error when client runs with Local System account?
I tried to run script under local system account on the client which connects to remote WMI (namespace: root\cimv2) using local administrator credentials of remote machine. But WMI connection failed with the following error. The remote server has firewall enabled and client has firewall disabled. Both client and remote server has windows 2012 R2 OS.
Access is denied.
Win32::OLE(0.1709) error 0x80070005: "Access is denied"
What could be the reason for this error? The same script worked when ran from another client machine.
A:
http://msdn.microsoft.com/en-us/library/aa826699(v=vs.85).aspx
refer to above link.
solution:
To solve the problem, UAC filtering for local accounts must be disabled by creating the following DWORD registry entry and setting its value to 1:
[HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System] LocalAccountTokenFilterPolicy
reason:
"In a workgroup, the account connecting to the remote computer is a local user on that computer. Even if the account is in the Administrators group, UAC filtering means that a script runs as a standard user"
| {
"pile_set_name": "StackExchange"
} |
Q:
Arithmetic and Geometric Mean Inequality
Use the AM - GM inequality (no other method is acceptable), to prove that for all positive integers $n$:
$$\left(1 +\dfrac{1}{n}\right)^n \leq \left(1 + \dfrac{1}{n+1}\right)^{n+1}$$
I see that it is increasing... Don't know how to keep going.
A:
One way is to rewrite the inequality as:
$$\sqrt[n+1]{\left(1+\frac{1}{n}\right)^n\cdot 1}\le \frac{n\left(1+\frac{1}{n}\right)+1}{n+1},$$
and note that this is precisely AM-GM for $\left(1+\frac{1}{n}\right)$ taken $n$ times and $1.$
| {
"pile_set_name": "StackExchange"
} |
Q:
No response when uploading relatively large files to server
I have a page to upload images to my server(http://neiol.1ufh.com/) in the uploads folder (http://neiol.1ufh.com/uploads) however I noticed that I can only upload images of about 160kb in size if higher than that I get no response not even the response that comes when uploading files with size bigger than 2M, (2M is the max file post size on the server).
A:
Not to answer your question, but you NEED to check on the security. I recommend setting the site down right now before fixing it. I just could upload and execute apac.php, which only contained this PHP:
<?php echo "This is a really bad security issue"; ?>
But I could be a malicious person and break your website. Check it out: http://neiol.1ufh.com/uploads/apac.php
NOTE: I put this in an answer since the comment is too small for the formatting and everything,
| {
"pile_set_name": "StackExchange"
} |
Q:
Round corner TD not Working
below code for round css dont know why isnt its working
its working only on background color if given;
but not the border
the border code is on the same line
style=" border : 1px solid #D6D6D6;
and round css below
.Round {
border-radius: 15px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
}
<table border="1" width="100%" height="100%" style="border-collapse:collapse; position: fixed; top: 0; right: 0; left: 0;">
<tr height="20%" style="background-color:#3D4552;">
<th colspan="3" class="shadow">
<asp:Panel ID="Panel2" runat="server" style="top: 15px; left: 92px; position: absolute; height: 55px; width: 10%;">
<asp:Image ID="Image1" ImageUrl="~/Images/CasePROLogoweb.jpg" runat="server" />
</asp:Panel>
</th>
</tr>
<tr height="10%">
<td colspan="3"></td>
</tr>
<tr height="45%">
<td width="30%"></td>
<td width="40%" style=" border : 1px solid #D6D6D6; " class="Round">' Here is the class for round
</td>
<td width="30%"></td>
</tr>
<tr height="25%">
<td colspan="3" colspan="8" align="center" style="font-family: Calibri; font-size: 40pt; color: #FFFFFF">
</td>
</tr>
</table>
A:
You need to set the border-collapse on the table to separate and the border to 0 (to actually see it properly)
<table border="0" width="100%" height="100%" style="border-collapse:separate; position: fixed; top: 0; right: 0; left: 0;">
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get proper object through loop using javascript for Bubble Charts of Highcharts
I'm new in php and highcharts. I tried to populate my 3d bubble chart using mysql and php, but when I tried to run it ,the chart not appear.But i want bubble chart is appear with different colors.I already tried from SO suggestions.The color should be come product name wise.I have declare only one series ,but My php script returns the following json:
[{"name":"HP","0":80,"1":85,"2":87.5},{"name":"DELL","0":65,"1":80,"2":58.5},{"name":"SONY","0":55,"1":55,"2":60}]
But here I want my bubble color will be shows name wise with different colors.and want to know I can get proper correct object through loop using JavaScript.So how it possible To show different color.
Here is my index.php
$(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bubble',
plotBorderWidth: 1,
zoomType: 'xy'
},
title: {
text: 'Bubbles Chart SHOWS DIFFERENT COLOR'
},
xAxis: {
gridLineWidth: 1,
title: {
text: 'Product Ratings'
},
min: 0,
max: 100
},
legend: {
// layout: 'vertical',
// align: 'center',
verticalAlign: 'bottom',
//x: -10,
//y: 18,
enabled:true
},
yAxis: {
title: {
text: 'Specs Ratings'
},
startOnTick: false,
endOnTick: false,
min: 0,
max: 100
},
series: [{
name: 'PRODUCT NAME', //here i want dynamic name whatever comes from database
data: [],
showInLegend:true,
marker: {
fillColor: {
radialGradient: { cx: 0.4, cy: 0.3, r: 0.7 },
stops: [
[0, 'rgba(255,255,255,0.5)'],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0.5).get('rgba')]
]
}
}
}]
});
$.getJSON("bubbleChart.php", function(data) {
chart.series[0].setData(data);
});
});
HERE IS MY bubbleChart.php
$sqlBubble = "SELECT product.product_name,
product_rate.pro_rating,specs_rate.specs_rating,avg_rate.avrg_rating
FROM product
LEFT OUTER JOIN product_rate ON product.product_id = specs_rate.product_id
LEFT OUTER JOIN specs_rate ON product.product_id = specs_rate.product_id
LEFT OUTER JOIN temp_bubble ON product.product_id = temp_bubble.product_id
LEFT OUTER JOIN avg_rate ON product.product_id = avg_rate.product_id
where temp_bubble.product_id = product.product_id and temp_bubble.product_id = specs_rate.product_id and temp_bubble.product_id = avg_rate.product_id ";
$resultBubble = mysql_query($sqlBubble);
$result = array();
while($rowsBubble = mysql_fetch_array($resultBubble)){
$result[] = array('name' => $rowsBubble['product_name'],
$rowsBubble['pro_rating'],
$rowsBubble['specs_rating'],
$rowsBubble['avrg_rating']);
}
print json_encode($result, JSON_NUMERIC_CHECK);
So i request to you Please suggest me how can i show my different bubble color for HP,DELL,SONY like this.
A:
I presume your json's output format is wrong. It likes to be [{"name":"HP","data":[[80,85,87.5]]},{"name":"DELL","data":[[65,80,58.5]]},{"name":"SONY","data":[[55,55,60]]}].
and your bubbleChart.php you can fetch data like this
$rows = array();
$rows['name'] = $rowsBubble['product_name'];
$rows1 = array();
$rows1[0] = $rowsBubble['pro_rating'];
$rows1[1] = $rowsBubble['specs_rating'];
$rows1[2] = $rowsBubble['avrg_rating'];
$rows['data'][0] = $rows1;
array_push($result,$rows);
Try this format .Check what your json returns. I think it will be work fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hyphens when using "something + style" to describe something?
He lit the fire Cherokee style.
or:
He lit the fire Cherokee-style.
I have seen both. Which is correct?
And, if it's the second option, then what about "multiple words + style"? E.g.:
She organized the view spiral staircase style.
versus:
She organized the view spiral-staircase-style.
(which looks very wrong)
A:
You should use hyphens when the phrase appears as an adjectival phrase—just as you would any compound modifier—for example,
The Cherokee-style headdress was quite impressive.
In your example, it appears to be an adverbial phrase, in which case, I believe hyphens are not warranted. You may add an (optional) comma to avoid confusion:
He lit the fire, Cherokee style.
She organized the view, spiral-staircase style.
In the second, sentence 'spiral-staircase' is an adjectival phrase describing 'style'.
| {
"pile_set_name": "StackExchange"
} |
Q:
Joint distribution gives two marginal
In the following exercise I got two different distributions for $Z.$ I want to know where my mistake is. Every hint or comment is appreciated.
The exercise goes as follows:
Let $(X,Y)$ be a random vector with values in $\mathbb{R}^2$ such that it has a joint density given by:
$$f(x,y)=\frac{1}{x}\exp(-x)\chi_{\{0<y<x\}}$$
where $\chi_{\{0<y<x\}}$ is the indicator fct. on $\{0<y<x\}.$
Let $Z:=\frac{X}{Y}$.
Compute the distribution of $(X,Z)$ and $Z$.
Now my computations:
First computation:
\begin{align*}
\mathbb{E}[f(X,Z)]&=\int_{\{0<y<x\}}f(x,\frac{x}{y})\frac{1}{x}\exp(-x)d(x,y)\\
&=\int_{\mathbb{R}_{>0}\times\mathbb{R}_{>1}}f(x,z)\frac{1}{x}\frac{x}{z^2}\exp(-x)d(x,y).
\end{align*}
Where I used the change of variables $\phi:\mathbb{R}_{>0}\times\mathbb{R}_{>1} \rightarrow \{(x,y) \in \mathbb{R}^2 : 0<y<x\}; (x,z) \mapsto (x,\frac{x}{z}).$
Hence $d\mathbb{P}_{(X,Z)}=\frac{1}{z^2}\exp(-x)\cdot \chi_{\mathbb{R}_{>0}\times\mathbb{R}_{>1}}$.
Thus $\mathbb{P}(Z\leq \alpha)=\int_{1}^{\alpha}\frac{1}{z^2}\int_{0}^{\infty}\exp(-x)dxdy=\int_{1}^{\alpha}\frac{1}{z^2}dy$, leading to
$$d\mathbb{P}_{Z}=\frac{1}{z^2}\chi_{\mathbb{R}_{>1}}.$$
Second computation:
\begin{align*}
\mathbb{P}(Z\leq \alpha)=\mathbb{P}(\frac{X}{Y}\leq \alpha)&=\int_{\{\frac{X}{Y}\leq \alpha\}}\frac{1}{x}\exp(-x)\cdot \chi_{\{0<y<x\}}d(x,y)\\
&=\int_{\mathbb{R}^2}\frac{1}{x}\exp(-x)\cdot \chi_{\{0<y<x\}}\cdot \chi_{\{x\leq \alpha y\}}d(x,y)\\
&=\int_{0}^{\infty}\frac{1}{x}\exp(-x)\int_{0}^{\alpha x}dydx\cdot \chi_{\{0<\alpha<1\}}\\
&=\alpha\chi_{\{0<z<1\}}
\end{align*}
Hence $Z$ is uniformly distributed on $(0,1)$.
Now, where is my mistake? (I am always uneasy when doing change of variables so I fear there is my problem...).
Thanks in advance.
A:
I don't see how you got from
∫χ{0 < y < x}⋅χ{x ≤α y}d(x,y) to ∫dydx⋅χ{0<α<1} where first integral is over R and the second is from 0 to αx. As y goes from 0 to αx how is the constraint x≤αy maintained?
| {
"pile_set_name": "StackExchange"
} |
Q:
How do the eigenvalues change if we change the diagonal entries of the matrix?
Suppose $A \in M_n(\mathbb R)$ is stable. By stable, we mean the eigenvalues are all on the left open half plane of $\mathbb C$. Now if we decrease the value of $A_{11}$, does the matrix remain stable?
I first thought in terms of Gershgorin Disks. If we decrease the entry $A_{11}$, the center of corresponding disk would move to the left of the real axis. But then I realized this is not enough since we only know the eigenvalues are contained in the union of all disks. However, I could not see a counterexample.
Alternatively, the question is a perturbation with rank-one matrix, i.e., we want to know whether $A-t e_1e_1^T$ remains stable for $t > 0$ where $e_1 = (1, 0, \dots, 0)^T$.
A:
Let $A_t=A-te_1{e_1}^T$ and $\lambda_t$ be the max of the real parts of the eigenvalues of $A_t$.
By continuity of $\lambda_t$ wrt ${A_t}_{1,1}$, $A_t$ remains stable when $t$ is small enough.
Yet, there is no lower bound for the admissible variation of $t$, as shows the folllowing example.
Let $\epsilon$ be a fixed small positive real (for example $\epsilon<0.1$) and
$A=\begin{pmatrix}-2-\epsilon&2\\-1&1-\epsilon\end{pmatrix}$, that is, $A_t=\begin{pmatrix}-2-\epsilon-t&2\\-1&1-\epsilon\end{pmatrix}$.
Note that $spectrum(A)=-\epsilon,-1-\epsilon$.
The derivative in $A$ of the greatest eigenvalue of $A$ wrt $A_{1,1}$ is $\lambda '=-1$. Then $\lambda_{\epsilon}\approx -\epsilon+\epsilon \approx 0$.
In particular, $A_{2\epsilon}$ is not stable.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fetch image icons from an Array & append one by one inside DIVs
How to fetch image icons from an Array & append one by one inside DIVs. I have an array with image path. I want to fetch images from that array & append one by one inside DIVs.
I want to append those icons in "class=acc_trigger" divs.. here is the HTML
<div class="container">
<h2 class="acc_trigger"><a href="#">Home</a></h2>
<div class="acc_container">
<div class="block">
<ul>
<li><a href="#">One</a></li>
<li><a href="#">One</a></li>
<li><a href="#">One</a></li>
</ul>
</div>
</div>
<h2 class="acc_trigger"><a href="#">Req Mgmt</a></h2>
<div class="acc_container">
<div class="block">
<ul>
<li><a href="#">Requirments</a></li>
<li><a href="#">Use Cases</a></li>
<li><a href="#">Test Cases</a></li>
</ul>
</div>
</div>
<h2 class="acc_trigger"><a href="#">Test</a></h2>
<div class="acc_container">
<div class="block">
<ul>
<li><a href="#">One</a></li>
<li><a href="#">One</a></li>
<li><a href="#">One</a></li>
</ul>
</div>
</div>
<h2 class="acc_trigger"><a href="#">Project</a></h2>
<div class="acc_container">
<div class="block">
<ul>
<li><a href="#">One</a></li>
<li><a href="#">One</a></li>
<li><a href="#">One</a></li>
</ul>
</div>
</div>
</div>
*********** JQUERY ARRAY *****************
var $iconLeft = new Array();
$iconLeft[0] = 'images/icons/home_icon.gif';
$iconLeft[1] = 'images/icons/reqMgmt_icon.gif';
$iconLeft[2] = 'images/icons/test_icon.gif';
$iconLeft[3] = 'images/icons/project_icon.gif';
$iconLeft[4] = 'images/icons/issue_icon.gif';
$iconLeft[5] = 'images/icons/more_icon.gif';
Should I use .each() ?? if so, how to use that? please help.
A:
Try this out:
$(document).ready(function () {
$('h2.acc_trigger').each(function(i){
var icon = new Array;
icon[0] = 'images/icons/home_icon.gif';
icon[1] = 'images/icons/reqMgmt_icon.gif';
icon[2] = 'images/icons/test_icon.gif';
icon[3] = 'images/icons/project_icon.gif';
icon[4] = 'images/icons/issue_icon.gif';
icon[5] = 'images/icons/more_icon.gif';
$(this).prepend('<img src='+icon[i]+' />');
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Breaking ICE - exactly how should strength be treated?
Sorry if this is quite a basic question, but I've reviewed the rule book a few times and haven't been able to answer it myself (although I appreciate that doesn't mean the answer isn't there, but I've just not been able to find it!).
When a Runner encounters a rezzed piece of ICE, that ICE has a numeric strength and perhaps a number of subroutines (as well as encounter events/abilities, but those are not relevant to my question). I think I understand that when it comes to the subroutines, as long as they are either broken or do not include "End the run" as an effect, the Runner is not prevented from proceeding past the piece of ICE, but I'm not 100% clear on how the strength of the ICE factors into this.
I know that the Runner must have an installed Icebreaker with at least the same strength as the ICE being encountered in order to be able to interact with the ICE (and therefore break the subroutines). But my question is: Does the type of the Icebreaker need to match that of the ICE being encountered to be able to use the strength to gain access to interact?
So for example, if the Runner has an installed Mimic icebreaker, which has a strength of 3 and the ability to break Sentry subroutines, can it be used to gain access to a non-Sentry piece of rezzed ICE which equal or lower strength, with a different icebreaker (with a strength lower than that of the encountered ICE) then used to break some/all of the subroutines (or not, if the Runner is happy to let the subroutines run)?
A:
Unless otherwise stated, strength simply determines which icebreakers can interact with (typically meaning break subroutines on) a piece of ice. From page 16 of the rulebook:
An icebreaker can only interact with ice that
has equal or lower strength than the icebreaker.
Notice that the individual icebreaker whose breaking ability you want to use needs to have high enough strength, the strength of your other icebreakers isn't a factor. It's also worth noting:
Many icebreakers allow the Runner to temporarily increase the
icebreaker’s strength by spending credits...This strength increase
lasts only while the current piece of ice is being encountered, unless
otherwise noted by card abilities. After an encounter with a piece of
ice, the icebreaker’s strength returns to the value shown on its card.
Just to be clear, it's certainly possible that at some point in the future an ice will be designed for which the strength factors into some other effect (e.g. "do X meat damage. X is the strength of this ice"), but I don't believe there's anything like that in the card pool today.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bound on $c-b$ for $a^n+b^n=c^n$
Let $a\leq b\leq c$ be positive real numbers and $n$ positive integer with $a^n+b^n=c^n$. Prove that $c-b\leq(\sqrt[n]{2}-1)a$.
The desired inequality can be written as $c-b+a\leq \sqrt[n]{2}a$. Raising to the power of $n$, this is $(c-b+a)^n\leq 2a^n$. If it were true that $(c-b+a)^n\leq c^n-b^n+a^n$ we would be done, since the latter is just $2a^n$.
A:
Fix $a$. By convexity of $f(x) = x^n$ on $\mathbb{R}_+$, an increase in $b$ leads to a lesser increase in $c$. Hence, the difference $c-b$ is maximized when $a=b$. The inequality follows.
| {
"pile_set_name": "StackExchange"
} |
Q:
Server startup error - Error in SQL syntax
I used mysql server 5.6.19 and mysql-connector-Java-5.0.8. I have following error.
ERROR {xxxxxxx} - Error while retrieving roles from Internal JDBC role store
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use
near 'OPTION SQL_SELECT_LIMIT=100' at line 1
Is this mysql server compatibility error ??
Is anyone can find what is the reason for this?
A:
The problem is that - probably - the JDBC driver is using the old SET OPTION <option-name> ... syntax, that has been deprecated since MySQL 5.0 (maybe earlier). See the comment on SET in the MySQL 5.0 documentation:
Older versions of MySQL employed SET OPTION, but this syntax is deprecated in favor of SET without OPTION.
MySQL 5.6 only supports SET <option-name> ....
Your JDBC driver is really old. See http://bugs.mysql.com/bug.php?id=66659 : you need to upgrade the Connector/J library to a - vastly - newer version (eg the latest: 5.1.32: http://dev.mysql.com/downloads/connector/j/ ).
This is assuming that your code doesn't execute any SET OPTION ... commands itself. Otherwise you will need to fix your code to use the newer syntax.
| {
"pile_set_name": "StackExchange"
} |
Q:
Validating ASP.Net Custom MembershipUser over WCF Causing Unsolicited Service Calls?
Okay,...first the facts.
I'm working on an ASP.Net project which validates it's users across a WCF service. I have a CutomMembershipUser class in a shared assembly which inherits from MembershipUser since I'm using a custom membership provider. All this cannot change because it's out of my remit.
Here's roughly what's happening. I've got some code in the Logged_In event of a login control that looks like this...
CustomMembershipUser user = (CustomMembershipUser)SecurityBL.GetUser(userName);
if (user.Customer.ToLower() == "some user")
{
//impl omitted
}
The first line executes without problems and I get the correct user back from the service. However, in the second line, when I compare the user.Customer property a second request is sent to the service with an empty userName string which hangs the whole IDE for about 30 secnods or so and eventually throws a FaultException<T> which I can catch on the service side.
Obviously my first assumption was that there was some logic in the getter of that property that lazy loads the property but there isn't; in fact it's an auto implemented property!
Even more strange than that,..in the calling code I can't even catch the exception which tells me that the request is coming from a different thread than that which I'm executing.
This same problem happens for any property access on this object whether it's overridden or entirely new.
Has anyone seen anything like this before? I'v been scratching my head for 2 days now and I'm not sure what to try next.
Any help would be great.
Thanks in advance.
Stimul8d
A:
membership is pretty straight ahead and actually has no knowledge of network communications especially not WCF,, so there has to be something hinky happening in your code. really.
if you want to try and isolate the smallest footprint of code that reproduces the effect and upload it somewhere I would be happy to take a look.
| {
"pile_set_name": "StackExchange"
} |
Q:
Comparable Class
I've been trying to learn the comparable class for sometime now, I know the correct syntax and the how it is used in most cases. Such as:
int result = ObjectA.compareTo(ObjectB);
would return a value of 0 if both object is the same; a negative value if object A is less then object B ,or a positive value if A is greater then B.
However when I go to actually write a program that uses the compareTo method, the compiler is saying that it can not find the compareTo method.
my question is: Do I have to directly inherit from the Comparable class in order to use the compareTo method? only reason I'm asking is because you do not have to explicitly inherit methods like toString or equals...because everything inherit from object. Where does CompareTo fall under?
A:
You need to implement the Comparable interface:
public class MyClass implements Comparable<MyClass>
and then declare the compareTo() method:
public int compareTo(MyClass myClass){
//compare and return result
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to change styles on word in statement in react native?
how to change color and fontSize on word in statement in react native?
for example "hello world test"
hello and test is red but world is blue
A:
<Text style={{color: 'red'}}>
hello
<Text style={{color: 'blue'}}>
word
</Text>
test
</Text>
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Cómo puedo cambiar el idioma de dotproject al Español?
He instalado dotproject y el lenguaje predeterminado esta en ingles quisiera cambiarlo al español e intentando de la formas recomendadas y no lo he podido hacer, ya he tratado agregando la carpeta es en el directorio locales y cambiado la variable host locale que estaba en en por es y el idioma sigue en inglés.
A:
Juan, esto lo tienes en el pdf de dotproject. Aquí está el link, http://www.faltantornillos.net/proyectos/gnu/manuales/dotProject/dotProject.pdf.
Espero te ayude.
| {
"pile_set_name": "StackExchange"
} |
Q:
Struct labeling
In C I would like to be able to label a specific location within a struct. For example:
struct test {
char name[20];
position:
int x;
int y;
};
Such that I could do:
struct test srs[2];
memcpy(&srs[1].position, &srs[0].position, sizeof(test) - offsetof(test, position));
To copy the position of srs[0] into srs[1].
I have tried declaring position as type without any bytes however this didn't work either:
struct test {
char name[20];
void position; //unsigned position: 0; doesn't work either
int x;
int y;
};
I am aware that I could embed the x and y within another struct called position:
struct test {
char name[20];
struct {
int x;
int y;
} position;
};
Or just use the location of the x property:
struct test srs[2];
memcpy(&srs[1].x, &srs[0].x, sizeof(test) - offsetof(test, x));
However I was wondering if there was a way to do what I had initially proposed.
A:
struct test {
char name[20];
char position[0];
int x;
int y;
};
0 length arrays are/were quite popular in network protocol code.
A:
Another solution using C11 an anonymous union with an anonymous structure :
struct test {
char name[20];
union {
int position;
struct {
int x;
int y;
};
};
};
The address of position is the address of the next structure members after name member.
I show it only for the sake of showing it as the natural solution is to just take the address of member x in the first structure declaration of your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the proper term for a function inverse to a constructor - to unwrap a value from a data type?
Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.)
Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell):
newtype Wrap = Wrap { unwrap :: Int }
Here Wrap is the constructor and unwrap is what?
The questions are:
How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term?
And to clarify, is this/other terminology applicable to other functional languages, or is it used just in the Haskell?
Perhaps also, is there any terminology for this in general, in non-functional languages?
I've seen both terms, for example:
... Most often, one supplies smart constructors and destructors for these to ease working with them. ...
at Haskell wiki, or
... The general theme here is to fuse constructor - deconstructor pairs like ...
at Haskell wikibook (here it's probably meant in a bit more general sense), or
newtype DList a = DL { unDL :: [a] -> [a] }
The unDL function is our deconstructor, which removes the DL constructor. ...
in The Real World Haskell.
A:
Destructor is the term used by C++ and maybe other languages that I don't know of. They are used to release ressources created by the constructor so they do the exact opposite of it. Maybe the concept does not translate literally to Haskell, but the term seems to be used at some places.
EDIT: Considering your edit to the question, I would call it an unwrapper then... I was able to answer the original question but now it has driven away from my knowledge so don't take this edit too seriously.
A:
In OOP, a constructor is a function or language construct that creates and initializes a new object ('constructs' the object), and a destructor is its dual, a function or language construct that cleans up after the object (by releasing any resources it holds) and deletes it.
However, since Haskell (unlike, say, C++) has garbage collection and doesn't support mutable state or other side effects (at least not directly), there is absolutely no reason for a destructor notion in the OOP sense. Also, Haskell constructors, unlike OOP constructors, have more applications than just object creation; they are also heavily used in pattern matching (see below for an example).
In your code example, 'unwrap' is a record field, and depending on how it is used, I might refer to it as an accessor, or maybe even a getter (although the latter is also used in a lens context, so it might actually be a bit confusing).
I have never heard the term 'destructor' (or 'deconstructor') used in a Haskell context myself; as Andres F. notes, however, it is sometimes used to refer to a function that undoes the wrapping introduced by a constructor. To my understanding, a record getter may serve as a destructor, but so could regular functions, provided that they get a value back out of a more complex data type. Examples include maybe and either from the Prelude.
Note that unwrap, in your example, can be several things:
a function (just like any other): you can, for example, do map unwrap [ Wrap 23, Wrap 42 ]; this usage is roughly equivalent to a getter method in OOP.
a record field specifier in a record construction: let w = Wrap { unwrap = 23 }
a record field specifier in a record update: let w' = w { unwrap = 23 }; this is similar to setter methods in OOP (if you squeeze a lot).
a record field specifier in pattern matching: f Wrap { unwrap = a } = a
It's probably best to think of Haskell constructors as something altogether different from OOP constructors. I suggest you (re-)read a good book on the Haskell programming language for a better understanding - "Real World Haskell" is really good, and I've heard good things about "Learn You A Haskell". Both should have good explanations about constructors and record syntax in particular.
A:
There are several terms for the concept. Deconstructing is what I believe is common in Haskell circles, it is what Real World Haskell calls it. I believe the term destructuring(or destructuring bind) is common in Lisp circles.
| {
"pile_set_name": "StackExchange"
} |
Q:
MacBookPro Ram Frequency
i have a MacBookPro 5,5 (Intel Core 2 Duo 2,26GHz) with Snow Leopard.
Actualy i've 2 ram block of 2GB (total 4GB) of DDR3 at 1067MHz.
Now i'm buying 2 ram bloc of 8GB of DDR3 but at 1600MHz, could i've problems?
This is the ram i'm going to buy:
http://www.amazon.it/Komputerbay-MACMEMORY-PC3-12800-1600MHz-204-Pin/dp/B009GYVK1O/ref=sr_1_2?ie=UTF8&qid=1392556082&sr=8-2&keywords=macmemory+16gb
I hope they will run at maximum frequency that motherboard support.
A:
MacBookPro 5,5
Has a maximum RAM capacity of 8 Gig. (2x 4 Gig banks)
You are trying to install 16 Gig!
That will not work regardless of the RAM frequency.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to install Tomcat7 in Ubuntu 14.04 LTS?
If I apt-get install tomcat7 it is installing a broken tomcat7. A simple startup.sh will give me errors, than when fixed says that tomcat has started but nothing shows up in localhost:8080. shutdown.sh will give me errors and even throw Java exceptions.
This wasn't happening in some previous Ubuntu release, where it simply worked. So, it is looks like tomcat package it been not maintained lately.
I can get it working from Eclipse (which by the way it is not been properly maintain too) when I am testing my web app. However there are things I need to test in an standalone tomcat installation. So far, Google hasn't helped.
Have any of you managed to properly installing tomcat7 in Ubuntu 14.4LTS? If so, can you point me to the right direction?
Edit:
Here is some logs.
Starting tomcat:
$ sudo /usr/share/tomcat7/bin/startup.sh
Using CATALINA_BASE: /usr/share/tomcat7
Using CATALINA_HOME: /usr/share/tomcat7
Using CATALINA_TMPDIR: /usr/share/tomcat7/temp
Using JRE_HOME: /usr
Using CLASSPATH: /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar
Tomcat started.
Browsing to localhost:8080 (and http://127.0.0.1:8080, http://127.0.0.1, http://[my network ip here]):
Oops! Google Chrome could not connect to localhost:8080
Stopping tomcat also fails:
$ sudo /usr/share/tomcat7/bin/shutdown.sh
Using CATALINA_BASE: /usr/share/tomcat7
Using CATALINA_HOME: /usr/share/tomcat7
Using CATALINA_TMPDIR: /usr/share/tomcat7/temp
Using JRE_HOME: /usr
Using CLASSPATH: /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar
Jul 03, 2014 7:15:55 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/common/classes], exists: [false], isDirectory: [false], canRead: [false]
Jul 03, 2014 7:15:55 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/common], exists: [false], isDirectory: [false], canRead: [false]
Jul 03, 2014 7:15:55 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/server/classes], exists: [false], isDirectory: [false], canRead: [false]
Jul 03, 2014 7:15:55 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/server], exists: [false], isDirectory: [false], canRead: [false]
Jul 03, 2014 7:15:55 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/shared/classes], exists: [false], isDirectory: [false], canRead: [false]
Jul 03, 2014 7:15:55 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/shared], exists: [false], isDirectory: [false], canRead: [false]
Jul 03, 2014 7:15:55 PM org.apache.catalina.startup.Catalina stopServer
SEVERE: Catalina.stop:
java.io.FileNotFoundException: /usr/share/tomcat7/conf/server.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at org.apache.catalina.startup.Catalina.stopServer(Catalina.java:466)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.stopServer(Bootstrap.java:370)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:457)
A:
I tried this on a fresh container:
sudo apt-get install tomcat7
sudo dpkg-reconfigure tomcat7
It seems to fix the issue in my case.
Edit :
dpkg-reconfigure will replace your custom config for tomcat7 with the default packet manager configuration, or, where given, it will present a menu to customize.
A:
I believe your CATALINA_BASE is incorrect it runs out of the /var/lib/tomcat7 directory and CATALINA_HOME is proper in regards to how you have declared the variable. Add CATALINA_HOME and CATALINA_BASE to /etc/default/tomcat7 along with JAVA_HOME and JRE_HOME. That executable notifies the tomcat servlet of how the environment is set upon start up of the servlet.
It could also be considered to put them in /etc/profile and then export them in /etc/bash.bashrc (i.e. export CATALINA_HOME). This should only be done if and only if your site doesn't have user login or registration. With out exporting the variables they would still be declared locally.
To globally declare the variables an approach, if you are the admin (group 4, you might also want to think about moving syslog to group 37, purging rsyslog and just keep the daemon running for logs as well so you preserve mandatory access control) you could ponder creating a ~/.bash_completion or ~/.bash_expert file in your home directory where you have something like this:
# ~/.bash_expert in regards to servlet alias
if [ -f /etc/bash_completion.d/.tomservlet ]; then
. /etc/bash_completion.d/.tomservlet
fi
export CATALINA_HOME
export CATALINA_BASE
export JRE_HOME
export JAVA_HOME
Then create the .tomservlet file in /etc/bash_completion.d/.tomservlet and add the
following:
CATALINA_HOME=/usr/share/tomcat7
CATALINA_BASE=/var/lib/tomcat7
JAVA_HOME=/usr/lib/jvm/jdk1.7.0
JRE_HOME=$JAVA_HOME:/jre
Once that is completed add the following lines to ~/.bashrc
if [ -f "$HOME/.bash_expert" ];then
. "$HOME/.bash_expert"
fi
Then source the ~/.bashrc file as shown below:
:~$ source .bashrc
and that should take care of your problems, in a secure fashion no matter what type of client side interaction is taken place. (Don't hold me to that, you never know what martians are lurking in cyberspace, it can be a scary realm sometimes).
P.S. I previously was referring to the oracle-sun jdk7 or I guess its just Oracle Jdk7 so if you are using the Open Jdk replace it as necessary, if using the oracle go back into the /etc/init.d/tomcat file and change openjdk to your version where the script refers to "$OPENJDK". This also assumes you installed from the repositories.
Good luck, and may your tomcat purr!!
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you add a checkbox input to an Azure DevOps Task Group?
In Azure DevOps, I have created a Task Group that runs Postman tests using the newman CLI. As inputs, users can pass in the paths to the Postman collection and environment files.
As the newman CLI is a requirement, the first task in the Task Group is to install it. However, in scenarios where several collections are run, there is no need to keep installing the CLI over and over, so I would like to offer a checkbox and then conditionally run the install task depending on the value of that checkbox.
As the UI for Task Groups is pretty lacking in useful options, I started exploring the API. I'm able to add additional inputs, but setting the obvious type option to checkbox yields only an additional text (string) input.
POST https://dev.azure.com/{org}/{project}/_apis/distributedtask/taskgroups?api-version=5.1-preview.1
{
...
"inputs": [
{
"aliases": [],
"options": {},
"properties": {},
"name": "Rbt.Cli.Install",
"label": "Install 'newman' CLI?",
"defaultValue": true,
"required": false,
"type": "checkbox",
"helpMarkDown": "Choose whether or not to install the 'newman' CLI. You only need to install it if it hasn't already been installed by a previos task running on this job.",
"groupName": ""
},
...
],
...
}
Looking more closely at the documentation, there is a definition for inputs - TaskInputDefinition. However, it looks as though whoever was tasked with writing that documentation left early one day and never got around to it. There are no descriptions at all, making it impossible to know valid values for properties in the definition.
How can I add a checkbox to my Task Group?
A:
I have now found that Task Groups offer picklist as an input type. This has allowed be to present a yes/no option to the user, and based on their answer I am able to conditionally run a task.
I would still prefer to have a checkbox though, should anyone know how to do that.
{
"aliases": [],
"options": {
"yes": "Yes - install CLI",
"no": "No - the CLI has already been installed"
},
"properties": {},
"name": "Postman.Cli.Install",
"label": "Install 'newman' CLI?",
"defaultValue": "yes",
"required": true,
"type": "picklist",
"helpMarkDown": "Choose whether or not to install the 'newman' CLI. You only need to install it if it hasn't already been installed by a previos task running on this job.",
"groupName": ""
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to round the result of a computation to n decimal places in Java
I can see that there are hundreds of posts on the subject of rounding decimal places. However, I have searched high and low and cannot seem to find a previous instance that matches my problem.
I am pretty new to java.
I am trying to calculate the slope of a line, assign it to a variable and have the contents of that variable be formatted to 4 decimal places.
I have tried DecimalFormat (appears to return a string, I need a numerical value that can be used in another stage of calculations)
I have tried BigDecimal (cannot seem to figure out how to construct it and setScale).
Below is my code:
import java.math.BigDecimal;
public class Scratch {
public static void main(String[] args) throws Exception {
BigDecimal slope1, slope2, slope3;
slope1 = new BigDecimal((8 - 8) / (20 - 5));
slope2 = new BigDecimal((9 - 8) / (22 - 5));
slope3 = new BigDecimal((9 - 8) / (22 - 20));
slope1 = slope1.setScale(4);
slope2 = slope1.setScale(4);
slope3 = slope1.setScale(4);
System.out.println(slope1);
System.out.println(slope2);
System.out.println(slope3);
}
}
The resulting output is:
0.0000
0.0000
0.0000
How to I construct the big data object, set it's scale, and do the calculation in a way that will give the real result of the calculation to 4 decimal places and not 0.0000?
Any help would be greatly appreciated. I've been messing with this for hours.
A:
You've got two problems here.
The first is that you are using integer arithmetic in the constructor of your BigDecimals.
You can fix this by casting the value to double.
Your second problem is that you are setting the scale of slope1 three times, and ignoring the values of slope2 and slope3 here:
slope1 = slope1.setScale(4);
slope2 = slope1.setScale(4); // should be slope2
slope3 = slope1.setScale(4); // should be slope3
However, when you fix this, you'll get an ArithmeticException when you try to calculate slope2. Whenever you use scale() to round a number, you need to specify a RoundingMode so that it knows how you want to round.
Try this:
slope1 = new BigDecimal((double) (8 - 8) / (20 - 5));
slope2 = new BigDecimal((double) (9 - 8) / (22 - 5));
slope3 = new BigDecimal((double) (9 - 8) / (22 - 20));
slope1 = slope1.setScale(4, RoundingMode.HALF_UP);
slope2 = slope2.setScale(4, RoundingMode.HALF_UP);
slope3 = slope3.setScale(4, RoundingMode.HALF_UP);
System.out.println(slope1); // 0.0000
System.out.println(slope2); // 0.0588
System.out.println(slope3); // 0.5000
| {
"pile_set_name": "StackExchange"
} |
Q:
Check a String for a Slash
string testStr="thestringhasa\slash";
if(testStr.Contains("\"))
{
//Code to process string with \
}
How do I properly test to see if a string contains a backslash, when I try the it statement if says a New Line in constant.
A:
You should use double slashes
string testStr=@"thestringhasa\slash";
if(testStr.Contains("\\"))
{
//Code to process string with \
}
A:
The backslash must be escaped. Try the following:
string testStr = @"thestringhasa\slash";
if (testStr.Contains("\\"))
{
//Code to process string with \
}
A:
The other two answers are entirely correct, but no one bothered to explain why. The \ character has a special purpose in C# strings. It is the escape character, so to have a string that contains a slash, you have to use one of two methods.
Use the string literal symbol @. A string preceded by the @ symbol tells the C# compiler to treat the string as a literal and not escape anything.
Use the escape character to tell the C# compiler there is a special character that is actually part of the string.
So, the following strings are equivalent:
var temp1 = @"test\test";
var test2 = "test\\test";
test1 == test2; // Yields true
| {
"pile_set_name": "StackExchange"
} |
Q:
tkinter grid not working correctly
when I try to make a window using tkinter in python 3.4.2, the windows opens, but the ..grid method doesnt function properly. The label and entry box dont move even though I change the row and column parameters. Please help:
from tkinter import *
root = Tk()
root.geometry("1024x768")
root.resizable(width=FALSE, height=FALSE)
label_title = Label(root, text="Past paper helper")
entry_1 = Entry(root)
label_title.grid(row=0, column=5)
entry_1.grid(row=16, column=1)
root.mainloop()
A:
Empty rows and columns have zero size. Column 1000 will give the same effect as column 0, if columns 0-999 are empty. Sames goes for rows.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending Bitcoins through Tor versus sending them through VPN
I bought a VPN subscription using Tor and Bitcoins. The commercial VPN service provider does not know who I am.
Below are my questions:
Could someone tell me whether sending Bitcoins through Tor provides more anonymity than sending them through my VPN service?
Is it true that sending Bitcoins through Tor is awfully slow?
What are the other advantages of sending Bitcoins via Tor?
A:
Well, if you are interested being as anonymous as possible, Tor is far more interesting. The VPN provider may not know who you are but it does know your IP address and the website you are visiting, which is almost the same if it comes in the hands of those you probably want to avoid knowing it.
With Tor on the other hand, node know each other's IP address. As you make a network request with Tor, it will pass through a number of nodes, usually 5 I thought. Of these 5 nodes, only the first one knows your IP address and only the last one can see the request you send. Supposing you use SSL as much as possible, the last node only knows the IP address your request is send to.
All intermediate nodes know nothing about you. So you are in fact the most vulnerable for the first node, because he knows your IP address. But he has no clue what website you are visiting, so no single computer in the Tor network will be able to see what you are doing.
Besides, sending a transaction with Tor does not have to be slow. That's just a small packet. You probably mean that syncing with the network and downloading all blocks is slow. Well, there is not much of a point for doing that via Tor. None of your addresses are sent along with block requests, so you can safely sync blocks over VPN or regular internet. The most information the outside world will get to know is that you are downloading Bitcoin data. But using a VPN that accepts Bitcoin, I doubt if they would be eager to share that information with others.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why would someone use NEAT over other machine learning algorithms?
Why would someone use a neuroevolution algorithm, such as NEAT, over other machine learning algorithms? What situation would only apply to an algorithm such as NEAT, but no other machine learning algorithm?
A:
The main difference leading to strengths and weaknesses of NEAT algorithm, is that it does not use any gradient calculations. That means for NEAT, neither the cost function, nor the activation functions of the neurons are required to be differentiable. In some circumstances - e.g. where agents directly compete, and you can select them for next generation if they win versus one or more opponents - you may not even need a cost function to optimise. Quite often the cost function can be a simple number generated from a complex evaluation of the network.
Therefore, NEAT can be used in situations where the formula for a cost function, in terms of single feed-forward runs of the network, is not very clear. It can also be used to explore activation functions such as step functions or stochastic firing neurons, where gradient based methods are difficult to impossible to apply.
NEAT can perform well for simple control scenarios, as a policy network that outputs actions given some sensor inputs. For example, it is popular to use it to create agents for racing games or simulated robotics controllers. When used as a policy-based controller, NEAT is in competition with Reinforcement Learning (RL), and has basic similarities with policy gradient methods - the nature of the controller is similar and often you could use the same reward/fitness function.
As NEAT is already an evolution-inspired algorithm, it also fits well with a-life code as the "brains" of simulated creatures.
The main disadvantage of NEAT is slow convergence to optimal results, especially in complex or challenging environments. Gradient methods can be much faster, and recent advances in Deep RL Policy Gradients (algorithms like A3C and DDPG) means that RL can tackle much more complex environments than NEAT.
I would suggest to use NEAT when:
The problem is easy to assess - either via a measurement of performance or via competition between agents - but might be hard to specify as a loss function
A relatively small neural network should be able to approximate the target function
There is a goal to assess a non-differentiable activation function
If you are looking at a sequential control problem, and could use a standard feed-forward neural network to approximate a policy, it is difficult to say in advance whether NEAT or some form of Deep RL would be better.
| {
"pile_set_name": "StackExchange"
} |
Q:
Properly Divergent Sequences
Using the definition in Bartle's Introduction to Real Analysis, I am trying to gain an intuitive understanding of limits that tend to infinity.
Given Definition:
Let ($x_n$) be a sequence of real numbers.
(i) We say that ($x_n$) tends to $\infty$, and write $lim(x_n) = +\infty$ , if for every $\alpha \in \Bbb R$ there exists a natural number $K(\alpha)$ such that if $n \ge K(\alpha)$, then $x_n > \alpha$.
(ii) We say that $(x_n)$ tends to $- \infty$, and write $lim(x_n) = - \infty$, if for every $\beta \in \Bbb R $ there exists a natural number $K(\beta)$ such that if $n \ge K(\alpha)$, then $x_n < \beta$.
My question is this: Can anyone put this into words or paraphrase their understanding of this concept? I'm having trouble grasping the concept of these kinds of limits with the formal definitions. Apologies if this is more of a 'soft' question.
As an example question, I know that the lim$(\sqrt{n^2+2} = \infty$ however I don't understand why this is so.
A:
Essentially what the definition is saying is, if you claim that a sequence ${x_n}$ is truly 'approaching infinity', if I give you a really large number, say $100000000000000000000000$ you should be able to tell me that there is a point in this sequence of numbers $x_n$, where if you take all terms of the sequence after that point, they are all bigger than $100000000000000000000000$ .
Now you should not only be able to do this with $100000000000000000000000$, but literally with all positive numbers, that is numbers of ANY size, no matter how large.
So intuitively, this means that the sequence keeps getting larger and larger and never ceases to get larger and larger.
This is basically the same for when a sequence tends to $-\infty$, except the sequence gets increasingly large and negative.
You may think, okay so a sequence tending to $\infty$ intuitively means it gets larger and larger, so why don't we leave it at that? Point is, how do we actually know a sequence continues to get larger if we can't find terms in the sequence that exceed a number we have in mind? The answer is we can't know for sure, which is why we define a sequence to tend to $\infty$ only if we can do this, and for all positive numbers too.
EDIT: Also, just for completeness, we don't actually NEED to find a $K(\alpha)$ so that for all $n\geq K(\alpha)$ , $x_n \geq \alpha$ , we could use non-strict inequalities for the definition as well and it would be the same. That is, we could also just find a $K(\alpha)$ so that for all $n> K(\alpha)$ , $x_n > \alpha$.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between Apache Mahout and Apache Spark's MLlib?
Considering a MySQL products database with 10 millions products for an e-commerce website.
I'm trying to set up a classification module to categorize products. I'm using Apache Sqoop to import data from MySQL to Hadoop.
I wanted to use Mahout over it as a Machine Learning framework to use one of it's Classification algorithms, and then I ran into Spark which is provided with MLlib
So what is the difference between the two frameworks?
Mainly, what are the advantages,down-points and limitations of each?
A:
The main difference will come from underlying frameworks. In case of Mahout it is Hadoop MapReduce and in case of MLib it is Spark. To be more specific - from the difference in per job overhead
If your ML algorithm mapped to the single MR job - main difference will be only startup overhead, which is dozens of seconds for Hadoop MR, and let say 1 second for Spark. So in case of model training it is not that important.
Things will be different if your algorithm is mapped to many jobs.
In this case we will have the same difference on overhead per iteration and it can be game changer.
Lets assume that we need 100 iterations, each needed 5 seconds of cluster CPU.
On Spark: it will take 100*5 + 100*1 seconds = 600 seconds.
On Hadoop: MR (Mahout) it will take 100*5+100*30 = 3500 seconds.
In the same time Hadoop MR is much more mature framework then Spark and if you have a lot of data, and stability is paramount - I would consider Mahout as serious alternative.
A:
Warning--major edit:
MLlib is a loose collection of high-level algorithms that runs on Spark. This is what Mahout used to be only Mahout of old was on Hadoop Mapreduce. In 2014 Mahout announced it would no longer accept Hadoop Mapreduce code and completely switched new development to Spark (with other engines possibly in the offing, like H2O).
The most significant thing to come out of this is a Scala-based generalized distributed optimized linear algebra engine and environment including an interactive Scala shell. Perhaps the most important word is "generalized". Since it runs on Spark anything available in MLlib can be used with the linear algebra engine of Mahout-Spark.
If you need a general engine that will do a lot of what tools like R do but on really big data, look at Mahout. If you need a specific algorithm, look at each to see what they have. For instance Kmeans runs in MLlib but if you need to cluster A'A (a cooccurrence matrix used in recommenders) you'll need them both because MLlib doesn't have a matrix transpose or A'A (actually Mahout does a thin-optimized A'A so the transpose is optimized out).
Mahout also includes some innovative recommender building blocks that offer things found in no other OSS.
Mahout still has its older Hadoop algorithms but as fast compute engines like Spark become the norm most people will invest there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: my .jar file created, but the main class cannot be found?
I've got these following steps:
(1) I'm under my Linux home directory of /home/a
(2) A simple java file, cat m.java
package my;
public class m{
public static void main(String[] args){
}
}
(3) javac m.java
(4) mkdir my && cp m.class my/
(5) $ cat manifest.mf
Manifest-Version: 1.0
Main-Class: my/m
Class-Path: /home/a
(6) jar cfm m.jar manifest.mf m.class
(7) java -jar m.jar
Error: Could not find or load main class m.class
How to make it work?
A:
Main-Class should be with package with dot separated and not /
Main-Class: my.m
Main-Class: MyPackage.MyClass
Remove Class-Path line if you don't need more jars
Adding Classes to the JAR File's Classpath
You may need to reference classes in other JAR files from within a JAR file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Xpages: error trapping in LotusScript Agent called from SSJS
I am calling a lotusscript agent from the PostSave event of an xpage (taken from the IBM Wiki Template). I would like to add some error trapping so if something happens (I had cases of "attachments missing... run compact to fix this" error), the application would at least warn the user that something went wrong.
Do I need to put the error trapping code in the agent? Does it belong in the PostSave event of the xpages?
The agent is called that way:
<xp:this.data>
<xp:dominoDocument var="pageDocument" formName="fPage"
action="openDocument" ignoreRequestParams="false"
computeWithForm="onsave">
<xp:this.postSaveDocument><![CDATA[#{javascript:var agent = database.getAgent("XPSavePage");
agent.runOnServer(pageDocument.getDocument().getNoteID());}]]>
</xp:this.postSaveDocument>
</xp:dominoDocument>
<xp:this.data>
The agent is working great, but on some documents, we do have a missing attachments error, due to some conversion errors and other cases (persitence related, most probably). But I have no clue on how to trap if an error occured in the Lotus Script agent...
A:
I recommend to use the method:
agent.runWithDocumentContext(doc); // << ssjs
then in the agent you get the document updated with the last changes:
set doc = ses.documentContext ' << ls
Other option would be to use the property webQuerySaveAgent of the DocumentDataSource
A:
The agent has ZERO visibility to the calling environment, short of the DocumentContext.
So you need to write any status back into the document and check that value in your XPage.
If you want to be very cautious, you set the status to 'AgentFailed' and let the agent update it with either 'success' or a more specific error. This way you trap errors where the agent couldn't write back into the document.
While you are on it: improve your application's response time by taking out the start of the agent runtime - write your code in a bean. SessionAsSigner gives you elevated rights you might need
| {
"pile_set_name": "StackExchange"
} |
Q:
Sublime Text says "No Build System" on Ubuntu/Linux
Recently i switched to Ubuntu/Linux and searched for some good text editor and i found Sublime Text, i'm very beginner at coding and i was using Notepad++ in windows.
After i downloaded sublime text, i tried to write some codes in javascript to see if it works but it said "No Build System" and when i looked for it, i didn't find any guide for linux... in Notepad++ all i have to do was click run and ta da, the output screen was there.
I don't know much about linux or sublime text, my exact question is how can i run and see my codes in the output screen, currently i'm working on Javascript and i have no idea what a "Build System" is, i just want to type some basic code in sublime text and see the result on the screen, so if you help me i'll be much appreciated.
Here's an image the problem:
A:
In order to explain your problem it's first important to realize that although the feature is called build, it applies just as much to running an interpreted program as it does to actually building anything; think of it less as a "build" tool and more as a "run some external program to do something" tool instead.
With that said, Sublime comes pre-installed with a few different build systems for various languages, but JavaScript isn't one of them. Possibly this is because it's generally unclear whether a particular JavaScript file is meant to be used in a browser, or executed via something like node, but that's just a guess.
In your case, the text No build system is literally telling you that you have told Sublime to automatically select an appropriate build system for the type of file that you're editing, but that it didn't find one and so there's nothing that it can do.
The solution to the problem would be to either install a third party package that includes a JavaScript build system (see Package Control) or create one yourself.
A good rule of thumb for Sublime is that if there is a command you can execute from a command prompt that will do what you want, and you don't need to interact with that command (i.e. it doesn't need to ask you questions before or while it does something), you can set up Sublime to run that command for you.
One tool you can use to execute JavaScript is NodeJS, which provides a command named node that can execute JavaScript files if you install it:
tmartin:dart:~> cat sample.js
console.log("Hello, world!")
tmartin:dart:~> node sample.js
Hello, world!
Since this is a command that we can execute from a terminal to do what we want, and it doesn't require us to interact with it to tell it how to do anything, we can set up a build system to use it.
As an example of how to do that, select Tools > Build System > New Build System... from the menu, and then replace the contents of the file with the following code, then save it in the location that Sublime will default to as something like JavaScript.sublime-build:
{
"shell_cmd": "node \"${file}\"",
"selector": "source.js"
}
This simply says that when executing this build, Sublime should use the command node and provide it the name of the file that you're currently editing, and that this build system applies to source files of type js (JavaScript).
With that in place, if you select Tools > Build System > Automatic or Tools > Build System > JavaScript (the name in the menu reflects the name you used for the file), you should be able to use Ctrl+B to execute your program:
Note: This is an older image and uses cmd instead of shell_cmd; both examples will work the same way but shell_cmd is the recommended way to go unless you have a compelling reason not to.
You can check out the official documentation on build systems for more information on the options available to you in a build system.
Important notes:
If you get an error like command not found or something similar, it means that you either entered the command incorrectly, that program is not installed, or you need to tell your computer (and thus Sublime) where to find it by modifying your PATH; how you do that is system specific.
Make sure you save a new file manually at least once before you try to run it; before you do the file isn't on disk yet and can't be executed, which can cause strange errors to occur. It can be a good idea to make sure that Tools > Save all on build is checked to ensure your files on disk are always up to date when you build, but this won't save a new file that doesn't have a name yet.
I said this twice, but it bears repeating; if you need to interact with a command in any way, this won't work for you (without changes on your end). This includes if you try to execute a script that wants you to interact with it (e.g. it asks you your name and then prints it and such like). In such a case your program will seem to hang forever because it's waiting for input that you can't provide.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery Ajax HTML - Add Loading
I have tried this code locally and I can't seem to get it to display the contents of the html file in my country_slide div. I've tried playing around with it a bit all to no avail. I can't seem to see any code to actually tell the ajax where to put the content.
http://jsfiddle.net/spadez/uhEgG/23/
window.onload = function () {
var a = document.getElementById("country_link");
a.onclick = function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
success: function (data, textStatus) {
$("#country_slide").show();
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
return false;
}
}
A:
I usually insert the content into the parent element using the .html function
window.onload = function () {
var a = document.getElementById("country_link");
a.onclick = function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
return false;
}
}
This way the spinner can initially be placed inside the parent, and then be overwritten when the content is returned from the server
| {
"pile_set_name": "StackExchange"
} |
Q:
Two consecutive rows into a table from one form
i have a little problem with a form that must send a picture into a specific folder, and then store the picture name along with other details such as name, email, phone, password into a database.
All work well, with a little problem, when i send my form, in the database there are 2 different rows with different ids, in the first row all the fields are empty except the md5 password field, and on the secound row are all the fields with all the info that i've send into the database. Below i've put the code that i'm using.
$target = "../uploads/";
$target = $target . basename( $_FILES['photo']['name']);
$name = $_POST['name'];
$email = $_POST['email'];
$telefon = $_POST['telefon'];
$password = md5($_POST['password']);
$photo = ($_FILES['photo']['name']);
$result = $mysqli->query("INSERT INTO imobiliare_agenti (id, name, email, telefon, password, photo) VALUES ('$id', '$name', '$email', '$telefon', md5('$password'), '$photo')") ;
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
A:
In php you have added
$password = md5($_POST['password']);
Again in query you have added mysql md5 function.
"INSERT INTO imobiliare_agenti (id, name, email, telefon, password, photo) VALUES ('$id', '$name', '$email', '$telefon', md5('$password'), '$photo')"
Try removing one of the md5 functions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I properly provide places to ship freight?
I have several industries complaining now.
We need somewhere to ship our freight
Need to ship, going out of business
I have built a Trade Depot and added several Freight Shipping Warehouses. Some of them seems to be used (fills up with boxes), but there's lots of free space.
How does freight shipping work really? What am I missing? How do I stop the complaints?
A:
Freight Delivery Truck Respawn
Each industrial building gets its own truck to deliver freight. The truck will locate nearby available orders and attempt delivery. Delivery may involve multiple buildings. All the freight on the truck must be delivered before the return trip starts.
If the truck returns from delivery quickly, it will spawn once per hour - each industrial building has its own timer. This way you get 24 truck deliveries per day.
If the truck is delayed, does not return in one hour (before the next truck would spawn... then the next truck doesn't spawn. The building resets the clock for another hour. This can happen when the gets stuck in traffic, or its freight shipment is far away. In this case, you get less than 24 truck deliveries per day.
For example: if a truck takes 2.5 hours to return, the next truck will spawn in 0.5 hour. The building keeps the timer. If this happens consistently to the same building, you'll get 8 truck shipments per day.
If your city suffers complete gridlock, you may get down to 2 truck shipments per day.
Solving the problem
If you switch to industry view, and you observe an industry building which never hits 0 freight (empty yellow bar) - then you have identified a building that really needs better freight shipping. Either solve the traffic jams, or place a freight accepting building close to the industry. Watch the truck before you try to solve the problem.
Freight accepting buildings include commercial buildings, trade depot with freight attachment, trade port with freight attachment, many service buildings (power, sewage), and the road out of the city (although I haven't seen that last one accept freight yet).
A:
Besides zoning more commercial, the intended solution is to build nearby Trade Depots (Specialization: Trade). Airports can be modified to accept freight as well.
Unfortunately, as of Patch 1.4, industrial buildings will often ignore Trade Depots, even if they are less than a block away. Sometimes they will drive several blocks to get to a Trade Depot, so it appears to be a bug in however they search.
| {
"pile_set_name": "StackExchange"
} |
Q:
Shell Script stops after connecting to external server
I am in the process of trying to automate deployment to an AWS Server as a cool project to do for my coding course. I'm using ShellScript to automate different processes but when connecting to the AWS E2 Ubuntu server. When connected to the server, it will not do any other shell command until I close the connection. IS there any way to have it continue sending commands while being connected?
read -p "Enter Key Name: " KEYNAME
read -p "Enter Server IP With Dashes: " IPWITHD
chmod 400 $KEYNAME.pem
ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com
ANYTHING HERE AND BELOW WILL NOT RUN UNTIL SERVER IS DISCONNECTED
A:
A couple of basic points:
A shell script is a sequential set of commands for the shell to execute. It runs a program, waits for it to exit, and then runs the next one.
The ssh program connects to the server and tells it what to do. Once it exits, you are no longer connected to the server.
The instructions that you put in after ssh will only run when ssh exits. Those commands will then run on your local machine instead of the server you are sshed into.
So what you want to do instead is to run ssh and tell it to run a set of steps on the server, and then exit.
Look at man ssh. It says:
ssh destination [command]
If a command is specified, it is executed on the remote host instead of a login shell
So, to run a command like echo hi, you use ssh like this:
ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com "echo hi"
Or, for longer commands, use a bash heredoc:
ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com <<EOF
echo "this will execute on the server"
echo "so will this"
cat /etc/os-release
EOF
Or, put all those commands in a separate script and pipe it to ssh:
cat commands-to-execute-remotely.sh | ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com
Definitely read What is the cleanest way to ssh and run multiple commands in Bash? and its answers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hide a div in a page and make it visible only on print bootstrap 3 MVC 5
There is a web page showing information to the user. If the user decides to print it I want to include additional information that is not required on the screen, but would be helpful when printed.
In order to implement this behaviour I was trying to make a div visible only for printing. It hasn't worked though:
<div class="visible-print hidden-lg hidden-md hidden-sm hidden-xs">
I'm using Bootstrap 3 and wondered if there is an easy way to accomplish this?
A:
I think the fact you've used
hidden-lg hidden-md hidden-sm hidden-xs
across the div means you've effectively hidden it across all viewports. To simply hide or show a div for print use the following:
<div class="hidden-print">content for non print</div>
<div class="visible-print">content for print only</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Appending a java String one character at a time
I have a very simple question, in fact I'm a bit frustrated that I can't solve this on my own but here it is:
strBuffer += arg.charAt( i );
With this line I'm trying to parse a value and add it character by character to a new string. I'm doing this to seperate a single long string into an array of smaller string.
Example, this string
-time delayed -run auto -mode go_n_run
would become this array
strBuffer [0] = -time
strBuffer [1] = delayed
strBuffer [2] = -run
strBuffer [3] = auto
strBuffer [4] = -mode
strBuffer [5] = go_n_run
So the line of code with the '+=' doesn't work, nothing gets put in my strBuffer. So I've tried something a little more "complex" that I found on a forum :
strBuffer.concat( new String( new char[]{arg.charAt( i )} ) );
But same result, nothing is put in strBuffer,
So, any hints would be appreciated
Thanks
EDIT : Here is the complete method
String[] args = new String[2 * ARG_LIMIT];
int index = 0;
for( int i = 0; i < arg.length(); i++ )
{
String strBuffer = new String();
if( arg.charAt( i ) != ' ' )
{
// The two methods I've tried
strBuffer.concat( new String( new char[]{arg.charAt( i )} ) );
strBuffer += arg.charAt( i );
}
else if( arg.charAt( i ) == ' ' )
{
args[index] = strBuffer;
index++;
strBuffer = "";
}
}
A:
I will assume that strBuffer is an instance of java's StringBuffer; if so - you should use strBuffer.append().
But there's a way simpler method for doing the thing you want:
String[] strBuff = arg.split(" "); //split by space
| {
"pile_set_name": "StackExchange"
} |
Q:
TextTrackList onchange event not working in IE and Edge
The TextTrackList.onchange event is not working in IE and Edge. In Chrome and FireFox it works fine.
Is there any alternative I can use? Ive searched through the available events but can't find any.
Or how can I create a workaround? So it works amongst all browsers?
https://www.javascripture.com/TextTrackList
var video = document.getElementById('video');
video.textTracks.addEventListener('change', function () {
console.log("TextTracks change event fired!");
});
video {
max-width: 400px;
max-height: 400px;
}
<video controls id="video">
<source src="https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_30mb.mp4" type="video/mp4" />
<track label="Caption #1" kind="subtitles" srclang="nl" src="path/to/caption1.vtt">
<track label="Caption #2" kind="subtitles" srclang="en" src="path/to/caption2.vtt">
<track label="Caption #3" kind="subtitles" srclang="de" src="path/to/caption3.vtt">
</video>
A:
You might be able to create a kind of polyfill.
First to detect if we support the event or not, we can check for ('onchange' in window.TextTrackList). So we can integrate our unperfect polyfill conditionally and leave the correct implementations unchanged.
Then, we can iterate every x-time over our TextTrackList's TextTracks in order to find which one is the active one, it should be the one with its mode set to "showing".
Now, we just have to store the previous active track and check if the current one is the same. Otherwise, fire the Event.
So a simple implementation could be
// in an outer scope
// textTracks is our TextTrackList object
var active = getActive();
// start polling
poll();
function poll() {
// schedule next check in a frame
requestAnimationFrame(poll);
var current = getActive();
if (current !== active) {
active = current; // update the active one
// dispatchEvent is not supported on TextTrackList in IE...
onchange({
target: textTracks
});
}
}
function getActive() {
for (var i = 0; i < textTracks.length; i++) {
if (textTracks[i].mode === 'showing') {
return textTracks[i];
}
}
}
But to implement a better polyfill, we will want to override the original addEventListener, removeEventListener and onchange properties of the TextTrackList prototype.
Here is a rough implementation, which will not take care of the third param of [add/remove]EventListener.
(function() {
/* Tries to implement an 'change' Event on TextTrackList Objects when not implemented */
if (window.TextTrackList && !('onchange' in window.TextTrackList.prototype)) {
var textTracksLists = [], // we will store all the TextTrackLists instances
polling = false; // and run only one polling loop
var proto = TextTrackList.prototype,
original_addEvent = proto.addEventListener,
original_removeEvent = proto.removeEventListener;
var onchange = {
get: getonchange,
set: setonchange
};
Object.defineProperty(proto, 'onchange', onchange);
Object.defineProperty(proto, 'addEventListener', fnGetter(addListener));
Object.defineProperty(proto, 'removeEventListener', fnGetter(removeListener));
function fnGetter(fn) {
return {
get: function() {
return fn;
}
};
}
/* When we add a new EventListener, we attach a new object on our instance
This object set as '._fakeevent' will hold informations about
the current EventListeners
the current onchange handler
the parent <video> element if any
the current activeTrack
*/
function initFakeEvent(instance) {
// first try to grab the video element from where we were generated
// this is useful to not run useless tests when the video is detached
var vid_elems = document.querySelectorAll('video'),
vid_elem = null;
for (var i = 0; i < vid_elems.length; i++) {
if (vid_elems[i].textTracks === instance) {
vid_elem = vid_elems[i];
break;
}
}
textTracksLists.push(instance);
instance._fakeevent = {
parentElement: vid_elem,
listeners: {
change: []
}
}
if (!polling) { // if we are the first instance being initialised
polling = true;
requestAnimationFrame(poll); // start the checks
}
return instance._fakeevent;
}
function getonchange() {
var fakeevent = this._fakeevent;
if (!fakeevent || typeof fakeevent !== 'object') {
return null;
}
return fakeevent.onchange || null;
}
function setonchange(fn) {
var fakeevent = this._fakeevent;
if (!fakeevent) {
fakeevent = initFakeEvent(this);
}
if (fn === null) fakeevent.onchange = null;
if (typeof fn !== 'function') return fn;
return fakeevent.onchange = fn;
}
function addListener(type, fn, options) {
if (type !== 'change') { // we only handle change for now
return original_addEvent.bind(this)(type, fn, options);
}
if (!fn || typeof fn !== 'object' && typeof fn !== 'function') {
throw new TypeError('Argument 2 of EventTarget.addEventListener is not an object.');
}
var fakeevent = this._fakeevent;
if (!fakeevent) {
fakeevent = initFakeEvent(this);
}
if (typeof fn === 'object') {
if (typeof fn.handleEvent === 'function') {
fn = fn.handleEvent;
} else return;
}
// we don't handle options yet...
if (fakeevent.listeners[type].indexOf(fn) < 0) {
fakeevent.listeners[type].push(fn);
}
}
function removeListener(type, fn, options) {
if (type !== 'change') { // we only handle change for now
return original_removeEvent.call(this, arguments);
}
var fakeevent = this._fakeevent;
if (!fakeevent || !fn || typeof fn !== 'object' && typeof fn !== 'function') {
return
}
if (typeof fn === 'object') {
if (typeof fn.handleEvent === 'function') {
fn = fn.handleEvent;
} else return;
}
// we don't handle options yet...
var index = fakeevent.listeners[type].indexOf(fn);
if (index > -1) {
fakeevent.listeners[type].splice(index, 1);
}
}
function poll() {
requestAnimationFrame(poll);
textTracksLists.forEach(check);
}
function check(instance) {
var fakeevent = instance._fakeevent;
// if the parent vid not in screen, we probably have not changed
if (fakeevent.parentElement && !fakeevent.parentElement.parentElement) {
return;
}
// get the current active track
var current = getActiveTrack(instance);
// has changed
if (current !== fakeevent.active) {
if (instance.onchange) {
try {
instance.onchange({
type: 'change',
target: instance
});
} catch (e) {}
}
fakeevent.listeners.change.forEach(call, this);
}
fakeevent.active = current;
}
function getActiveTrack(textTracks) {
for (var i = 0; i < textTracks.length; i++) {
if (textTracks[i].mode === 'showing') {
return textTracks[i];
}
}
return null;
}
function call(fn) {
fn({
type: 'change',
target: this
});
}
}
})();
var video = document.getElementById('video');
video.textTracks.onchange = function ontrackchange(e) {
console.log('changed');
};
video {
max-width: 400px;
max-height: 400px;
}
<video controls id="video">
<source src="https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_30mb.mp4" type="video/mp4" />
<track label="Caption #1" kind="subtitles" srclang="nl" src="path/to/caption1.vtt">
<track label="Caption #2" kind="subtitles" srclang="en" src="path/to/caption2.vtt">
<track label="Caption #3" kind="subtitles" srclang="de" src="path/to/caption3.vtt">
</video>
| {
"pile_set_name": "StackExchange"
} |
Q:
LibGDX dual assets setup, Eclipse, Gradle
I have decided to use two different sets of assets for desktop and android but I am not sure what the best way to do this would be? If anyone got some tip or suggestion on how to streamline this I would appreciate it!
I am using Eclipse and Gradle.
A:
You can use two different assets folders. No one is forcing you to share assets for all platforms.
In build.gradle of Android project you can locate and modify assets.srcDirs = ['assets'] line. It stores a relative path to the assets folder. Since you want to keep separate assets for mobiles (or at least the Android version), I suggest you leave it as it is, though - just keep the android/assets folder as usual and store mobile assets there.
As for the desktop project, assets are referenced two times in build.gradle: in project.ext.assetsDir = new File("../android/assets"); and linkedResource name: 'assets', type: '2', location: 'PARENT-1-PROJECT_LOC/android/assets'. As you can see, they both store (sorta) relative paths that you can safely replace. Creating a new desktop/assets folder makes sense if you want to keep a similar folder structure. These two lines would be simply replaced with project.ext.assetsDir = new File("assets"); and linkedResource name: 'assets', type: '2', location: 'PARENT-1-PROJECT_LOC/desktop/assets' - and then you can just import the project as usual.
Note that this answer assumes that you generated your project with the default gdx-setup app. The default LibGDX project generator usually does not handle assets folder linking for you, so just remember to mark the new desktop/assets folder as resource in Eclipse.
| {
"pile_set_name": "StackExchange"
} |
Q:
Different citation styles for different entry types in the footnotes (biblatex-dw)
Problem
I am using biblatex together with the authortitle-dw style. As it is desired in most cases, citations show up in the footnotes in the form "name, shorttitle, pages (if indicated)".
However, as a historian, I work with a great amount of unpublished documents I've collected in various archives. To deal with these, I have modified the entrytype @unpublished in a rather dilettantish way (I guess).
The problem is that in the footnotes, as it is expectable, only the title of my unpublished documents appears, while in this special case a full citation in the form "title, in: archive, shelf, Bd. box" would be desirable.
The \fullcite command doesn't work for me here, because it doesn't allow the content of certain fields to be replaced by "ibid.", which is absolutely necessary.
Example
Here's my MWE:
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage[
style=authortitle-dw
]{biblatex}
\DefineBibliographyStrings{ngerman}{
chapter = {Bd.}
}
\DeclareBibliographyDriver{unpublished}{%
\usebibmacro{bibindex}%
\usebibmacro{begentry}%
\usebibmacro{title}%
\newunit
\usebibmacro{in:}%
\printlist{institution}%
\newunit\newblock
\printlist{location}%
\newunit\newblock
\printfield{chapter}%
\newunit\newblock
\setunit{\bibpagerefpunct}\newblock
\usebibmacro{pageref}%
\usebibmacro{finentry}}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@unpublished {test1,
title = {Source1},
institution = {Archive1},
location = {Shelf1},
chapter = {Box1}
}
@unpublished {test2,
title = {Source2},
institution = {Archive1},
location = {Shelf1},
chapter = {Box2}
}
@unpublished {test3,
title = {Source3},
institution = {Archive1},
location = {Shelf1},
chapter = {Box2}
}
\end{filecontents}
\addbibresource{\jobname.bib}
\begin{document}
\footcite{test1}
\footcite{test2}
\footcite{test3}
\end{document}
This example produces the following output:
1 Source1
2 Source2
3 Source3
However, the way I'd like to have it is the following:
1 Source1, in: Archive1, Shelf1, Bd. Box1
2 Source2, in: ibid., Bd. Box2
3 Source3, in: ibid.
Is it possible to achieve this in any way?
A:
By default, the authortitle-dw style makes "short" citations, i.e. something consisting of the author name and the title (and some other things, according to options set). Your @unpublished entries have only title as a "relevant" field for the short citation so this will be the only field printed.
As you've written your own bibliography driver for this format anyway, it will probably be easiest to use full citations and adapt your driver accordingly.
Looking into authortitle-dw.cbx, both \cite and \footcite call the bibmacro cite, which does the actual work. The original code is
\newbibmacro*{cite}{%
\usebibmacro{cite:citepages}%
\global\boolfalse{cbx:loccit}%
\ifbool{cbx:firstfull}
{\ifciteseen
{\usebibmacro{cite:normal}}
{\usebibmacro{cite:firstfull}}}
{\usebibmacro{cite:normal}}}
i.e. if the option firstfull is given and the item is cited for the first time, the bibmacro cite:firstfull is called, otherwise cite:normal is called. We can adapt this slightly to force a full citation for every item of type @unpublished. This is done using the biblatex macro \ifentrytype. Note that this should occur before checking the option firstfull so that the behaviour is not affected by the (un)setting of that option.
\renewbibmacro*{cite}{%
\usebibmacro{cite:citepages}%
\global\boolfalse{cbx:loccit}%
\ifentrytype{unpublished}%
{\ifciteibid{\usebibmacro{cite:ibid}}%
{\usebibmacro{cite:firstfull}}}%
{\ifbool{cbx:firstfull}%
{\ifciteseen%
{\usebibmacro{cite:normal}}
{\usebibmacro{cite:firstfull}}}
{\usebibmacro{cite:normal}}}%
\usebibmacro{savestuff}%
}
Note that in case the same item was cited just before, "ibid" (or your local alternative) is printed and nothing else, by use of the biblatex check \ifciteibid and the bibmacro cite:ibid. You may, in practice, want to combine this with \iffirstonpage to check if the preceding item was on the last (double) page and only use the ibid in case the item referred to is actually on the same page, i.e.
\ifthenelse{\ifciteibid\and\not\iffirstonpage}%
{\usebibmacro{cite:ibid}}{\usebibmacro{cite:firstfull}}%
This will stop any citation being replaced by "ibid" if it is the first to occur on a new (double) page, i.e. on a different page than the citation being referenced by the "ibid".
This approach has the advantage that the bibliography driver you wrote is used for every citation so that is the only thing you need to worry about.
Next, you need to tell biblatex to replace repeating occurrences of your fields by "ibid" (or "idem" or whatever seems most appropriate ;)). As only the entire entry and the main fields (author, editor, title ...) are checked automatically, we need to do this manually, e.g. by defining a bibmacro
\newbibmacro{savestuff}{%
\savelist{institution}{\lastinstitution}%
\savelist{location}{\lastlocation}%
\savefield{chapter}{\lastchapter}}
saving all the current values of fields to macros to be compared to in the next citation. This should be called not only in this bibliography driver but whenever anything is cited or put in the bibliography, otherwise the next @unpublished will be compared to the last @unpublished, not to the previous citation/bibliography entry. For citations, this can be achieved by placing it into the (redefined) cite bibmacro. To "automatically" have it included in all bibliography drivers, one can append it to the finentry bibmacro which seems to be called by all authortitle-dw bibliography drivers. This can be done with the help of the xpatch package (see also biblatex: Is it possible to patch macros created with \newbibmacro?)
\xapptobibmacro{finentry}{\usebibmacro{savestuff}}{}{}
Now, instead of just saying
\printlist{location}%
you should say something like
\iflistequals{institution}{\lastinstitution}%
{\bibstring{ibidem}}%
{\printlist{institution}}%
to replace the field institution by the bibstring associated to ibidem.
As I understand it, for the fields location and chapter, you want to either print the field if it contains "new" information or omit it entirely, if it matches the preceding entry. This can be achieved by nesting tests:
\iflistequals{institution}{\lastinstitution}%
{\bibstring{ibidem}%
\newunit\newblock%
\iflistequals{location}{\lastlocation}%
{\iffieldequals{chapter}{\lastchapter}%
{}{\printfield{chapter}}}%
{\printlist{location}\newunit\newblock%
\iffieldequals{chapter}{\lastchapter}%
{\bibstring{ibidem}}%
{\printfield{chapter}}}%
}%
{\printlist{institution}\newunit\newblock%
\iflistequals{location}{\lastlocation}%
{\bibstring{ibidem}\newunit\newblock%
\iffieldequals{chapter}{\lastchapter}%
{}{\printfield{chapter}}}%
{\printlist{location}\newunit\newblock%
\iffieldequals{chapter}{\lastchapter}%
{\bibstring{ibidem}}%
{\printfield{chapter}}}%
}%
(Possibly a "cleaner" solution is available, similar to the use of the punctuation tracker of biblatex ....).
To ensure that this complies with the "no ibid for the first entry on a page" rule, either all conditionals should be extended (as above) to also check \iffirstonpage or, alternatively, we can check \iffirstonpage at the beginning of the bibliography driver and if this is the case, simply delete (or put something "impossible" into) the stored data so the comparison will be negative, e.g.
\iffirstonpage{\def\lastinstitution{}%
\def\lastlocation{}%
\def\lastchapter{}}{}%
In any case, this is the complete file (with the biblatex-dw option firstfull):
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{xpatch}
\usepackage[
style=authortitle-dw,
firstfull=true
]{biblatex}
\DefineBibliographyStrings{ngerman}{
chapter = {Bd.}
}
\renewbibmacro*{cite}{%
\usebibmacro{cite:citepages}%
\global\boolfalse{cbx:loccit}%
\ifentrytype{unpublished}%
{\ifthenelse{\ifciteibid\and\not\iffirstonpage}%
{\usebibmacro{cite:ibid}}{\usebibmacro{cite:firstfull}}}%
{\ifbool{cbx:firstfull}%
{\ifciteseen%
{\usebibmacro{cite:normal}}
{\usebibmacro{cite:firstfull}}}
{\usebibmacro{cite:normal}}}%
\usebibmacro{savestuff}%
}
\newbibmacro{savestuff}{%
\savelist{institution}{\lastinstitution}%
\savelist{location}{\lastlocation}%
\savefield{chapter}{\lastchapter}}
\xapptobibmacro{finentry}{\usebibmacro{savestuff}}{}{}
\DeclareBibliographyDriver{unpublished}{%
\iffirstonpage{\def\lastinstitution{}%
\def\lastlocation{}%
\def\lastchapter{}}{}%
\usebibmacro{bibindex}%
\usebibmacro{begentry}%
\usebibmacro{title}%
\newunit
\usebibmacro{in:}%
\iflistequals{institution}{\lastinstitution}%
{\bibstring{ibidem}%
\newunit\newblock%
\iflistequals{location}{\lastlocation}%
{\iffieldequals{chapter}{\lastchapter}%
{}{\printfield{chapter}}}%
{\printlist{location}\newunit\newblock%
\iffieldequals{chapter}{\lastchapter}%
{\bibstring{ibidem}}%
{\printfield{chapter}}}%
}%
{\printlist{institution}\newunit\newblock%
\iflistequals{location}{\lastlocation}%
{\bibstring{ibidem}\newunit\newblock%
\iffieldequals{chapter}{\lastchapter}%
{}{\printfield{chapter}}}%
{\printlist{location}\newunit\newblock%
\iffieldequals{chapter}{\lastchapter}%
{\bibstring{ibidem}}%
{\printfield{chapter}}}%
}%
\newunit\newblock%
\setunit{\bibpagerefpunct}\newblock
\usebibmacro{pageref}%
\usebibmacro{finentry}}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@unpublished {test1,
title = {Source1},
institution = {Archive1},
location = {Shelf1},
chapter = {Box1}
}
@unpublished {test2,
title = {Source2},
institution = {Archive1},
location = {Shelf1},
chapter = {Box2}
}
@unpublished {test3,
title = {Source3},
institution = {Archive1},
location = {Shelf1},
chapter = {Box2}
}
@article{test4,
title={something},
author={someone}
}
\end{filecontents}
\addbibresource{\jobname.bib}
\begin{document}
\footcite{test1}
\footcite{test1}
\footcite{test4}
\footcite{test1}
\footcite{test2}
\footcite{test3}
\footcite{test1}
\footcite{test4}
\clearpage
\footcite{test1}
\printbibliography
\end{document}
and the result (in footnotes):
The footnote on the second page contains no "ibid" because even though identical to the previous one, its the first on its page (note that this requires two run-throughs to work!):
The bibliography looks like this:
Note: This solution produces identical behaviour in the bibliography and citations. If this is not desired (especially regarding the ibidem stuff), use the biblatex checks \ifcitation and \ifbibliography, respectively, to treat the various sub-cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why NSIS return this error "Invalid command: SetRegView"
I'm trying to use this command SetRegView 64 on NSIS script but the compiler says it is a invalid command.
A:
Including the exact compiler error message in your question would help...
SetRegView was added in v2.26 so you are really out of date if you don't have a version that supports it. It can only be used in a Function or Section but it should warn you if you use it somewhere else.
Section
SetRegView 64
WriteRegStr HKCU Software\... ...
SectionEnd
| {
"pile_set_name": "StackExchange"
} |
Q:
how does `ls "*" 2>&1 | tee ls.txt` work?
I was finding a way to save all output to a file and print it.
And the command like the following does work perfectly!
ls "*" 2>&1 | tee ls.txt
But I think I don't understand it well.
And I tried ls "*" | tee ls.txt. It doesn't work. The error message was not saved into ls.txt.
Also I tried ls "*" 1>&2 | tee ls.txt. It behaved some strange. What happened?
A:
2>&1 says "redirect stderr (2) to wherever stdout (1) goes". 1 and 2 are the file descriptors of stdout and stderr respectively.
When you pipe ls output to tee, only stdout goes to tee (without 2>&1). Hence, the error messages are not saved into ls.txt.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between MVC 3 Partial Page (Razor) and MVC 3 View Page with Layout (Razor)?
In MVC 3 Beta, is there a difference between the templates MVC 3 Partial Page (Razor) and MVC 3 View Page with Layout (Razor) ?
I added a partial page (_partialList) to my application. Now when I return only the partial view, it applies the Layout present in _ViewStart.cshtml - acting very much like a stardard view page with layout.
if (Request.IsAjaxRequest())
return View("_partialList", someModelData);
How does a "partial" page distinguish itself from a standard view page with layout ? Will the two behave differently in any particular scenario?
A:
If you don't want to apply the layout return a PartialView instead of View:
if (Request.IsAjaxRequest())
return PartialView("_partialList", someModelData);
A:
Darin's response solves your practical issue of not wanting the layout to be applied.
Regarding the difference between the two, in Razor they are practically the same because both full pages and partials use the same extension and have the same base class.
The reason why there is different UI is because in the Web Forms view engine the two are implemented with different extensions and different base classes, which is why to seperate templates are necessary.
A:
Add the following code to your page, and the view engine will not apply the layout to it.
@{
Layout = null;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Code to create and check a numeric password
I am very new to coding and I have created this relatively simple code to do with my basic knowledge of the language. However I have had to do with some unwanted code including shutting it down if password is too long. so could anybody help me with any improvements to this?
import time
passwordx = float(input('create your password'))
def password():
passwordx
if passwordx>9999:
print('password is wrong\n innitiating shutdown')
x=5
time.sleep(1)
print(x)
x-=1
time.sleep(1)
print(x)
x-=1
time.sleep(1)
print(x)
x-=1
time.sleep(1)
print(x)
x-=1
time.sleep(1)
print(x)
x-=1
time.sleep(1)
print(x)
x-=1
quit()
else:
print('code saved')
x=1
while x <1000:
print('###############')
x+=1
def login():
passwordguess = float(input('please enter password'))
if passwordguess == passwordx:
print('access granted')
else:
print('wrong')
print('here\'s a clue', (passwordx-passwordguess)**2)
login()
password()
login()
A:
A couple of things:
Start using range.
Range is the recommended way to loop in Python.
And you can change your shutdown sequence, and while loop to use it.
This improves the clarity of your code, which is good for when others read it.
And even if no-one else will, it's always good to get good habits.
Reduce the amount of unneeded messages to the end user.
Here less is more.
Seriously, I was used to overly verbose messages when I was on windows.
And then I installed Linux and would most of the time get no feedback.
To change my keyboard layout I use loadkeys dvorak, and I get no message.
I create a file, touch file, and again no message.
The only time I get a message is if that's the intent of the command, ls, or if it's an error.
Honestly you should probably take a leap out of their book.
It's normally best to avoid recursion.
I once made a program that heavily used recursion,
it exceeded the recursion limit and there was no way for me to fix it.
I can assure you I never touched that project again.
Instead I'd use a while loop.
Use getpass.
This removes the need to display a lot of hashes to remove the password from display.
As it never displays in the first place.
Change password to create the password.
This way the method of creating a password is always the same.
Change login to take the password as an argument.
This is as it removes reliance on globals which is always a good thing.
You should check the input is a number, otherwise you program will exit with an error.
from time import sleep
from getpass import getpass # 4
def create_password(): # 5
password = getpass('Create your password: ') # 4, 5
try: # 7
password = float(password)
except ValueError:
quit()
if password > 9999:
print('Password is invalid, initiating shutdown.')
for i in range(5, -1, -1): # 1
time.sleep(1)
print(i)
quit()
return password # 5
def login(password): # 6
while True: # 3
password_guess = float(input('Please enter password: '))
if password_guess == password:
break # 3
else:
print("Wrong. Here's a clue", (password - password_guess) ** 2)
password = create_password()
login(password)
The above shows how I'd change your code if I were to keep the messages you added special code for.
I still think most of your messages are not needed, and so I'd remove more of them.
I also dislike your clue, as it's ridiculously insecure.
And due to floating point inaccuracy I'd store the password as a string.
Resulting in:
from getpass import getpass
def create_password(): # 5
password = getpass('Create your password: ')
try:
float(password)
except ValueError:
quit()
if float(password) > 9999:
quit()
return password
def login(password):
while True:
password_guess = input('Please enter password: ')
if password_guess == password:
break
password = create_password()
login(password)
Finally I'd think about removing the float(password) > 9999.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery Mobile navigate or changePage?
With the arrival of jQuery Mobile 1.3, the .navigate() function has been added. I've heard that is the recommended way to change pages, and it seems they addressed the issues of transferring data between pages.
The problem is, since it has been simplified, how do I access the other options that changePage offered? I would really like to use the {data} portion of the .navigate() but I would also like to set a few options that I do normally with changePage (such as transition, direction, etc).
I currently have a "router" that listens for all navigate events, then passes along any data that it receives on to the next page (doing some other simple logic as well, like setting up the views controller).
Is there some hidden properties in the [,options] that I would be able to set up simple things like direction and transition?
A:
$.mobile.navigate is still a new function, according to code comments it is also a work in progress.
Transition is active among hidden options;
$.mobile.navigate( "#bar", { transition : "slide", info: "info about the #bar hash" });
Working example: http://jsfiddle.net/Gajotres/g5vAN/
On the other hand, change to direction reverse is still not implemented, default false value is applied.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Remote Logging through HTTPS 443
If I have a java applet for a site, is it possible to do remote logging through HTTPS? how does this work?
I know there is java sockethandler, which could direct the log to a server, but what should I do in the server side, so I can get the log and save it to a file in the server. I try to create a logserver app and put it on server but if I specify port 443, it will say
`java.net.BindException: Address already in use: JVM_Bind`
Can someone point me out and give some examples what should I do in the applet side and server side?
A:
On that server TCP port 443 is already in use - therefore you have to use a different port.
SSL does work on any port - 443 is just the standard port for HTTPS. Therefore if you start your SSLServerSocket you can bind it to any port.
If your applet used port 1234, then in your Applet you can use an SSLSocket instance and let it connect to your server URL and port.
Note that most likely you are using a self-signed certificate. In that case you have to embed the custom certificate in your applet and set it as trusted certificate when opeing the SSL connection.
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL INSERT if record exists in another table
having a little trouble with a query that I'd like to keep to just one query. Basically, I have two tables, users, and relationships. Users have an ID, the relationships table has user_a and user_b fields which contain users.id values, which matches users up as 'user_a follows user_b'.
Now I'm hitting the Twitter API to pull in user_a's followers (https://dev.twitter.com/docs/api/1/get/friends/ids) but people in the users table are people attending an event, and not necessarily in user_a's friends. I need to execute an INSERT in the relationships table if user_b exists in the users table.
Here's what I have so far!
$json = file_get_contents('https://api.twitter.com/1/friends/ids.json?cursor=-1&user_id=' . $this->_attendee->id);
$response = json_decode($json);
if($response->ids){
foreach($response->ids as $friend){
// query goes here
}
}
A:
Build a select statement that returns the line you want to add exactly if the user entry exists. Then do INSERT INTO user_a SELECT YOUR_STATEMENT;
eg. INSERT INTO user_a SELECT uid, "value1", 2, "some other string" FROM user_b WHERE uid=$friend;
| {
"pile_set_name": "StackExchange"
} |
Q:
Action bar: about up affordance icon
In action bar, there is an icon called "up affordance" showed below (the left-most one):
In my Activity onCreate() method, I have set the following things:
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
My Question is:
how can I implement an onClickListener on this "up affordance" icon, so that when user click on it, the application will be navigated to the upper level hierarchy ?
how can I have only the left arrow without the android default icon of "up affordance" part on action bar?
A:
For implementing an onClickListener, instead just catch it in onOptionsItemSelected:
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// Do what you want here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
For question two, this page states:
Using a logo instead of icon
By default, the system uses your application icon in the action bar, as specified by the android:icon attribute in the or element. However, if you also specify the android:logo attribute, then the action bar uses the logo image instead of the icon.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way I can create a custom dictionary in python without copy method?
I am having a use case where I want to store a key value pair in dictionary.
The problem I'm facing is my key is 'copy'. So after inserting 'copy' key, I'm not able to access it via getattr method, since it always returns the copy method of dict.
I cannot use get method on dict because my code is unaware of the type of object that is being passed. So, I went ahead with using getattr which is generic function to access properties.
I also created a custom class inheriting from dict and wrote getattribute but that blocks access to methods
class DictLike(dict):
def __getattribute__(self, k):
try:
return self[k]
except KeyError:
getattr(super(DictLike, self), k)
def paste(self):
return "Test"
a = DictLike()
a['copy'] = 1;
a['state'] = 'completed'
print(getattr(a, 'copy')) // prints 1
print(a.paste()) // this does not works
b = {'copy': 1}
print(b.get('copy')) \\ 1
getattr(b, 'copy') \\ function
Is there a way I could fix this behavior ?
A:
Here is the working solution:
class DictLike(dict):
def __init__(self, *args, **kw):
super(DictLike, self).__init__(*args, **kw)
self.itemlist = super(DictLike, self).keys()
def __getattribute__(self, k):
try:
return self[k]
except Exception as e:
return super().__getattribute__ (k)
def paste(self):
return "Test"
a = DictLike()
a['copy'] = 1
a['state'] = 'completed'
print(getattr(a, 'copy'))
print(a.paste())
| {
"pile_set_name": "StackExchange"
} |
Q:
Palette API not working (Works only when I'm debugging)
I created a simple RecyclerView and a CardView in it. In CardView there are ImageView and TextView. So I'm get the url of the image and load it using Picasso. Everything worked well before using Palette API. So I want to get the color from image and set it to CardView and TextView.
Here's my RecyclerView.Adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private List<String> imagesUrl;
private List<String> imageDescription;
RecyclerAdapter(List<String> imagesUrl, List<String> imageDescription) {
this.imagesUrl = imagesUrl;
this.imageDescription = imageDescription;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, int position) {
myViewHolder.textView.setText(imageDescription.get(position));
Picasso.get()
.load(imagesUrl.get(position))
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
myViewHolder.imageView.setImageBitmap(bitmap);
myViewHolder.getPalette();
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
myViewHolder.imageView.setImageResource(R.drawable.error);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
myViewHolder.imageView.setImageResource(R.drawable.placeholder);
}
});
}
@Override
public int getItemCount() {
return imagesUrl.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView textView;
private CardView cardView;
MyViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
cardView = itemView.findViewById(R.id.cardView);
}
private void getPalette() {
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(@Nullable Palette palette) {
//assert palette != null;
Palette.Swatch swatch = palette.getVibrantSwatch();
//assert swatch != null;
textView.setTextColor(swatch.getBodyTextColor());
cardView.setCardBackgroundColor(swatch.getRgb());
}
});
}
}
}
Every time it shows the placeholder image. When I'm doing debug, it works. So what's the problem?
A:
So problem is not in Palette API. Problem is that target is being garbage collected.So the solution is to implement it on an object or store it in a field and set it as tag to our ImageView.
Here. That's now working.
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, int position) {
myViewHolder.textView.setText(imageDescription.get(position));
Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
myViewHolder.imageView.setImageBitmap(bitmap);
myViewHolder.getPalette();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
myViewHolder.imageView.setImageResource(R.drawable.error);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
myViewHolder.imageView.setImageResource(R.drawable.placeholder);
}
};
Picasso.with(context)
.load(imagesUrl.get(position))
.into(target);
myViewHolder.imageView.setTag(target);
}
I think this will help anyone someday))) Thank you
| {
"pile_set_name": "StackExchange"
} |
Q:
コマンドラインのショートオプションの大文字小文字の使い分け
背景
PythonでCLIツールを作成しています。
コマンドライン引数のパースは、argparseモジュールで行っています。
考えていること
ロングオプションからショートオプション名を考えています。
質問
ショートオプションで大文字/小文字は、どう使い分ければよいですか?
Command-Line Options - The Art of Unix Programmingに載っているショートオプションには、-dも-Dもありました。
上記サイトには、ショートオプションに関して、次のように述べています。
大文字よりは小文字がよい
大文字は、小文字オプションの特別な変形として使うのがよい
In this style, lowercase options are preferred to uppercase. When you use uppercase options, it's good form for them to be special variants of the lowercase option.
「特別な変形」とは具体的に、どのようなことを指しているのでしょうか?
参考にしたサイト
Are there standards for Linux command line switches and arguments?
Table of Long Options - GNU Coding Standards
コマンドラインツールのショートオプションをどの用途で使うべきか
A:
「特別な変形」とは具体的に、どのようなことを指しているのでしょうか?
Gitのbranchコマンドを例にすると、
-dは「ブランチの削除」で、予めマージをしていないと削除ができません。
-Dは「ブランチの強制削除」で、マージをしていなくても削除が出来ます (-d --force相当)。
通常の小文字オプションなら警告などが表示されるけど、大文字の入力で手間をかけさせる分その警告を無視させるようなイメージです。
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert a list of lists of items to dummies in pandas
I have a list of lists of items like this:
lgenre[8:15]
[['Action'],
['Action', 'Adventure', 'Thriller'],
['Comedy', 'Drama', 'Romance'],
['Comedy', 'Horror'],
['Animation', "Children's"],
['Drama'],
['Action', 'Adventure', 'Romance']]
What I want is:
id Action Adventure Thriller Comedy Drama Romance Horror Animation Children's
0 0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
2 2 0 0 0 1 1 1 0 0 0
3 3 0 0 0 1 0 0 1 0 0
4 4 0 0 0 0 0 0 0 1 1
5 5 0 0 0 0 1 0 0 0 0
6 6 1 1 0 0 0 1 0 0 0
What I tried is to write a double loop which looks like this:
stor=pd.DataFrame({'id':list(range(len(lgenre[8:15])))})
for num,list in enumerate(lgenre[8:15]):
for item in list:
try:
stor[item][num]=1
except:
stor[item]=0
stor[item][num]=1
Although it is compilable, it is too slow to implement.
Is there any efficient way to do this kind of thing?
Any better algorithm or built-in method?
A:
Build a dataframe from the nested list, and use pd.get_dummies:
df = pd.get_dummies(pd.DataFrame(l))
df.columns = df.columns.str.split("_").str[-1]
Action Animation Comedy Drama Adventure Children's Drama Horror \
0 1 0 0 0 0 0 0 0
1 1 0 0 0 1 0 0 0
2 0 0 1 0 0 0 1 0
3 0 0 1 0 0 0 0 1
4 0 1 0 0 0 1 0 0
5 0 0 0 1 0 0 0 0
6 1 0 0 0 1 0 0 0
Romance Thriller
0 0 0
1 0 1
2 1 0
3 0 0
4 0 0
5 0 0
6 1 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Environment/system variables in server.xml
How can I use environment/system variables in tomcat server.xml, context.xml, etc configuration files?
I tried to use ${ENV_VAR_NAME} (both for environment and system variable), ${env.ENV_VAR_NAME} (for environment variables). And nothing seems to work.
A:
How it's realized in my box.
Bash-script for startup:
#!/bin/sh
SMEMORY=1G
XMEMORY=1G
if [ $ENV == DEV ]; then
port_shutdown="8005"
port_http="8080"
port_https="8443"
elif
[ $ENV == SIT ]; then
port_shutdown="8006"
port_http="8081"
port_https="8444"
elif
[ $ENV == UAT ]; then
port_shutdown="8007"
port_http="8082"
port_https="8445"
else
echo "Unknown ENV"
exit 1
fi
export CATALINA_OPTS=" ${SYSTEM_PROPS} -d64 -server -Xms$SMEMORY -Xmx$XMEMORY \
-XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=64M \
-XX:+HeapDumpOnOutOfMemoryError -XX:MaxPermSize=1024M \
-Dport.http=${port_http} -Dport.https=${port_https} -Dport.shutdown=${port_shutdown}"
exec $CATALINA_HOME/bin/startup.sh
In server.xml:
<Connector
port="${port.http}"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="${port.https}"
/>
Take a look at process:
$ ps ux | grep tomcat
... -Xms1G -Xmx1G ... -Denv=KIEV_DEV... -Dport.http=8084 -Dport.https=8446 -Dport.shutdown=8008...
Check ports:
$ netstat -anp | grep java
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp 0 0 :::8084 :::* LISTEN 23343/java
tcp 0 0 :::8446 :::* LISTEN 23343/java
A:
Environment variables can be referenced in the server.xml etc by setting the system property org.apache.tomcat.util.digester.PROPERTY_SOURCE to the value org.apache.tomcat.util.digester.Digester$EnvironmentPropertySource.
That system property has been available since 7.0, but EnvironmentPropertySource was not mentioned in the doc until 8.5.
https://tomcat.apache.org/tomcat-9.0-doc/config/systemprops.html
Update (April 2020):
The latest tomcat releases (9.0.34, 8.5.54) now support property replacement in most configuration files:
https://tomcat.apache.org/tomcat-9.0-doc/changelog.html#Tomcat_9.0.34_(markt)
| {
"pile_set_name": "StackExchange"
} |
Q:
Next.js React component getInitialProps doesn't bind props
In Next.js, you can use in your React components a lifecycle method bound to the server side rendering on first load.
I tried to use this function as presented in the ZEIT tutorial (alternatively on their Github), but this.props doesn't seem to get JSON returned by the function.
When I click on the component, console print an empty object.
import React from 'react'
import 'isomorphic-fetch'
export default class extends React.Component {
static async getInitialProps () {
const res = await fetch('https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json')
const data = await res.json()
return { data }
}
print() {
console.log(this.props);
}
render() {
return <div onClick={this.print.bind(this)}>print props</div>
}
}
A:
I had this issue due to a problem in my _app.js (i.e. NextJS Custom App) which I caused while adding in Redux (not a Redux issue). As soon as I started using getInitialProps in a page my props were empty at render though data was there in the static call. The cause was the incorrect propagation of pageProps in my _app.js.
So in my case the fix was changing, in custom _app.js getInitialProps, this:
return {
...pageProps,
initialReduxState: reduxStore.getState()
}
to:
return {
pageProps: {...pageProps},
initialReduxState: reduxStore.getState()
}
.. so the render method as seen in the NextJS doc link could wire them through.
| {
"pile_set_name": "StackExchange"
} |
Q:
Replace Vintage Shimano Trigger Shifter
I have a Cannondale M600 Red White & Blue.
My 7 speed Shimano integrated trigger shifter will no longer function.
I cannot tell the model
I cannot fix it nor find an identical replacement what other compatible Shimano shifters Can I use?
A:
Looking up the M600 on Bicycle Blue Book, it seems it was outfitted with Shimano STX SE Rapidfire shifters to work the 3x7 drivetrain. A Google search of "Shimano STX SE Rapid fire Shifter" yielded several results, including many videos on fixing a problematic STX shifter and it's rapid fire cousins. You dont describe the specific problem with yours but often with these types of shifters, the pawls become stuck with old dried grease and dirt and thus the shifting is unreliable or non-existent. Removing the cover and dousing the innards with WD-40 or similar degreaser while working the levers will clean the mechanism, freeing up the pawls, restoring their motion, and the shifter begins to function anew. Follow up the cleaning with application of a better lubricating spray grease and you may have a reconditioned shifter to use. Details can be found in several videos offered by search engine. Here's one such video.
Should you want or need replacement STI's, Shimano's current and readily available model, ST-EF500, is a 3x7 set-up and would be a drop in replacement. However if it's original, stock equipment you must have, the same search as above contained hits of the STX for sale, even a couple NOS (New Old Stock).
| {
"pile_set_name": "StackExchange"
} |
Q:
data structure problems
Please help me in finding the optimized solutions to these interesting data structure questions:
Given a file containing approx 10 million words, design a data structure for finding the anagrams
Write a program to display the ten most frequent words in a file such that your program be efficient in all complexity measures.
You have a file with millions of lines of data. Only two lines are identical; the rest are all unique. Each line is so long that it may not even fit in the memory. What is the most efficient solution for finding the identical lines?
Adding some more questions:
4) (asked by MS) You are given an array of Strings of length 3. One of the string in the array is marked as Start string and another one as End string. You have to convert start string to end string, given the condition that the intermediate string which you will make should differ from its previous string by only one character and the string should be present in the input array.
eg. If input is
Array: {"fat", "tab", "eat", "see", "tub", "fab", "rat", "sel"}
Start: "fat"
End: "tub"
Then the output should be
fat -> fab -> tab -> tub
I had tried to solve the third one and had come up with two possible appraoches:
1) Read only the first word of all the lines and then eliminate all those lines whose first word does not match the first word of any other line. Keep getting the successive words of the remaining lines in this manner until you are left with just two lines. You got your answer!
2) Convert each line into a smaller representation. This can be achieved by coding each word in short binary form and then XORing the bits representing each line.
Edit: I now have a good collection of data-structure problems with me, if anyone is interested in discussing them here, then I can post some more.
A:
The solution which I proposed for the 4th question was to make a graph of all the words in the array.
First create an adjacency matrix which will have a value 1 if a word can be directly converted to another word.
Now use depth first search to find a path from Start string to End string and return the path if found.
Note that you will have to modify the depth first search here to store the path which you have traversed till now. For this, instead of pushing the node which is being visited to Stack, I pushed the complete path till now to the stack, so that when the element is found, I have the complete path from the Start string to the End string.
| {
"pile_set_name": "StackExchange"
} |
Q:
The mappings are inconsistent with each other
I have problem with inconsistent mappings. I have in my application two entities - Contact (entity with contacts...) and Information, entities with informations to this contact (phones, emails, fax, websites etc.).
And In my Contact entity I made variables for each type, I need it in my application because this way is much easier:
/**
* @ORM\OneToMany( targetEntity = "RelationInformations" , mappedBy = "objectID", cascade={"persist"} )
*/
protected $contactInformations;
/**
* @ORM\OneToMany( targetEntity = "RelationInformations" , mappedBy = "objectID", cascade={"persist"} )
*/
protected $contactPhone;
/**
* @ORM\OneToMany( targetEntity = "RelationInformations" , mappedBy = "objectID", cascade={"persist"} )
*/
protected $contactFax;
/**
* @ORM\OneToMany( targetEntity = "RelationInformations" , mappedBy = "objectID", cascade={"persist"} )
*/
protected $contactWebsite;
/**
* @ORM\OneToMany( targetEntity = "RelationInformations" , mappedBy = "objectID", cascade={"persist"} )
*/
protected $contactEmail;
/**
* @ORM\OneToMany( targetEntity = "RelationInformations" , mappedBy = "objectID", cascade={"persist"} )
*/
protected $contactCommunicator;
And for example getter for phones looks like:
/**
* Get contactPhone
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getContactPhone()
{
if ($this->contactPhone !== null) {
foreach ($this->contactPhone->toArray() as &$info) {
if ($info->getType() !== RelationInformations::TYPE_TELEPHONE) {
$this->contactPhone->removeElement($info);
}
}
}
return $this->contactPhone;
}
This way i got only phones from my informations only by using this function so it's much easier in other places in application to get what I want.
RelationInformation Entity:
/**
* @var integer
* @ORM\Column( name = "rnis_id" , type = "integer" , nullable = false );
* @ORM\Id
* @ORM\GeneratedValue( strategy = "AUTO")
*/
private $id;
/**
* @var integer
* @ORM\ManyToOne( targetEntity = "RelationContact" , inversedBy = "contactInformations" )
* @ORM\JoinColumn( name = "rnis_object_id" , referencedColumnName="rnct_id", nullable = false );
*/
private $objectID;
/**
* @var string
* @ORM\Column( name = "rnis_value" , type = "string" , nullable = false )
*/
private $value;
/**
* @var string
* @ORM\Column( name = "rnis_type" , type = "string" , nullable = false , length = 1 )
*/
private $type;
/**
* @var boolean
* @ORM\Column( name = "rnis_active" , type = "boolean" , nullable = false )
*/
private $active;
/**
* @var boolean
* @ORM\Column( name = "rnis_default" , type = "boolean" , nullable = false )
*/
private $default;
/**
* @var string
* @ORM\Column( name = "rnis_txt" , type = "string" , nullable = true )
*/
private $txt;
/**
* @var integer
* @ORM\Column( name = "rnis_type_private_business" , type = "integer" , nullable = true )
*/
private $typePrivateBusiness;
The problem is that in my profiler i can see errors like bellow. Application works correctly but I want to solve this issue.
The mappings RelationContact#contactPhone and RelationInformations#objectID are inconsistent with each other.
The mappings RelationContact#contactFax and RelationInformations#objectID are inconsistent with each other.
The mappings RelationContact#contactWebsite and RelationInformations#objectID are inconsistent with each other.
The mappings RelationContact#contactEmail and RelationInformations#objectID are inconsistent with each other.
The mappings RelationContact#contactCommunicator and RelationInformations#objectID are inconsistent with each other.
The mappings RelationContact#contactBrand and RelationInformations#objectID are inconsistent with each other.
A:
You can't map the same OneToMany relations on the same mappedby key, so the beahviour of the doctrine mapping validation is to correctly pass the first contactInformations reference and fail on the other.
Try to map your entities as One-To-Many, Unidirectional with Join Table as described in the Doctrine2 doc reference
Hope this help
| {
"pile_set_name": "StackExchange"
} |
Q:
setcookie for little time doesn't work in non-firefox
While testing some scripts, I've noticed, if expiration time is little (not zero) - cookie isn't available in Chrome, Opera, IE.
Example:
<?php
// setting cookie for 5 minutes
setcookie( 'cookie1' , 'Test', time()+60*5 );
echo $_COOKIE['cookie1'];
// yeap (it should display it only with refresh of page - I know:)
?>
In Firefox - I see the word Test (after opening and refreshing the page).
But in other browser - I don't see this.
If I change time to time()+60*100 for example - it works fine in all browsers.
What's the reason of this?
UPD:
From Chome Dev Tool (sorry, don't know how Chrome firebug is called):
Date:Sun, 22 May 2011 10:29:59 GMT
Keep-Alive:timeout=15, max=99
Server:Apache/2.2.14 (Ubuntu)
Set-Cookie:Maslo123=Test; expires=Sun, 22-May-2011 10:34:59 GMT
Date is early than 'expires';
A:
As we have already acquired that your server’s time is wrong by few hours and thus the cookies are already expired.
The reason why Firefox still stores the cookie might be that it detect the odd time difference between the server and the client and uses the difference between the Date value and the Expires attribute value to determine the cookie expiration date.
These issues are also the reason why latter RFC standards like the current RFC 6265 prefer the relative time value of delta seconds.
| {
"pile_set_name": "StackExchange"
} |
Q:
Correct usage it Or that
I am unsure, should I use pronoun it or that at the end of this sentence.
The legislature seems to talk at great length about reform but to do almost nothing to achieve it/that.
A:
Both it or that are correct but I think it is better.
Your sentence has an extra word 'to'
The legislature seems to talk at great length about reform but to do
almost nothing to achieve it/that.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between “der Zug” and “die Bahn”?
What is the difference between der Zug and die Bahn (besides the gender of course)? When should one be used and not the other?
A:
There are plenty of situations where Bahn and Zug can be used interchangeably:
Both words can denote a concrete track-based vehicle ("Meine Bahn kommt."/"Mein Zug kommt.").
Both words can denote the concept of a train ("Ich fahre mit der Bahn nach München."/"Ich fahre mit dem Zug nach München.").
When they are not interchangeable, though, or when both words are used together, Bahn leans towards describing the infrastructure or network, whereas Zug rather denotes the concrete vehicle, which is either track-based or composed of several connected vehicles:
Railway companies or systems will usually call themselves ...bahn, hardly ever ...zug.
Railway companies will call their vehicles exclusively Zug, especially when it gets more technical/internal ("Zugschluss", "Zugnummer", ...), but also when talking about the vehicles towards customers ("Zugdurchfahrt", "Zug fällt aus.", "Zug wird abgestellt.", "Zug wird in ... geteilt.", ...).
Even some vehicles (or other moving things) that do not run on a track are sometimes called Zug. For instance, this can be the case for large trucks with heavy trailers ("Sattelzug"), but also for parades that move through a town ("Faschingszug").
The word Bahn is also used for some non-track-based systems, such as aerial cable cars ("Gondelbahn").
Lastly, note that using either word (in particular Zug) to describe a concrete vehicle is reserved to track-based means of transportation. While aerial lifts are called Bahn such as "Gondelbahn", the vehicles/transport cabins are never called Zug or Bahn.
A:
Bahn (which means something like "track") in general is anything that runs on rails or is otherwise bound to a track. For instance Straßenbahn, U-Bahn, S-Bahn, Seilbahn, Magnetschwebebahn, Eisenbahn These words are used when talking about the type of transport in general, e.g.: "die Berliner S-Bahn...", "Ich nehme die S-Bahn und nicht das Auto"... Also, as a general term it can be used to refer to the railway network (Bahn=railway) and also to "Deutsche Bahn", the german railway company.
Zug (from ziehen, to pull) refers to the train (locomotive plus coaches/wagons). Typically long distance trains are called Zug, while local trains are called S-Bahn, Regionalbahn, Stadtbahn, or similar. However Zug can also be used in the context of S-Bahn, U-Bahn, when referring to a specific train or to technical terms, e.g. "Zugnummer", "der Zug fährt ab", "die Züge der Berliner S-Bahn"
A:
Bahn is simply "Railway" and Zug is simply "Train".
| {
"pile_set_name": "StackExchange"
} |
Q:
Humping pumping
I was watching the movie "When Harry Met Sally" and I had a trouble to understand this highlighted part of their conversation.
Harry: No you didn't. A Sheldon can do your income taxes. If you need a root canal Sheldon's your man, but
humping and pumping
is not Sheldon's strong suit. It's the name. Do it to me 'Sheldon', you're an animal 'Sheldon', ride me big 'Sheldon'. Doesn't work.
A:
Humping is slang for sex (or similar activities).
The phrase "humping and pumping" probably refers to an Arnold Swhwarzenegger quote:
The best activities for your health are pumping and humping
When he said it, "pumping" referred to lifting weights.
It's not a common idiom but is easily understood.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java server program doesn't accept the input from client at second run of client
I wrote a small client server program in Java. Server creates a ServerSocket on some port and keeps listening to it. Client sends some sample info to this server.
When I run Client the first time connection is accepted by server and info is printed by server. Then Client program exits. When I run Client again, connection is accepted however, data is not printed.
Please check following code.
Server Program
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(dis.available() > 0) {
System.out.println(dis.readByte());
}
}
}
}
Client Program
package javadaemon;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
} catch(IOException e) {
}
}
}
Please help me in finding why next time no data is received by server.
A:
The reason is before server side receive data, the Client already exits, I just debug it. (Can't explain whey it works at the first time.)
Just change your code like the below, and it works.
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(true) {
try {
System.out.println(dis.readByte());
} catch (Exception e) {
break;
}
}
}
}
}
The Client must add flush before exits,
package javadaemon;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
out.flush();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery Hide table rows
I am hiding a bunch of textboxes and it works fine, the problem is, the textboxes are in a table, so I also need to hide the corresponding labels.
the structure is something like this
<tr>
<td>
Label
</td>
<td>
InputFile
</td>
</tr>
in fact its just easier if I hide the rows that have a fileinput , can someone help please
A:
this might work for you...
$('.trhideclass1').hide();
<tr class="trhideclass1">
<td>Label</td>
<td>InputFile</td>
</tr>
A:
You just need to traverse up the DOM tree to the nearest <tr> like so...
$("#ID_OF_ELEMENT").parents("tr").hide();
jQuery API Reference
A:
This should do the trick.
$(textInput).closest("tr").hide();
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to stream an audio playlist to peers using webRTC?
In essence, I'd like to create an online radio where users can upload music to be played at specific times. Is webRTC capable of this or would I be better served going with something like Icecast?
A:
WebRTC is about peer2peer communications.
If users would upload their media on to your server, then you would need to use some WebRTC-compatible media streaming software (such as Wowza, for example) for serving the media via WebRTC; in other words, the server would have to act as a WebRTC peer.
For the described task WebRTC is not the case, on my opinion. Icecast & Co would be better suitable for the task. Basically, I believe that it can be built using just HTML5 (and JavaScript, probably).
| {
"pile_set_name": "StackExchange"
} |
Q:
Return a value from php to $.get
Now I am upgrading my website user experience, so I'm trying modify my form from form action to ajax.
Coding now work fine, server side can update the database, but I don't know how to return the custom message to my user.
My html coding.
<form method="post" id="jnfarm_pop">
blablabla...
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login();">submit</button>
</form>
My php file plugin.php
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
My jQuery
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
Now the alert doesn't work, I am also try like
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
result = JSON.parse(result); alert(result.final); //not working also
}
and
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result = JSON.parse(result)) => {
alert(result.final); //this show alert unidentified
}
Can someone correct my coding?
A:
Change
return json_encode(['final' => $final]);
to
echo json_encode(['final' => $final]);
return is really only useful when you're inside a PHP function. If you want to output something back to the caller of the script then you need to use echo, as always.
| {
"pile_set_name": "StackExchange"
} |
Q:
Would you fix this gap in vinyl siding?
I've been fixing a bunch of cracked siding panels, so I was on a mission to "fix it all". I came across this one (see red circle in picture below). Oddly (to me), unlike the other sides of the structure this side did not use "finish trim" at the top with the siding panels cut to fit up under it. Instead, the siding panels are uncut at the top, but their nail strips are nailed up under a board. So to fix this, I think I'd have to remove the board, replace the siding panel with one that is longer to fill that gap, then re-attach the board.
1) Will this gap cause trouble (water entering, etc.)?
2) Can anyone explain why this side of the structure would be so different from the others in the attachment of the top of the siding?
A:
That gap could be the result of seasonal movement. If installed correctly, the nails in vinyl siding components are left loose, so that the vinyl can move with daily and seasonal expansion and contraction.
I'd try pulling each section of edge channel sideways to close the gap. You might find that it moves easily.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как правильно написать "if else" в теле "for" без повторений
Мой код ревьювер сказал, изменить текущий так как он не соответсвует принципу "Don't repeat yourself" en.wikipedia.org/wiki/Don%27t_repeat_yourself
Конструкцию if else надо изменить. Технология ".vm", java apach velocity template, но думаю это не очень важно.
#set($first = "true")
#foreach($item in $data)
#if($first == "true")
<div class="tabs first" id="$item.get('Key')">
#set($first = "false")
#else
<div class="tabs" id="$item.get('Key')">
#end
<h1>str1</h1>
<h1>str2</h1>
<h1>str3</h1>
</div> ##//Close div created in (if else)
#end
A:
<div class="tabs
#if($first == "true")
first
#set($first = "false")
#end
" id="$item.get('Key')">
Но, на мой взгляд, это типичный пример принесения читаемости кода в жертву догматическому следованию "принципу".
A:
Признак первого элемента при переборе можно получить из переменной $foreach: $foreach.first
Следовательно код может принять вид:
#foreach($item in $data)
<div class="tabs #if($foreach.first) first#end" id="$item.get('Key')">
<h1>str1</h1>
<h1>str2</h1>
<h1>str3</h1>
</div> ##//Close div created in (if else)
#end
| {
"pile_set_name": "StackExchange"
} |
Q:
I would like the command to display the file disk location, and size of the recovery area?
I am hoping this is a easy question to answer. Default recovery file disk location and the size set for your recovery area
A:
Always include Oracle version and platform.
You should check v$flash_recovery_area_usage and v$recovery_file_dest
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hazards of mouthwash?
I encountered this claim (here):
Listerine (and related mouth washes) probably do not eliminate bad breath. Although it may be effective at first, in the long term it generally increases bad breath by drying out the mouth and inhibiting the salivary glands. This may also increase the population of dental bacteria. Most top dentists recommend avoiding mouth wash or using it very sparingly.
The claim is given in context with seven other claims, and we are told that four of them are true.
I use mouthwash occasionally, and I would use it more regularly if I were more confident it didn't have negative health consequences. Is this claim true?
A:
The statement quoted is actually contained under the heading: 4.2: Is this really true? Surely people would investigate the safety, ethics, and efficacy of the products they buy.So this statement is not necessarily true or false; it is just one of the many statements in this heading that may or may not be so.As to whether or not mouthwash may be effective, this article in DetistryIQ has this to say about Listerine:"These findings support the benefit of adding an antiseptic mouthwash to a daily oral health care routine, especially for those patients who don't brush and floss properly," ..."The findings, however, do not mean that flossing should be replaced with rinsing. I recommend that dentists and hygienists talk to their patients about what's best for their oral healthcare routine, and devise strategies to target difficult to reach areas that are susceptible to plaque accumulation and gingivitis."The ADA in this article also says:While not a replacement for daily brushing and flossing, use of mouthwash (also called mouthrinse) may be a helpful addition to the daily oral hygiene routine for some people.It also has some good information in it.I could not find any reputable articles that made the claim in the OP's citation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using WQL query from SCCM in powershell
I have a query in SCCM that will take a printer IP address and return all workstations in SCCM that have the printer installed on it. I am wanting to create a powershell script that will take said query and use the workstations that it returns to then list current print jobs in the print queue on the workstation.
I know that you can use Get-CIMInstance -query to query different things in WMI. That works well if I am trying to find out information locally. However if I dump the WQL query into a Here-String and assign it to a variable and then call it with Get-CIMInstance -query it returns an error saying invalid query. The same thing happens when I use Get-WmiObject -Namespace "root\wmi" -Query $WQlquery
So how would I be able to use the WQL query from SCCM in powershell? Here is an example of what I have so far:
$WQLquery = @"
select SMS_R_System.Name from
SMS_R_System inner join
SMS_G_System_PRINTER_DEVICE on
SMS_G_System_PRINTER_DEVICE.ResourceID =
SMS_R_System.ResourceId where
SMS_G_System_PRINTER_DEVICE.PortName like "10.10.10.10"
"@
Get-CIMInstance -query $WQLquery
Assuming that worked and returned a list of workstation ids, I would then use Get-Printjob cmdlet to list current jobs in each workstations print queue. I have found a few questions posted here already that have helped me get this far. Any additional help would be appreciated. Go easy on me, still a newb here.
A:
You need to specify the namespace for the sccm site root\sms\site_SITECODE and the sccm-server if you're running it from a remote computer. Ex:
$WQLquery = @"
select SMS_R_System.Name from
SMS_R_System inner join
SMS_G_System_PRINTER_DEVICE on
SMS_G_System_PRINTER_DEVICE.ResourceID =
SMS_R_System.ResourceId where
SMS_G_System_PRINTER_DEVICE.PortName like "10.10.10.10"
"@
Get-WmiObject -Query $WQLquery -ComputerName "SCCMSERVER" -Namespace "root\sms\site_PRI"
| {
"pile_set_name": "StackExchange"
} |
Q:
Pattern Matcher gets ArrayIndexOutOfBoundsException: 0
Here is the pseudocode of what I'm trying to do:
procedure naive(T, P):
result = { }
for s = 0 to n – m
match = true
for j = 0 to m – 1
if T[s+j] ≠ P[j]
match = false
if match
result = result + {s}
Here's what I've written:
public class naivepatternmatcher {
public static Integer[] main(char[] T, char[] P) {
Integer[] results = {};
int count = 0;
boolean match;
for (int s = 0; s <= (T.length - P.length); s++) {
match = true;
for (int j = 0; j <= P.length - 1; j++) {
if (T[s + j] != P[j]) {
match = false;
}
}
if (match == true) {
results[count] = s;
count++;
}
}
return results;
}
}
When I try to run my Junit test class I get an ArrayIndexOutOfBoundsException: 0 at "results[count] = s;" in my main and "Integer[] results = naivepatternmatcher.main(Sequence, Pattern1);" in my Junit Test.
public class naivepatternmatcherTest {
private static final char[] Sequence = new char[] { 'a', 'b', 'a', 'a', 'a',
'b', 'a', 'c', 'c', 'c', 'a', 'a', 'b', 'b', 'a', 'c', 'c', 'a', 'a',
'b', 'a', 'b', 'a', 'c', 'a', 'a', 'b', 'a', 'b', 'a', 'a', 'c' };
@Test
public void test() {
char[] Pattern1 = new char[] { 'a', 'a', 'b' };
Integer[] ShouldEqual = new Integer[] { 3, 10, 17, 24 };
Integer[] results = naivepatternmatcher.main(Sequence, Pattern1);
assertArrayEquals(ShouldEqual, results);
}
}
Can anyone solve this to me and explain what I am missing?
A:
Your results is an empty array with a fixed size of 0 and results[count] = s won't increase the array's size by one and append the value of s to it. Better use an ArrayList for such a dynamically growing results.
Another suggestion is that you add a call to break at the end of your inner for loop's if because if T[s + j] != P[j] there is no need to further search for the rest of the pattern.
if (T[s + j] != P[j]) {
match = false;
break
}
See the following code for an example of implementation that keeps your returntype of Integer[] and only internally uses an ArrayList.
public static Integer[] main(char[] T, char[] P) {
List<Integer> results = new ArrayList<>();
boolean match;
for (int s = 0; s <= (T.length - P.length); s++) {
match = true;
for (int j = 0; j <= P.length - 1; j++) {
if (T[s + j] != P[j]) {
match = false;
break;
}
}
if (match == true) {
results.add(s);
}
}
return results.toArray(new Integer[results.size()]);
}
See it run live
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.