text:
Q: How a proper way to test with RSpec a unchecked checkbox in PostController I'm doing this test controller with RSpec on post_controller, but I'm having difficult to evaluate the users who don't have permission for check the categories.
expect(posting.categories).to have_unchecked_field("Sports")
This test it's like a way for a user don't hacking the post categories.
The
context "restrictions for users on posts who" do
    let(:user) { create(:user) }
    let(:category) { create(:category)}
    let(:posting) { Post.create(title: "State transitions", subtitle: "Can't be hacked.", content: "State transitions now they can't be hacked anymore.", author: user) }

    before :each do
      posting.categories << category
      assign_role!(user, :editor, posting)
      sign_in user
    end

    it  "can edit a post, but not tag them" do
      put :update, { id: :posting.to_param, title: "Editing post for editors!",
                            content: "The editor users, they cannot tag a post",
                            tag_names: "these are tags" },
                    post_id: posting.id

      posting.reload
      expect(posting.tags).to be_empty
    end

    it  "can edit a post, but not check the categories" do
      put :update, { id: :posting.to_param,
                     title: "Editing post for editors!",
                    content: "The editor users, they cannot check categories",
                    category_ids:["Sports"] },
                  post_id: posting.id

      posting.reload

      expect(posting.categories).to have_unchecked_field("Sports")

    end

  end
end

form:
- if policy(post).change_category?
  = f.association :categories, label: "Select the Categories:", as: :check_boxes , collection: @categories.map{|c| [c.name, c.id]}, include_hidden: false

So I'm using the private method sanitizing_parameters for deleting the parameters if a user don't have a permission.
post_controller.rb
def update
    authorize @post, :update?
    @post.author = current_user

    if @post.update(sanitized_parameters)
      flash[:notice] = "Post has been updated."
      redirect_to @post
    else
      flash.now[:alert] = "Post has not been updated."
      render "edit"
    end
  end

...
private

  def post_params
params.require(:post).permit(:title,
                             :subtitle,
                             :content,
                             :tag_names,
                             :attachment,
                             :attachment_cache,
                             :remove_attachment,
                             :remote_attachment_url,
                             category_ids:[])
  end

  def sanitized_parameters
    whitelisted_params = post_params

    unless policy(@post).change_category?
      whitelisted_params.delete(category_ids:[])
    end

    unless policy(@post).tag?
      whitelisted_params.delete(:tag_names)
    end

    whitelisted_params
  end

error:
Failures:

  1) PostsController restrictions for users on posts who can edit a post, but not check the categories
     Failure/Error: expect(posting.categories).to have_unchecked_field("Sports")
       expected to find field "Sports" that is not checked but there were no matches

A: You're writing a controller or possibly request test, but Capybara is only for use in feature/system and view tests.  When you attempt to call have_unchecked_field("Sports") it should have raised a no method error since you shouldn't even be including the Capybara methods into controller tests.
Since you have included Capybara::DSL into all your tests (assumed) it's taking posting.categories, converting it to a string, parsing it as HTML, and then looking for elements in it.  Since posting.categories isn't HTML it's never going to work like that.  What you probably want is something like
expect(posting.categories).to be_empty


text:
Q: Why doesn't my new Odoo module show up on the module list? I am using Odoo v12 on Windows.
I have followed the steps in HowTo to create a module Saadoodoo. My problem is that I have failed to make this new module appear on the Odoo module list.
I am using the below command
python.exe odoo-bin" -d SaadoIncLocal -i Saadoodoo --addons-path D:\PythonDev\Odoo

It seems Odoo simply ignores the commands and starts the server normally, as the module does not appear on the apps list (even when selecting developer mode).
I thought the issue may be in the addon path, so I added the module under the default Odoo path along with Odoo modules in C:\Program Files (x86)\Odoo 12.0\server\odoo\addons and did an apps update on Odoo interface but still problem persists. Starting and stopping the server does not help either.
What am I doing wrong?

A: After adding new module in the addons_path, you have to turn on debug/developer mode, goto Apps > Update modules list, remove Apps filter from search and search your module.
Don't forget to add __manifest__.py with proper data, which is important for odoo addons.
If still having problem, you can use scaffold option of odoo-bin to create empty module.
python.exe odoo-bin scaffold my_module

This is will create a empty module with all the necessary skeleton files in the current working directory, you can just move it to addons folder, rename the variables accordingly and files and you are good to go.

A: There could be 2 Reasons that you are not able to see the module :-
1. You have not updated the database
Two ways to update the database :-
1.1 from Terminal use this command to update the module and database
./odoo-bin -c debian/odoo.conf -d {NAME_OF_ODOO_DATABASE} -u {NAME_OF_THE_NEW_MODULE}
1.2. From frontend
By activating the developer mode by going to Setting --> under the developer tools option --> Activate the developer mode
Now go to app list and select the option update app list.
2. You have not configured the addons path in the debian/odoo.conf file
Make sure that you have added the addons_path of the custom-addons folder in odoo.conf file inside debian folder

A: why don't you simply use these commands
cd C:\Program Files (x86)\Odoo 12.0\server\odoo\addons
C:\Program Files (x86)\Odoo 12.0\python\python.exe C:\Program Files (x86)\Odoo 12.0\server\odoo-bin scaffold my_module --config C:\Program Files (x86)\Odoo 12.0\server\odoo.conf

A: Use this command to create module in odoo.
odoo-bin scaffold mynewmodule addons

directive command module-name modulepath

A: Oh once your module is ready, go to the Odoo directory in windows, navigate to custom-addons and you will see a list of all the available modules. paste your new module in there. Now open the Odoo again, go to Apps, then update module list. Then search for your app in the app list. Make sure the developer mode is activated

A: Have you click Update App List in menu Apps?
This is screenshot from Odoo 11, it should applied in Odoo 12 but may be different position.

A: *

*Go to your odoo-version folder (ex: cd /home-path/odoo-09.0/10.0/11.0/12.0/13.0) where your odoo-bin file is placed (till odoo-10.0 the file is openerp-server but in later version the file is odoo-bin)

*Run the command ./odoo-bin scaffold yourModuleName destinationDirectory (odoo_version >= 10)

*Run the command ./openerp-server scaffold your_module_name destinationDirectory (odoo_version < 10)

please use configuration file to run odoo(it's quite easy without any mistake)
run this command: python3 odoo-bin --save --config odoo.cfg --stop-after-init
that will save odoo.cfg file  open it up and add your custom module path in addons_path varibale which is defined in top of configuartion file

A: using mode debug, go to your apps, click update app list

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Daario smash the dead Dothraki's head in with a rock? I understand that in Vaes Dothrak, weapons are forbidden, but isn't bloodshed also forbidden? Did they just mess this up, because later on in the Temple of the Dosh Khaleen, the blood rider mentions this to Khal Moro (about bloodshed being forbidden), and he is dismissive of it.
So did Daario read Khal Moro's mind in advance to know he wouldn't care about bloodshed, and hence the rock smashing?
Or did he smash the guy's head in because he was unaware of the bloodshed rule? (Which would make no sense because Jorah would know this and would've told him before he started bashing the dead guys head in).

A: Daario used the rock to hide the stab wound from a knife.
Dothraki are always fighting so there will be deaths from fist fights/general brawling.
If a warrior is dumb enough to die to unarmed combat then it reflects badly on his Khal. That is why Moro said what he did about the death.
So in summary Daario used the rock to hide the fact that he had killed a man with a blade.

A: Jorah Mormont clearly mentioned that if somebody noticed the stab wound, they would start searching for them and could get caught. Because weapons and the use of weapons are not allowed, it would mean that there was a chance of it being an outsider, as Dothrakis don't have weapons in that area. Smashing it with a rock removed the stab wound and now it can be made to look like a normal fight between Dothrakis. It seems to be normal as they have shown anger issues many times.

A: A wound made by a bladed weapon would have drawn attention

You all right? If they find a body with a stab wound, the whole city
will be looking for us.

Assuming that bloodshed is prohibited in Vaes Dothrak, getting into a fistfight and killing someone may be technically disallowed, but it is something a sufficiently foolish or drunk resident may do. Killing someone with a blade, given that weapons are prohibited within the city? Clearly the work of a foreigner, and thus of high priority.
A death via blunt force trauma will undoubtedly be looked into, but perhaps not with the same urgency. Thus the need to conceal the cause of death.
The rules against bloodshed may not be so hard-and-fast
In the novels, it is established that any sort of bloodshed (of humans, at least) is prohibited, along with bladed steel weapons.

Many of the men were drunk on clotted mare's milk, yet Daenerys knew no
arakhs would clash tonight, not here in the sacred city, where blades and bloodshed were forbidden.
—A Game of Thrones

On the TV show, people generally speak of the ban on weapons when they mention Vaes Dothrak:

JORAH MORMONT: Don't let them see you carrying a sword in Vaes
Dothrak. You know the law.
VISERYS TARGARYEN: (sheaths his sword) It's
not my law.(turns and puts another egg in the bag)

and

It's forbidden to carry weapons in the sacred city.

and

You all right? If they find a body with a stab wound, the whole city
will be looking for us.

On the other hand, Viserys Targaryen does not (though admittedly he is an individual with perhaps not a stellar understanding of Dothraki culture, as evidenced by his final fate):

VISERYS TARGARYEN: They can't kill us. (pointing his sword again at
Jorah) (Drogo mutters to his Dothraki soldier, who then gets up) They
can't shed blood in their sacred city.

Indeed, the translation of the Dothraki dialogue from the episode makes the reasoning clear:

FORZHO : It is forbidden to spill blood in the sacred city.
MORO: It is forbidden to carry weapons in the sacred city.
FORZHO: So we don't spill blood!
MORO: Well… There's always a little blood.
FORZHO: Not when you strangle them.

It seems that not all the Dothraki practice the prohibition on spilling blood so firmly, and that bloodshed through non-weapon means is not unheard of (not surprising, given how many Dothraki fetishize violence elsewhere).
So while avoiding spilling blood may be the point of the prohibition on weapons, some Dothraki seem to interpret the prohibition rather literally. Of course, this still probably wouldn't let someone get away with the murder of a prominent individual, but as mentioned previously, it would make the death much less suspicious.

A: Like anything else rules are open to interpretation and can be taken literally or figuratively.  Like is it ok to kill someone if they are trying to kill you?  But they were obviously not concerned with rules at that point as they had already killed the men. Smashing his head was just a distraction that would buy them some time.


text:
Q: Pros and Cons of Isotope templates (Rails) Isotope lets you write templates in javascript. These templates can then be rendered by either the client (using plain-old javascript) or on the server (using Johnson).
The benefit is DRYer code. When updating the DOM on an ajax or web socket update, you can don't have to write a new partial...just point it to the one you already wrote.
Has anyone used this?

A: Interesting, I would have to try it, however , and I know not a lot of people do it, but I actually use HAML to template .js files. Although there is still that problem the author mentions , of each request being templated on the server and sending back html, unless you are sending loads of kb, or you have really, really high load site I don't think it's such a big deal.
Also ideally you shouldn't be even sending html data back and force, just JSON objects, which are rendered on the page by your ajax request. The only legitimate use I can see for this is if you have heavily ajax website, such as where you load a page once, and the you just keeping doing ajax requests for all interaction and javascript to manipulate view.
So it would help if you would clarify the final goal. Is this for some internal app where you control user environment ( you know for sure which browsers they will use, and that they will have fast enough computers to manipulate all this javascript?) Or is it going to be an app targeted towards 3rd world, where people don't have yet resources available to use all that fancy javascript.
All that said, it's an interesting concept, and I will try it our myself, to see how well it works.

A: This uses Johnson, which last I checked did not work on Ruby 1.9. So that might hint at some of the immaturity of this particular solution. Eventually the community will come up with something that works really well.
One approach I have used is to make 2 completely separate templates, but try to make them as similar as possible so that it is easy to port changes from one to the other.

A: This seems like a bad idea. In an Ajax application, I believe that the server should be responsible for rendering all display text. This makes i18n easier, and concentrates everything in one place. The JavaScript should simply receive data from the server, with all display text already rendered, and put it in the appropriate DOM object.
In other words, I believe that in an Ajax application, the need for a JS template engine is itself a design smell.
The situation is different in exclusively client-side JS applications, of course.


text:
Q: Modify a wildcard string within two other strings Assuming I have the following code as the value of a variable (I can use either  JS or PHP for this):

The Page Title

Some body copy...

Is there a way I can convert the image filenames to lower case whilst preserving the case of everything else, and then rewrite all of the new code into the variable?
If the solution involves finding all instances of src="*" (or, anything between the strings src=" and ") and converting them to lower case, that would be fine (I'm happy with the src values of any future elements I add being converted as well).

A: With PHP where $html is your html content:
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$imgNodeList = $dom->getElementsByTagName('img');

foreach ($imgNodeList as $imgNode) {
    $imgNode->setAttribute('src', strtolower($imgNode->getAttribute('src')));
}

echo $dom->saveHTML();

A: If you need only to apply lowercase on path basement (filename) you can go with DOM along with regex:
$html = <<< STR

The Page Title

Some body copy...

STR;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

// Get all images
$images = $dom->getElementsByTagName('img');

foreach ($images as $img) {
    $newSrc = preg_replace_callback('~[^/]+$~', function($match) {
        // Convert file names to lowercase
        return strtolower($match[0]);
    }, $img->getAttribute('src'));
    // Set new attribute value
    $img->setAttribute('src', $newSrc);
}

// Save to original variable
$html = $dom->saveHTML();

Output of echo $html;

The Page Title

Some body copy...

Live demo

A: Try the below code

$('img').each(function(){
  $(this).attr('src',  $(this).attr('src').toLowerCase())
})

The Page Title

Some body copy...


text:
Q: Spring Security OAuth2 Java Config for Google Login I am migrating working XML configuration to Java configuration for Spring Security OAuth2 and using Google as the OAuth provider.
This is how my java configuration looks:
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final List<String> scope;

    static {
        // Permissions to access email and profile
        scope = new ArrayList<>(3);
        scope.add("openid");
        scope.add("email");
        scope.add("profile");
    }

    @Autowired(required = true)
    private UserService userService;

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.
            authorizeRequests()
                .antMatchers(HttpMethod.GET, "/","/public/**", "/resources/**","/resources/public/**").permitAll()
                //.antMatchers("/google_oauth2_login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/home")
                    .and()
                    .csrf().disable()
                    .logout()
                        .logoutSuccessUrl("/")
                        .logoutUrl("/logout")
                .and()
                    .requiresChannel().anyRequest().requiresSecure()
                .and()
                    .addFilterAfter(oAuth2ClientContextFilter(),ExceptionTranslationFilter.class)
                    .addFilterAfter(googleOAuth2Filter(),OAuth2ClientContextFilter.class)
                .userDetailsService(userService);
        // @formatter:on
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        // @formatter:off
        auth
            .authenticationProvider(googleOauth2AuthProvider())
            .userDetailsService(userService);
        // @formatter:on
    }

    @Bean
    public GoogleOAuth2Filter googleOAuth2Filter() throws Exception {
        GoogleOAuth2Filter filter = new GoogleOAuth2Filter(
                "/google_oauth2_login",
                "https://accounts.google.com/o/oauth2/auth",
                oAuth2RestTemplate(auth2ProtectedResourceDetails()));
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

    @Bean
    public GoogleOauth2AuthProvider googleOauth2AuthProvider() {
        GoogleOauth2AuthProvider authProvider = new GoogleOauth2AuthProvider();
        return authProvider;
    }

    @Bean
    public OAuth2ProtectedResourceDetails auth2ProtectedResourceDetails() {
        AuthorizationCodeResourceDetails auth2ProtectedResourceDetails = new AuthorizationCodeResourceDetails();
        auth2ProtectedResourceDetails
                .setClientAuthenticationScheme(AuthenticationScheme.form);
        auth2ProtectedResourceDetails
                .setAuthenticationScheme(AuthenticationScheme.form);
        auth2ProtectedResourceDetails.setGrantType("authorization_code");
        auth2ProtectedResourceDetails
                .setClientId("the-client-id");
        auth2ProtectedResourceDetails
                .setClientSecret("the-client-secret");
        auth2ProtectedResourceDetails
                .setAccessTokenUri("https://accounts.google.com/o/oauth2/token");
        auth2ProtectedResourceDetails.setScope(scope);
        auth2ProtectedResourceDetails
                .setUserAuthorizationUri("https://accounts.google.com/o/oauth2/auth");
        auth2ProtectedResourceDetails.setUseCurrentUri(false);
        auth2ProtectedResourceDetails
                .setPreEstablishedRedirectUri("https://localhost/google_oauth2_login");
        return auth2ProtectedResourceDetails;
    }

    @Bean
    public OAuth2RestTemplate oAuth2RestTemplate(
            OAuth2ProtectedResourceDetails resource) {
        OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource);
        return oAuth2RestTemplate;
    }

    @Bean
    public OAuth2ClientContextFilter oAuth2ClientContextFilter() {
        OAuth2ClientContextFilter oAuth2ClientContextFilter = new OAuth2ClientContextFilter();
        return oAuth2ClientContextFilter;
    }

}

Note that I have disabled CSRF.
From my login page the user do gets redirected to Google login page
Problem:-

*

*Google Permission Page just asks for "Have offline access".'Email/Profile' access request is missing.

The equivalent 'scope' attibute XML configuration :-
<oauth2:resource id="googleOauth2Resource" type="authorization_code"
        client-id="the-client-id
        client-secret="the-client-secret"
        user-authorization-uri="https://accounts.google.com/o/oauth2/auth"
        scope="openid email profile" use-current-uri="false"
        client-authentication-scheme="form" pre-established-redirect-uri="https://localhost/google_oauth2_login" />

do correctly asks for email and profile permissions. Why?

*Continuing anyway with the 'Have offline access' results in this exception:-

    org.springframework.web.client.HttpClientErrorException: 400 Bad Request
        at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
        at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport$AccessTokenErrorHandler.handleError(OAuth2AccessTokenSupport.java:243)
        at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:592)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:550)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:514)
        at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAuthorizationCode(AuthorizationCodeAccessTokenProvider.java:145)
        at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:196)
        at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:142)
        at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:118)
        at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
        at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
        at org.springframework.security.oauth2.client.OAuth2RestTemplate.createRequest(OAuth2RestTemplate.java:105)

while trying to get user profile using this code block:
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
        HttpServletResponse response) throws AuthenticationException,
        IOException, ServletException {
    logger.info("Google Oauth Filter Triggered!!");
    SecurityContext context = SecurityContextHolder.getContext();
    // auth null or not authenticated.
    String code = request.getParameter("code");
    Authentication dummyAuthentication = null;

    if (StringUtils.isEmpty(code)) {
        // Google authentication in progress. will return null.
        logger.debug("Will set dummy user in context ");
        dummyAuthentication = getDummyAuthenticationToken();
        context.setAuthentication(dummyAuthentication);
        // trigger google oauth2.
        oauth2RestTemplate.postForEntity(authURI, null, Object.class);
        return null;
    } else {
        // response from google received !!.
        // remove dummy authentication from context.
        //SecurityContextHolder.clearContext();
        logger.debug("Response from Google Recieved !!");
        // get user profile and prepare the authentication token object.
        ResponseEntity<Object> forEntity = oauth2RestTemplate.getForEntity(
                HTTPS_WWW_GOOGLEAPIS_COM_PLUS_V1_PEOPLE_ME_OPEN_ID_CONNECT,
                Object.class);

        @SuppressWarnings("unchecked")
        Map<String, String> profile = (Map<String, String>) forEntity
                .getBody();

        CustomOAuth2AuthenticationToken authenticationToken = getOAuth2Token(
                profile.get(EMAIL), profile.get(NAME));
        authenticationToken.setAuthenticated(false);
        return getAuthenticationManager().authenticate(authenticationToken);
    }
}

Spring RestTemplate showing this in logs:
o.s.web.client.RestTemplate              : POST request for "https://accounts.google.com/o/oauth2/auth" resulted in 400 (Bad Request); invoking error handler
2014-09-05 21:51:46.870  WARN 5836 --- [ qtp25546756-15] o.eclipse.jetty.servlet.ServletHandler   : /google_oauth2_login

This same piece of code works while using with XML configuration.
UPDATE 1
I was able to fix the 'Offline Access' problem by changing scope to 'https://www.googleapis.com/auth/plus.profile.emails.read' & 'https://www.googleapis.com/auth/plus.login'.
Still getting bad request error while trying to get user profile
Please find source code for the problem here -
git clone https://kumarsambhavjain@bitbucket.org/kumarsambhavjain/spring-oauth2-login.git

A: Have you tried change profile URL to
https://www.googleapis.com/plus/v1/people/me/openIdConnect

See more: https://developers.google.com/+/api/openidconnect/getOpenIdConnect

A: I used your code to create a OAuth2 Spring Boot sample, quite similar, and I had same issue once I replaced profile URL to:
https://www.googleapis.com/plus/v1/people/me/openIdConnect

I resolved it by enabling Google+ API in Google Console:

*

*Visit the Google API Console here:https://code.google.com/apis/console/?api=plus

*Under the Services panel, make sure the Google+ API is turned "on".

*In the APIs console, click API Access in the left menu.

*Copy the API key presented towards the bottom. Include this API key in your HTTP request.

This process is explained in this question:
How to call https://www.googleapis.com/plus/v1/people/me at google


text:
Q: Server side callback function ajax web service asp.net I'm using Web Service to handle ajax request in my project. I need to call a server side function to count users online when a new request is proceed.

A: If you want to call Server side method into Client side then,you have to transform this method as a PageMethod and then call this method i.e GetOnlineUser() from client side code; i.e. using JavaScript.
To enable the method as a PageMethod, add the attribute [WebMethod] on top of the GetOnlineUser method in .aspx code behind file.
if you are using asp.Net membership provider then simply call  Membership.GetNumberOfUsersOnline().
And if you are not using membership you have to implement your own custom counter...


text:
Q: creating a data frame with 100 columns of desired column name in R I would like to create a data frame with 100 columns whose names are feature1, feature2, feature3 ... feature100.
I was able to create the data frame as
df <- as.data.frame(matrix(0, ncol = 100, nrow = 2))

But the names of my columns are all V1, V2 etc
> names(df)
  [1] "V1"   "V2"   "V3"   "V4"   "V5"   "V6"   "V7"   "V8"   "V9"   "V10"  "V11"  "V12"  "V13"  "V14"  "V15"
 [16] "V16"  "V17"  "V18"  "V19"  "V20"  "V21"  "V22"  "V23"  "V24"  "V25"  "V26"  "V27"  "V28"  "V29"  "V30"
 [31] "V31"  "V32"  "V33"  "V34"  "V35"  "V36"  "V37"  "V38"  "V39"  "V40"  "V41"  "V42"  "V43"  "V44"  "V45"
 [46] "V46"  "V47"  "V48"  "V49"  "V50"  "V51"  "V52"  "V53"  "V54"  "V55"  "V56"  "V57"  "V58"  "V59"  "V60"
 [61] "V61"  "V62"  "V63"  "V64"  "V65"  "V66"  "V67"  "V68"  "V69"  "V70"  "V71"  "V72"  "V73"  "V74"  "V75"
 [76] "V76"  "V77"  "V78"  "V79"  "V80"  "V81"  "V82"  "V83"  "V84"  "V85"  "V86"  "V87"  "V88"  "V89"  "V90"
 [91] "V91"  "V92"  "V93"  "V94"  "V95"  "V96"  "V97"  "V98"  "V99"  "V100"

I have to then follow that up with something like
for(i in 1:100)
{
    df[,paste("feature",i,sep="")] = df[,paste("V",i,sep="")]
    df[,paste("V",i,sep="")] = NULL
}

Is there an easier way to have my columns names as "feature1", "feature2" etc

A: You can do
 names(df) <- paste0('feature', 1:100)

Or specify the dimnames part in the matrix call
as.data.frame(matrix(0, ncol=100, nrow=2, dimnames=list(NULL,
                 paste0('feature',1:100))))


text:
Q: How can I exit a function after X period of time? C++ I'm not really that good in C++, actually I'm new at this and still I have to much to learn.
I have this situation where a function its called and sometimes It takes thousands of seconds to complete and returns nothing.
Is there a way to put a timeout to exit that function once after I hit a time, let's say... 5 seconds
EDIT:
*I'm using qt also

A: Assuming you are able to modify the function, it's fairly straightforward; just have the function declare a QElapsedTimer object and periodically check it to see if "too much" time has passed:
void MyFunctionThatShouldntTakeMoreThanFiveSeconds()
{
   QElapsedTimer timer;
   timer.start();

   while(1)
   {
      if (timer.hasExpired(5000))
      {
         printf("Time's up!  Returning now\n");
         return;
      }

      // do other stuff that the function does
   }
}

If you can't modify the function, OTOH, you're out of luck -- there's very little you can do to affect its behavior unilaterally.  (As @user4581301 suggests, you could spawn a child process and run the function inside the child process, and then kill the child process after 5 seconds, but that's probably more overhead and complexity than is reasonable)


text:
Q: How to discord authentication in expo-auth-session? I'm new to expo and I trying expo-auth-session for discord but return "validation error auth url must be a valid uri"
This is my code
const { authorize, clientId, scopes } = discord;
const useProxy = true;
const redirectUri = makeRedirectUri({ useProxy });

export default function Login() {
    const discovery = useAutoDiscovery(authorize);
    const [request, response, promptAsync] = useAuthRequest(
        {
            clientId,
            redirectUri,
            scopes,
        },
        discovery
    );

    useEffect(() => {
      console.log(response)
    }, [response]);

    const onLogin = async () => {
        promptAsync({useProxy}).catch(e =>{
          console.log(e);
        })
    };

    return (
        <View>
         <Button title="Login" disabled={!request} onPress={onLogin} />
        </View>
    );
}


text:
Q: AngularJS Not Displaying Message Properly I am a beginner programmer learning angular and following along with a Music Store Application. I am having some trouble displaying a message in angularJS and was wondering if its a problem in the code, or something else. My expected result is to simply display "Manish Kumar" on the page. However, my actual result is simply displaying {{message}} from the html. It's as if its not picking up the JS controller reference. Please note the example was done in VS 2013, while I'm using 2015. Any help is appreciated, as I am a beginner. Thanks!!
My Code & Files:
Index HTML:
<!DOCTYPE html>

    <title></title>

            {{message}}

MusicListController:
(function (app) {
    var MusicListController = function ($scope) {
        $scope.message = "Manish Kumar";
    };
    app.controller("MusicListController", MusicListController);
}(Angular.module("theMusic")));

theMusic Class:
(function () {
    var app = Angular.module("theMusic", []);
}());

A: Please try this type i think solve  your problem  just make some changes.

(function () {
    var app = angular.module("theMusic", []);
}());

(function (app) {
    var MusicListController = function ($scope) {
        $scope.message = "Manish Kumar";
    };
    app.controller("MusicListController", MusicListController);
}(angular.module("theMusic")));

<!DOCTYPE html>

    <title></title>

            {{message}}


text:
Q: R If statement returns "the condition has length > 1 and only the first element will be used" I am trying to reproduce results from Stata in R. The specific line that is giving me trouble seems simple.
The line of Stata is
sum peace_index_score if Africa == 1
The code I tried in R is
if (World$Africa == 1){
    summary(World$peace_index_score)
}

This returns the following error message:
Warning message in if (World$Africa == 1) {:
"the condition has length > 1 and only the first element will be used"

A: It would be
summary(World$peace_index_score[World$Africa == 1])

A: Stata automatically applies the test if Africa == 1 observation by observation (row by row, if you like) given syntax like
sum peace_index_score if Africa == 1

This is an example of an if qualifier.
Stata is like R to the extent that use of the if command
if Africa == 1 sum peace_index_score

is interpreted as
if Africa[1] == 1 sum peace_index_score

However, that construct in Stata is legal, just rarely what you want, as almost always the if command is best used for comparing string or numeric constants (and in fact the above command is doing exactly that). So, it would be legal and idiomatic in Stata to check first for any values of Africa that are 1.
count if Africa == 1
if r(N) == 0 sum peace_index if Africa == 1


text:
Q: Facebook Search API throwing OAuthException I use the facebook graph search to get informations about urls. So i use the url as search value.
Since a few days, something went wrong, and i don't know why?
ca 30% of the search values throw this error:
{
   "error": {
      "message": "An unknown error has occurred.",
      "type": "OAuthException",
      "code": 1
   }
}

Here an Example:
https://graph.facebook.com/search?q=poolhall.de&type=page <- works!
https://graph.facebook.com/search?q=pool-hall.de&type=page <- error!
The ony difference: searchvalue
"poolhall.de" <-> "pool-hall.de"

Another url with error ist search for "horje.de"
"horje.de" -> error, "horje" and "horje.com" etc -> no error!

But why the "OAuthExeption" is being thrown?
The API does not need an authorisation! Just copy the postet URLs in the Browser adress line, you got an result without auth. Why some search values throws an error and other search values work?

A: Update: Since roundabout an hour, it looks like Facebook has fixed the bug! no "OAuthExeption" errors anymore!

A: They're still in beta, I tested this a bit and this really looks like a bug. So probably just need to report about that issue or just wait till this becomes stable.


text:
Q: DNS lookup is giving incorrect output This is the code I am using. What is the problem with the code?
Moreover, how can I specify the timeout parameter? tcp_timeout does not seem to work.
sub resolve_dns()
{
    my $dns = $_[0];
    my $res   = Net::DNS::Resolver->new(

                nameservers => [qw(24.116.197.232)],
                recurse     => 0,
                debug       => 1,
                tcp_timeout => 3
                );
    my $query = $res->search($dns);

    if ($query) {
        foreach my $rr ($query->answer) {
            next unless $rr->type eq "A";
            print $rr->address, "\n";
        }
    } else {
        warn "query failed: ", $res->errorstring, "\n";
    }
}

This is the output I am getting.
Output

query failed: query timed out
;; search(www.youtube.com)
;; setting up an AF_INET() family type UDP socket
;; send_udp(24.116.197.232:53)
;; send_udp(24.116.197.232:53)
;; send_udp(24.116.197.232:53)
;; send_udp(24.116.197.232:53)

A: You can specify a timeout using:
$res->udp_timeout(3);

or, replace the specify it in the constructor.


text:
Q: Joining and interpolating data points I wonder what is the best practice for interpolating curves? Usually, I'm using BSplineCurve and adjusting SplineWeights so it would fit better (and assigning more weight around the sharp edges to drag the curve closer to it). Or if I can guess what formula describes the points, I use FindFit. But often, I can't guess the formula and adjusting weights is very tedious, so it's easier to just manually draw the curve along the points. So what is the best way to join points in Mathematica?
Consider these five sets of points describing five resonance curves for example:
 data = {{{100.434, 0.}, {102.461, 0.0909091}, {104.392, 0.318182}, {105.321, 0.545455},
          {106.226, 1.}, {107.108, 0.545455}, {107.965, 0.318182}, {109.608, 0.136364},
          {111.154, 0.0909091}},
         {{100.434, 0.}, {102.461, 0.06}, {104.392, 0.22}, {105.321, 0.46}, {106.226, 1.},
          {107.108, 0.4}, {107.965, 0.12}, {111.154, 0.02}, {113.958, 0.}},
         {{100.434, 0.030303}, {102.461, 0.0505051}, {104.392, 0.0909091},
          {105.321, 0.272727}, {105.867, 0.494949}, {106.226, 1.}, {106.582, 0.636364},
          {107.108, 0.212121}, {107.965, 0.0505051}, {111.154, 0.}},
         {{100.434, 0.}, {102.461, 0.0555556}, {104.392, 0.333333}, {105.321, 0.611111},
          {105.867, 1.}, {106.226, 0.944444}, {106.405, 0.583333}, {106.582, 0.777778},
          {106.933, 1.}, {107.965, 0.444444}, {109.608, 0.166667}, {111.154, 0.0555556}},
         {{100.434, 0.0188679}, {102.461, 0.0566038}, {104.392, 0.}, {105.321, 0.54717},
          {105.867, 0.849057}, {106.226, 1.}, {106.405, 0.433962}, {106.582, 0.886792},
          {106.933, 0.924528}, {107.281, 0.660377}, {107.965, 0.320755},
          {111.154, 0.0566038}}}

A:
So, what is the best way to join points in Mathematica?

There is no one "best way" (not only in Mathematica, but in general); an interpolation scheme that behaves nicely for data set A might be a crapshoot when applied to data set B. It depends on the configuration of your points, and impositions you have on the interpolant (e.g. $C^1$/$C^2$ continuity, preservation of monotonicity/convexity, etc.), with these impositions not always being achievable all at the same time.
Having said this, if you're fine with a $C^1$ interpolant (interpolant and first derivative are continuous), one possibility is to use Akima interpolation. It is not always guaranteed to preserve shape (unless your points are specially configured), but at least for your data set, it does a decent job:
AkimaInterpolation[data_] := Module[{dy}, dy = #2/#1 & @@@ Differences[data];
          Interpolation[Transpose[{List /@ data[[All, 1]], data[[All, -1]],
                        With[{wp = Abs[#4 - #3], wm = Abs[#2 - #1]},
                             If[wp + wm == 0, (#2 + #3)/2, (wp #2 + wm #3)/(wp + wm)]] &
                        @@@ Partition[ArrayPad[dy, 2, "Extrapolated"], 4, 1]}],
                        InterpolationOrder -> 3, Method -> "Hermite"]]

MapIndexed[(h[#2[[1]]] = AkimaInterpolation[#1]) &, data];

Partition[Table[Plot[{h[k][u]}, {u, 100.434, 111.154}, Axes -> None,
                     Epilog -> {Directive[Red, AbsolutePointSize[4]], Point[data[[k]]]},
                     Frame -> True, PlotRange -> All],
                {k, 5}], 2, 2, 1, SpanFromBoth] // GraphicsGrid

Note that in the fifth plot, the Akima interpolant has a slight wiggle before hitting the third point; this, as I said, is due to the fact that Akima's scheme does not guarantee that it will respect the monotonicity of the data. If you want something that fits a bit more snugly, one scheme you can use is Steffen interpolation, which is also a $C^1$ interpolation method:
SteffenEnds[h1_, h2_, d1_, d2_] :=
       With[{p = d1 + h1 (d1 - d2)/(h1 + h2)}, (Sign[p] + Sign[d1]) Min[Abs[p]/2, Abs[d1]]]

SteffenInterpolation[data_?MatrixQ] := Module[{del, h, pp, xa, ya},
  {xa, ya} = Transpose[data]; del = Differences[ya]/(h = Differences[xa]);
  pp = MapThread[Reverse[#1].#2 &, Map[Partition[#, 2, 1] &, {h, del}]]/
       ListConvolve[{1, 1}, h];
  Interpolation[Transpose[{List /@ xa, ya,
                Join[{SteffenEnds[h[[1]], h[[2]], del[[1]], del[[2]]]},
                     ListConvolve[{1, 1}, 2 UnitStep[del] - 1] *
                     MapThread[Min, {Partition[Abs[del], 2, 1], Abs[pp]/2}],
                     {SteffenEnds[h[[-1]], h[[-2]], del[[-1]], del[[-2]]]}]}],
                InterpolationOrder -> 3, Method -> "Hermite"]]

MapIndexed[(w[#2[[1]]] = SteffenInterpolation[#1]) &, data]

Partition[Table[Plot[{w[k][u]}, {u, 100.434, 111.154}, Axes -> None,
                     Epilog -> {Directive[Red, AbsolutePointSize[4]], Point[data[[k]]]},
                     Frame -> True, PlotRange -> All],
                {k, 5}], 2, 2, 1, SpanFromBoth] // GraphicsGrid

Note that the interpolants from Steffen's method are a lot less wiggly, though the interpolant turns more sharply at its extrema. The advantage of using Steffen is that it is guaranteed to preserve the shape of the data, which might be more important than a smooth turn in some applications.
My point, now, is that sometimes, one must try a number of interpolation schemes to see what is most suitable for the data at hand, for which plotting the interpolant along with the data it is interpolating is paramount.

A: May not turn out to be a very general method but here I will adapt the Interpolation function of MMA in a way so that smoother result can be obtained for your specific data set.
Interpolation vs. ListLinePlot
First lets see how the default Interpolation behaves compared to the interpolating function used when we call ListLinePlot with same interpolation specification. We use Method-> "Spline" in both cases and vary the InterpolationOrder from 1 to 4.
GraphicsGrid[{
 Table[ff =Interpolation[#, Method -> "Spline", InterpolationOrder -> i] & /@data;
       Plot[#[x] & /@ ff // Release, {x, 101, 111},Frame -> None, Axes -> True,
       Epilog -> {Red, PointSize[Medium], Point[Flatten[data, 1]]}],
      {i, 1, 4}],
 Table[Show[
       ListLinePlot[#, InterpolationOrder -> i, Method -> "Spline",PlotRange -> All,
       PlotStyle -> Hue[RandomReal[]],Frame -> None, Axes -> True] & /@ data,
       Epilog -> {Red, PointSize[Medium], Point[Flatten[data, 1]]}],
      {i,1, 4}]
  }, Frame -> All, AspectRatio -> .5]

The plots in the first column are using default Interpolation function and they starts to oscillate quite naturally as from left to right higher order splines are used. We notice the plots using ListLinePlot are definitely more similar to what the OP is aspiring to achieve. We can get a less bumpy interpolation that still belongs to the $C^{3}(X)$ space of three times differentiable functions as follows.
Function I (ListPlotInterpolation):
Options[ListPlotInterpolation] = {InterpolationOrder -> 3,Method -> Automatic};
ListPlotInterpolation[data_, OptionsPattern[]] := Module[{pic, pts},
      pic = ListLinePlot[data, Method -> OptionValue[Method],
            InterpolationOrder -> OptionValue[InterpolationOrder],PlotRange -> All];
      Interpolation[First@Cases[pic, Line[pts : {{_, _} ..}] -> pts, Infinity],
             InterpolationOrder -> OptionValue[InterpolationOrder],
             Method -> OptionValue[Method]
       ]
 ];

Usage:
ListPlotInterpolation[data[[5]], Method -> "Spline",InterpolationOrder -> 3]

InterpolatingFunction[{{100.434,111.154}},<>]

In the following pic the plot in the left shows interpolation of the five given data sets using  the above function and all of them are indeed less oscillating than the default Interpolation results with same options at the right .

Taming the derivatives!
We can make the above situation a little better by taking the design advantage of the magic function Interpolation. We can always specify the derivatives numerically at the grid points to control the bumpiness of the interpolating function.
We will first use ListPlotInterpolation'[] to estimate the derivative at the given grid points. Then we use the TotalVariationFilter to regularize the discrete gradient further on.
Function II (InterpolationReduced):
Options[InterpolationReduced] = {InterpolationOrder -> 3, Method -> Automatic};
InterpolationReduced[data_, OptionsPattern[]] :=
    Module[{fun, coords, value},
        fun = ListPlotInterpolation[data, Method -> OptionValue[Method],
        InterpolationOrder -> OptionValue[InterpolationOrder]];
        coords = data // Transpose // First;
        value = Transpose@{data // Transpose // Last};
        Interpolation[Transpose[{Transpose@{coords}, value,
           (* You can change the filter parameter here *)
           TotalVariationFilter[fun'[coords], 1, Method -> "Laplacian",
           MaxIterations -> 200]}],
           InterpolationOrder -> OptionValue[InterpolationOrder]
          ]
      ]

Usage:
One can call the above function in similar fashion as the first one.
Now lets see how the gradients looks in case of three methods (default,ListLinePlot based and the TotalVariationFilter based). Each row of he following figure represent the methods respectively. From let to right each column represent InterpolationOrder of 1 to 4.

Compare!
Below in the last figure we show how all the three methods compare in terms of irregularity/bumpiness of their resulting interpolation output given the output needs to be a $C^{3}(X)$ class function.
See the most irregular fifth data set separately.

BR


text:
Q: How to take random sample of a cvs file in Python? I am new to Python and want to learn Data Wrangling process using it. I am using jupyter for this.
I have a file named fle with 81,000 rows and 89 columns. I want to randomly select about 100 rows from it. How do I do that? I keep on getting following error.
fle=pd.read_csv("C:\Users\Mine\Documents\ssample.csv", low_memory=  False)
import random
sampl = random.sample(fle, 10)

Error that I am getting is:
IndexError                                Traceback (most recent call last)
<ipython-input-37-fa4ec429f883> in <module>()
      1 import random
      2 #To take a sample of 10000 samples
 ----> 3 sampl = random.sample(fle, 10)
      4 #pd.DataFrame(sampler).head(10)

  C:\Users\E061921\AppData\Local\Continuum\Anaconda\lib\random.pyc in sample(self, population, k)
334             for i in xrange(k):         # invariant:  non-selected at [0,n-i)
335                 j = _int(random() * (n-i))
--> 336                 result[i] = pool[j]
337                 pool[j] = pool[n-i-1]   # move non-selected item into vacancy
338         else:

IndexError: list index out of range

A: use random.choice instead of sample.  you can use csv.DictReader to handle the csv as a list of dicts
import csv
import random

random_rows = set()
with open("C:\Users\Mine\Documents\ssample.csv", "r") as csvfile:
    reader = csv.DictReader(csvfile)

rows = [r for r in reader]
while len(random_rows) < 100:
    random_rows.add(random.choice(rows))


text:
Q: what is the "@" meaning in a asm inline function? I looking into a inline asm function, and I found a statement can't understand, the code is:
    static inline void arch_local_irq_enable(void)
    {
    unsigned long temp;
    asm volatile(
    "   mrs %0, cpsr    @ arch_local_irq_enable\n"
    "   bic %0, %0, #128\n"
    "   msr cpsr_c, %0"
    : "=r" (temp)
    :
    : "memory", "cc");
    }

The code is locate at : arch/arm/include/irqflags.h
In the 1st line, does "@ arch_local_irq_enable" means a comment? If so, would you tell me what document will tell the syntax? I searched in some site, but I failed to found that.
Thanks!

A: According to the GNU Assembler documentation on ARM syntax:

The presence of a `@' anywhere on a line indicates the start of a comment that extends
  to the end of that line.


text:
Q: Show that $\sup(\frac{1}{A})=\frac{1}{\inf A}$
Given nonempty set $A$ of positive real numbers, and define  $$\frac{1}{A}=\left\{z=\frac{1}{x}:x\in A \right\}$$ Show that $$\sup\left(\frac{1}{A}\right)=\frac{1}{\inf A}$$

let $\sup\left(\frac{1}{A}\right)=\alpha$ and $\inf A = \beta$. Apply the definition of supremum, $z<\alpha$, then there exist $z'\in 1/A$ such that for every $\epsilon>0$, $z'>\alpha-\epsilon$
And the definition of infimum, $x>\beta$ and there exists $x'\in A$ such that for every $\epsilon>0$, $x'<\epsilon+\beta$.
At this step, I don't see how to relate $\beta$ with $\alpha$ which is $\alpha=\frac{1}{\beta}$, can anyone give me a hit or suggestion. Thanks.

A: The crucial facts here are that if $x \in A$, then $x>0$ and the function
$x \mapsto {1 \over x}$ reverses order in $A$, that is, if $x,y \in A$, then $x<y$ iff${1 \over x } > {1 \over y}$.
We have $\sup_{x' \in A} {1 \over x'} \ge {1 \over x}$ for all $x \in A$.
Now let $x_n \in A$ such that $x_n \to \inf A$. Then this gives
 $\sup_{x' \in A} {1 \over x'} \ge {1 \over \inf A}$.
Since $x \mapsto {1 \over x}$ reverses order in $A$, we have
${1 \over \inf A} \ge {1 \over x}$ for all $x \in A$. Taking the
$\sup$ yields the desired answer,
${1 \over \inf A} \ge \sup_{x \in A} {1 \over x}$.

A: Let Inf$(A)=\beta(\neq0) \implies \forall\ a\in A,\ a\geq\beta$ and $\alpha=\sup\left(\frac{1}{A}\right)$. Since, $\frac{1}{A}$ is defined which means that $\forall\ a\in A,\ a\neq0. $
Claim: $\alpha=\frac{1}{\beta}$
$(i)\frac{1}{\beta}$ is an UB of $\frac{1}{A}.$
Since, $\beta $ is LB of $A\ \implies$ $$ \forall\ a\in A,\ a\geq\beta \implies \forall\ a\in A,\ \frac{1}{a}\leq \frac{1}{\beta}\implies \frac{1}{a} $$  So, $\frac{1}{\beta}$ is an UB of $A.$
Now we have to prove that $\frac{1}{\beta} $ is the LUB of $\frac{1}{A}\ i.e.\ \forall\ \epsilon>0\ \exists\ b\in \frac{1}{A}$ s.t. $\frac{1}{\beta}-\epsilon>b.$ Without loss of generality we can assume that $\epsilon $ is such that $\beta\epsilon<1.$
Let $\delta=\frac{\beta}{1-\beta\epsilon}-\beta$. Clearly, $\delta>0.$ Since, $\beta $ is the GLB of $A\ \implies \beta+\delta$ is not a LB of $A \implies \exists\ a\in A$ s.t $$\beta+\delta>a\geq\beta.$$ $$\implies \beta+\frac{\beta}{1-\beta\epsilon}-\beta>a\geq\beta. $$ $$\implies \frac{\beta}{1-\beta\epsilon}>a\geq\beta. $$ $$ \implies\frac{1-\beta\epsilon}{\beta}<\frac{1}{a}\leq \frac{1}{\beta} .$$ Since, $\frac{1}{a}\in \frac{1}{A} \implies \frac{1}{\beta}$ is the LUB of $\frac{1}{A}.$


text:
Q: Gradle AppEngine project file changes not reflecting without restart i wanted to know how others are hanlding this issue of file changes not getting reflected in running application which users gradle or maven (in this case gradle)
i have a gradle appengine project and while the application is running if i make any changes to static resources like HTML, CSS< JS , it not getting reflected in jetty war folder in appengine.
this is the only reason stopping me from using Gradle or Maven.
i wanted to konw

*

*is there is any standard solutions to resolve this issue ?

*if not what better alternative we have ?

*how actually others are using gralde in there project during development

i am using eclipse for development

A: Try using the flag for the devappserver to scan and reload :
-Dappengine.fullscan.seconds=5 (or some number of your liking)
If using gradle, as described in this issue on GitHub : https://github.com/GoogleCloudPlatform/gradle-appengine-plugin/issues/97
If launching directly from eclipse you might have to add it in the right place of the launch configuration.

A: In Maven run the 'package' goal and in Gradle run the 'assemble' task, both will update the target directory, and cause devserver to reload the application.


text:
Q: instanceof with shared prototype The following code logs 'true' 4 times:
var menuItem = {
    name: "New menuItem",
};

function food(name) {
    if(name) this.name = name;
    //this.resourceType = "food";
}
food.prototype = menuItem;

function drink(name) {
    if(name) this.name = name;
    //this.resourceType = "drink";
}
drink.prototype = menuItem;

var burger = new food();
var coke = new drink();

console.log(buger instanceof food);
console.log(burger instanceof drink);
console.log(coke instanceof food);
console.log(coke instanceof drink);

However if I comment out the following two lines:
//food.prototype = menuItem;
//drink.prototype = menuItem;

Then the code does what I want and logs true for "buger instanceof food" and "coke instanceof drink".
Is there a way of checking if the menuItem is an instance of either food or drink correctly while they both share the same prototype (menuItem)?
I'd prefer not to have to store the type like so:
this.resourceType = "food";

If there is a better way of doing it.

A: For each constructor, create a new object to use as the prototype of that constructor, and have each new prototype object use menuItem as its prototype:
food.prototype = Object.create(menuItem);

So the prototype chain for a food instance and drink instance now looks like:
[food instance] > [food prototype] > [menuItem]
[drink instance] > [drink prototype] > [menuItem]

The old chain looked like:
[food instance] > [menuItem]
[drink instance] > [menuItem]

As you can see, in the old chain, a food instance and drink instance really had the same prototype parent, so a food-constructed object and drink-constructed object has the same prototype parent. Under the new system, food and drink have separate prototype parents.
MDN has a good description of instanceof:

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

So, when you test burger instanceof drink you're testing "is drink.prototype in the prototype chain of burger?". Previously, drink.prototype was equal to menuItem, so you were really testing "is menuItem in the prototype chain of burger?". Now, drink.prototype is its own unique value, separate from food.prototype, so the result is false.


text:
Q: Ruby on rails tutorial chapter 12 random unrelated errors created This is my first foray into app development, and I have been following Michael Hartl's tutorial pretty much verbatim. All went fine until towards the end of chapter 12, when my tests started failing. The strange thing is that the tests which fail seem to be unrelated to the changes I made in chapter 12.
There are three failures and one error, and they are also duplicated by the local server when manually checked in the browser. Basically the logged_in_user before action doesn't seem to work, but only with some of the model actions, not all. I've tried to trace it with the debugger and tried to revert back to pre-chapter 12 commits (which all definitely worked) but I'm having trouble with database migrations and stuff and only introducing more and more errors. Below is the error log, my users controller, application controller and sessions helper. I feel like the error must be in one of those.
Many many thanks in advance for your help!

FAIL["test_should_redirect_update_when_not_logged_in", UsersControllerTest, 2016-03-06 05:58:45 -0800]
    test_should_redirect_update_when_not_logged_in#UsersControllerTest
    (1457272725.92s)
            Expected true to be nil or false
            test/controllers/users_controller_test.rb:27:in `block in '
ERROR["test_should_redirect_destroy_when_not_logged_in", UsersControllerTest, 2016-03-06 05:58:45 -0800]
    test_should_redirect_destroy_when_not_logged_in#UsersControllerTest
    (1457272725.96s) NoMethodError:         NoMethodError: undefined
    method admin?' for nil:NilClass
                app/controllers/users_controller.rb:77:inadmin_user'
                test/controllers/users_controller_test.rb:47:in block (2 levels) in <class:UsersControllerTest>'
                test/controllers/users_controller_test.rb:46:inblock in '
            app/controllers/users_controller.rb:77:in admin_user'
            test/controllers/users_controller_test.rb:47:inblock (2 levels) in '
            test/controllers/users_controller_test.rb:46:in `block in '
FAIL["test_should_redirect_edit_when_not_logged_in", UsersControllerTest, 2016-03-06 05:58:46 -0800]
    test_should_redirect_edit_when_not_logged_in#UsersControllerTest
    (1457272726.03s)
            Expected true to be nil or false
            test/controllers/users_controller_test.rb:21:in `block in '
FAIL["test_successful_edit_with_friendly_forwarding", UsersEditTest, 2016-03-06 05:58:46 -0800]
    test_successful_edit_with_friendly_forwarding#UsersEditTest
    (1457272726.07s)
            Expected response to be a redirect to <[removed link]/users/633107804/edit> but was a redirect to <[removed
    link]/users/633107804>.
            Expected "[removed link]users/633107804/edit" to be === "[removed link]/users/633107804".
            test/integration/users_edit_test.rb:22:in `block in '

class UsersController < ApplicationController

  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy, :following, :followers]

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to_users_url
  end

  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
  end

  def new
    @user = User.new
  end

  def index
    @users = User.paginate(page: params[:page])
  end

  def create
    @user = User.new(user_params)
   if @user.save
     @user.send_activation_email
     flash[:info] = "Please check your email to activate your account."
     redirect_to root_url
   else
     render 'new'
   end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def following
    @title = "Following"
    @user = User.find(params[:id])
    @users = @user.following.paginate(page: params[:page])
    render 'show_follow'
  end

  def followers
    @title = "Followers"
    @user = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    render 'show_follow'
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end

end

And the application controller:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

include SessionsHelper

private

#confirms a logged in user. Now placed in the application controller so both teh user controller and microposts controller can use it
def logged_in_user
  unless logged_in?
    store_location
    flash[:danger] = "Please log in."
    redirect_to login_url
  end
end

end

And the sessions helper:
module SessionsHelper
  #logs in the given user
  def log_in(user)
    session[:user_id] = user.id
  end

  # returns the current logged-in user (if any)
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: session[:user_id])
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # returns true if the user is logged in, and false otherwise
  def logged_in?
    !current_user.nil?
  end

  #Saves a user id and remember token digest to cookies
  def remember(user)
    user.remember
    #Code to save cookies with 20 year expiry ("permanent") and "signed" so it can't be accessed by third party
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  # runs the forget method and removes remember tokens from cookies
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # logs out the given user
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end

  def current_user?(user)
    user == current_user
  end

  # Redirects to stored location after trying to edit while logged out and then logging in
  def redirect_back_or(default)
    redirect_to(session[:forwarding_url] || default)
    session.delete(:forwarding_url)
  end

  # Stores the URL trying to be accessed
  def store_location
    session[:forwarding_url] = request.url if request.get?
  end

end

Userscontrollertest:
require 'test_helper'

class UsersControllerTest < ActionController::TestCase
  def setup
    @user = users(:Joe)
    @other_user = users(:Jane)
  end

  test "should redirect to index when not logged in" do
    get :index
    assert_redirected_to login_url
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should redirect edit when not logged in" do
    get :edit, id: @user
    assert_not flash.empty?
    assert_redirected_to login_url
  end

  test "should redirect update when not logged in" do
    patch :update, id: @user, user: { name: @user.name, email: @user.email }
    assert_not flash.empty?
    assert_redirected_to login_url
  end

  test "should redirect edit when logged in as wrong user" do
    log_in_as(@other_user)
    get :edit, id: @user
    assert flash.empty?
    assert_redirected_to root_url
  end

  test "should redirect update when logged in as the wrong user" do
    log_in_as(@other_user)
    patch :update, id: @user, user: { name: @user.name, email: @user.email }
    assert flash.empty?
    assert_redirected_to root_url
  end

  test "should redirect destroy when not logged in" do
    assert_no_difference 'User.count' do
      delete :destroy, id: @user
      end
        assert_redirected_to login_url
  end

  test "should redirect destroy when logged in as a non-admin" do
    log_in_as(@other_user)
    assert_no_difference 'User.count' do
      delete :destroy, id: @user
    end
    assert_redirected_to root_url
  end
end

A: After comparing your code to what I have in my tutorial code, try changing the order of the before_action statements in your UsersController and see if that works:
Before:
  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy, :following, :followers]

After:
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy, :following, :followers]
  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy

All the before_action statements are run in the order they are defined in the controller, so for the update action, you're currently running the correct_user filter first, which calls current_user?(@user), which calls current_user:
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: session[:user_id])
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

At that point in your tests, since you haven't logged in a user yet, you don't have a session[:user_id], so that if statement fails, and you also don't have a cookies.signed[:user_id], so the elsif statement fails, leaving you with a nil return value and @current_user not being set.
At some point in your request in the test, you seem to be finding its way over to the admin_user method, which is calling current_user.admin?, and since at this point current_user is nil, you're getting the NoMethodError: undefined method admin?' for nil:NilClass that you're seeing.


text:
Q: binary search of sorted array in assembly language [org 0x100]
;This code is for counting the size
        mov di, 0           ; to be used for indexing
        mov bp, s_a
        mov cx, 0
        jmp count

j1:     inc cx              ; storing the size in cx
count:  mov ax, [bp+di]
        add di, 2
        cmp ax, -1          ;-1 is the ending condition
        jne j1
;=================================;

        mov si, cx          ;Moving the size in si
        mov cx, 2           ;using cx for division number

;This code is for finding the centre point by division
j2:     mov ax, si
        mov bx, 0
        mov bx, cx
        div bl
;=================================;
        inc cx
        inc cx
        cmp al, 0           ;If al has 0 then the number is not in array
        je nfound
        mov dl, al
        mov di, 0

;Increasing bx to point to the required number
j3:     inc di
        inc di
        dec dx
        cmp dx, 0
        jne j3
;=================================;
        mov ax, [bp+di] ;Moving the centre number in array to ax
        mov dx, [b_s]       ;The number to be found

        cmp dx, ax
        je found

        cmp dx, ax
        jl below

        cmp dx, ax
        jg above

above:  add bp, di
        jmp j2

below:  jmp j2

found:  mov cx, bp
        add cx, di
        jmp exit

nfound: mov ax, [bp]        ;This code is for the first element
        mov di, 0
        cmp ax, [b_s]
        je found
        ;=================;
        mov cx, 0xffff
exit:

mov ax, 4c00h
int 21h

s_a: dw 1, 2, 3, 4, 5, -1
b_s: dw 5

This is my code for binary search its working fine for all numbers here except for '1' and '5'. I have handled the for '1'. Please suggest a solution for '5' as well. which means last number. '-1' is not to be searched.

A: I see some reasons why your code could fail.

*

*You assign a byte value to DL but later compare the word value in DX without making sure what DH contains.
mov dl, al
mov di, 0
;Increasing bx to point to the required number
j3:
inc di
inc di
dec dx
cmp dx, 0
jne j3

Either explicitely clear DH or decrement/compare only with DL.

*When the element was not found you simply jump back to label j2. This is wrong because you will be using the same number of elements contained in SI. You should recalculate the number of elements in the left/right partition. Either use (SI / 2) or (SI / 2 + 1)
Referring to the comment by Dirk Wolfgang Glomp

*

*Seeing [org 0x100] would mean that this is a .COM executable and so all segment registers should have the same value. Then there's no real need to write a DS: when using [bp+di].

Please clean up your code

*

*Writing 2 inc instructions in a row should become add ..., 2

*There's no need to move zero in a register before loading it with another register. mov bx, 0 mov bx, cx


text:
Q: Cloud computing over Client-server: differences, cons and pros? As far as I know, Cloud computing might be a evolution in software architect, and it will replace some current architectures, such as client-server.
These two architecture seem to share similarities for me (I know very little about both), but I don't know the differences between them. What are the cons and pros of cloud computing over client-server architecture?
Thank you so much.

A: Cloud Architectures are designs of software applications that use Internet-accessible on-demand services. Applications built on Cloud Architectures are such that the underlying computing infrastructure is used only when it is needed (for example to process a user request), draw the necessary resources on-demand (like compute servers or storage), perform a specific job, then relinquish the unneeded resources and often dispose themselves after the job is done. While in operation the application scales up or down elastically based on resource needs.
Example: an application that is currently in production using the on-demand infrastructure provided by Amazon Web Services. This application allows a developer to do pattern-matching across millions of web documents. The application brings up hundreds of virtual servers on-demand, runs a parallel computation on them using an open source distributed processing framework called Hadoop, then shuts down all the virtual servers releasing all its resources back to the cloud—all with low programming effort and at a very reasonable cost for the caller.

A: Client-Server
In the great-wide world of computing there are only two kinds of applications,

*

*standalone application, and

*client-server application

Standalone simply means the user-interface and the business logic and the datastore and any and all resources are completely self contained within a single execution environment - the end-user's machine.
In contrast, client-server means there is some logical segregation of these components, services, and resources. Typically we see user-interfaces in a local execution [aka "client"] and business and data store and other resources in a remote execution [aka "server"]. Some examples,

*

*MSN Messenger [contains an application we run on our local machine, while a back-end service facilitates communication at a remote location]

*Facebook [contains a thin application - our web browser - and a remote service - their servers]

*StackOverflow [same Facebook]

With this in hand, let's look at cloud computing.
Cloud Computing
Cloud computing is an abstraction of traditional server hosting solutions. Instead of buying 10 servers myself to run and manage in my own operations datacentre, I now lease X servers from a vendor where X is a variable number decided by me whenever I want.
There is a distinct advantage to leveraging a cloud. If I bought 10 servers, I must manage and maintain these 10 servers even if they are underutilized [say only 1 server is used 90% of the time, while all 10 are pinned 10% of the time at peak hours]. That means I am paying way too much in maintenance for 90% of the time, while being inflexible when I need to grow the remaining 10%.
The advantage of cloud computing is that "someone else" is managing the server farm for us, and is willing to lease out a variable number of machines to us on demand. So in our scenario above, I could lease 1 machine for 90% of the time in off-hours, and scale up to 10 or more machines the remaining 10% of the time.
Microsoft takes this abstraction one step further with Windows Azure. They do not lease generalized servers, but application domains. This is the one example [to mind] where a cloud implementation has actual design implications - but it is predicated on the same premise of elastic hosting.
Relation
For the most part, because client-server is a software paradigm and cloud computing is a hosting abstraction, they are independent concepts. Keeners, however will realize that cloud computing implies business, data stores, and other resources are remotely hosted, which necessitates that any application running within a "cloud" is part of a client-server application.

A: Cloud computing is just marketing wording of client-server architecture.

A: I think client server is generally implemented as a necessity for the software/application but cloud computing is generally opted for optimization like for saving on costs and maintenance.


text:
Q: Tracking files and file changes in excel At my place of work we have recently started to utilize Excel to track the receipt, processing, and authorization of faxes through a program called RightFax. When we receive the fax we enter the time received, fax number, and who the fax has been assigned to.
Throughout the day we monitor the end folder to see what faxes have been processed (and who they were approved by, if need be) and update them accordingly in the spreadsheet. Depending on the number of faxes this can be a lengthy amount of time. Since all of the faxes follow a standard naming scheme, Excel could be used to determine what each file name should be but could it then search for these files as well to detect where they are located on our shared drive? That is to say, could Excel tell me if a fax was waiting to be processed in the processor's folder, waiting for authorization in the auth folder, or done in the end folder?
In addition to this, is there any way to tag the files in a way that Excel could read to show who authorized them rather than having to open up each individual one?
Thanks in advance!

A: You could use "Track Changes" in excel to see who did what to the workbook. Review>>Track Changes
Instead, you could also use VBA to capture the username of the individual that opened the sheet or made a change to a specific tab. GetUserName function: http://support.microsoft.com/kb/161394  Running VBA when the workbook is open: http://www.ozgrid.com/VBA/auto-run-macros.htm
As for keeping an eye on the faxes in each folder... that could be done by Excel as well through VBA, but it would be a little messy and probably prone to errors here and there since it's not really the best piece of software for such a thing. If you want to go there: Check out the FileSystemObject: How do I use FileSystemObject in VBA?


text:
Q: Is constant current achievable with a dc/dc converter? I'm an electronics novice and part of a rocketry club. During the 4th of July we try to do a mass launch of rockets. Doesn't always work. I thought about building a capacitive discharge circuit to launch about 50 rockets and wow the spectators. The line of rockets would span about 100 feet using 22 gauge copper wire. I'd probably be another 100 feet away. For this much resistance I'm thinking I need a good amount of voltage.
So, each rocket requires an "electric match" to electrically fire. The electric match basically looks like a matchbook match head with wire leads. Each match requires 1 amp to pop and produce flame, per specs.
I purchased some photoflash capacitors, a toggle switch, a 12v battery and started to think about how I would charge the capacitor and looked into dc/dc converters. But most produced low watts. A 12v to 100v converter had a 1.5w spec. To my understanding that would only produce .015 amps. Somewhat expensive as well.
I need some insight on how I can get this to work. Would I need a dc/dc booster with a constant current of 1 amp?

A: The idea behind the capacitive discharge circuit is that you can charge it as slowly as you like, and then release it all quickly when needed. The current capability of the supply doesn't affect how the starters are ignited, it just affects how long it takes to recharge before the next launch.
The way this works is, your power supply can provide 15 mA for several seconds (or even minutes) to charge up the capacitors. The capacitors charge according to the formula
\$\dfrac{\mathrm{d}V}{\mathrm{d}t} = I/C\$
When charged, the stored energy in the capacitor is
\$ E = \dfrac{1}{2}CV^2\$
This energy is what you will use to heat up your igniters.
Then you disconnect the supply and close a switch to connect the capacitor to the igniter, and the capacitors can release its energy quickly into the igniter. The power supply isn't involved at all during the time when the igniters are being powered.
One thing to watch out for is, if the power supply is vastly underpowered, it will be spending a long time at the beginning of the charging cycle driving a much lower voltage than it is designed for (while the capacitor voltage is ramping up from 0 to near the inal value). Depending how the supply is designed, it might not last long when used this way.

A: I hear that a commercial electric match typically has a resistance of about 1.5 Ohm and a recommended firing current around 1 Ampere.
(Alan Yates. "Electrical Ignition".) (Pyromate: Basics of Electric Firing.) (Wikipedia: electric match.)
In other words, it (briefly) requires about 1.5 Watt per match to fire.
Since you want to launch 50 rockets at once, you need about 75 W of power.
A single automobile battery can easily supply several times this amount of power
for a minute.
It sounds like the setup have about 200 feet on the map of copper pair, so the total distance is 400 foot (out and back).
22 AWG copper wire has a resistance of about 16 Ohm per 1000 foot.
So 400 foot has a resistance of 6.4 Ohms.
As you have already discovered, simply applying the 12 V battery to a bunch of electric matches doesn't work.
By the often misunderstood maximum power transfer theorem,
the maximum power you can extract at the far end of a 6.4 Ohm resistance connected only to a 12 V battery is about 11.25 W.
So at 1.5 W per electric match, you can light at most 11.25 W / 1.5 W => 7 electric matches with this simple 12 V system.
To light 50 rockets requires a higher voltage, higher current, less lead-wire resistance, matches that require less power, or some combination.
So what is the simplest thing that could possibly work?
A big storage capacitor slowly charged up from 1 battery using some kind of DC-DC converter, and then quickly discharged into the electric matches, would work, as described by Alan Yates and The Photon. The system would weight much less than 4 batteries.
It may be simpler to use a few batteries of 12 V each
(perhaps borrow automobile batteries).
There are many arrangements that would work:

*

*Wiring all the matches in series, in a big loop, the entire loop would (briefly) run at 1 A. The total resistance of the loop is about 50 * 1.5 Ohm for the matches + 6.4 Ohm for the wiring = 81 Ohms. To drive 1 A through this resistance requires about 7 batteries (12 V each) in series. ( I*R = 1 A * 81 Ohm = 81 V )

*Wiring matches in chains of 10 matches per chain, then connecting all the chains in parallel, requires 5 chains at 1 A each, which would (briefly) pull 5 A from the battery. The total resistance of the loop is about 6.4 Ohm for the wiring + 1.5 Ohm * 10 / 5 = 9.4 Ohms. To drive 5 A through this resistance requires about 4 batteries (12 V each) in series. ( I*R = 5 A * 9.4 Ohm = 47 V ).

As others have already pointed out,
"matches wired in series-parellel combinations can fire more electric matches than series or parallel alone".
I see that Robert Briody has measured a surprisingly wide variation in the electrical characteristics of electric matches.


text:
Q: Jest unable to resolve alias used in SASS file in React project I have been trying to figure this out. I had a lot of issues trying to setup Jest in my react project. Below are my configurations:
webpack.config.js
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ip = require('ip');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js',
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              modules: true,
            },
          },
          'sass-loader',
        ],
      },
      {
        test: /\.(jpg|jpeg|png|svg)$/,
        loader: {
          loader: 'file-loader',
          options: {
            outputPath: 'images',
            name: '[name].[ext]',
          },
        },
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.scss'],
    alias: {
      sass: path.resolve(__dirname, 'src/shared/sass'),
      src: path.resolve(__dirname, 'src'),
    },
  },
  plugins: [
    new CopyWebpackPlugin([{ from: path.resolve('public') }]),
    new MiniCssExtractPlugin({ filename: 'css/main.css' }),
  ],
  devServer: {
    open: true,
    port: 3200,
    host: ip.address(),
    historyApiFallback: true,
    contentBase: path.resolve(__dirname, 'dist'),
    stats: 'errors-only',
  },
  stats: 'errors-only',
};

package.json
{
  "name": "AdminPortfolio",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@nivo/line": "^0.62.0",
    "@nivo/stream": "^0.62.0",
    "core-js": "^3.6.5",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-redux": "^7.2.1",
    "react-router-dom": "^5.2.0",
    "redux": "^4.0.5",
    "regenerator-runtime": "^0.13.7"
  },
  "devDependencies": {
    "@babel/core": "^7.11.0",
    "@babel/preset-env": "^7.11.0",
    "@babel/preset-react": "^7.10.4",
    "babel-jest": "^26.2.2",
    "babel-loader": "^8.1.0",
    "copy-webpack-plugin": "5.1.1",
    "css-loader": "^4.2.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "file-loader": "^6.0.0",
    "identity-obj-proxy": "^3.0.0",
    "ip": "^1.1.5",
    "jest": "^26.2.2",
    "mini-css-extract-plugin": "^0.9.0",
    "node-sass": "^4.14.1",
    "sass-jest": "^0.1.7",
    "sass-loader": "^9.0.2",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "scripts": {
    "start": "webpack-dev-server",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage --colors"
  }
}

jest.config.js
module.exports = {
  // Automatically clear mock calls and instances between every test
  clearMocks: true,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  collectCoverageFrom: ['src/**/*.{js,jsx,mjs}'],

  // The directory where Jest should output its coverage files
  coverageDirectory: 'coverage',

  // An array of file extensions your modules use
  moduleFileExtensions: ['js', 'json', 'jsx', 'scss'],

  moduleNameMapper: {
    '^sass(.*)$': '<rootDir>/src/shared/sass/$1',
  },

  transform: {
    '^.+\\.scss$': 'sass-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
  },

  // The paths to modules that run some code to configure or set up the testing environment before each test
  setupFiles: ['<rootDir>/enzyme.config.js'],

  // The test environment that will be used for testing
  testEnvironment: 'jsdom',

  // The glob patterns Jest uses to detect test files
  testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)+(spec|test).js?(x)'],

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  testPathIgnorePatterns: ['\\\\node_modules\\\\'],

  // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
  testURL: 'http://localhost',

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  transformIgnorePatterns: ['<rootDir>/node_modules/'],

  // Indicates whether each individual test should be reported during the run
  verbose: false,
};

Below is the component i am testing.
import React from 'react';
import classes from './style';

const PageHeader = ({ header }) => {
  return
{header}
;
};

export default PageHeader;

Below is the style.scss file
@import 'sass/theme';
@import 'sass/mix';

.header {
  @include withTheme {
    color: useValue('c08');
  }
  font-size: pxtorem(20);
  font-weight: 400;
  padding-bottom: 35px;
}

And this is my test file
import React from 'react';
import { shallow } from 'enzyme';
import PageHeader from './index';

const setup = () => {
  const props = { header: 'Test' };
  const wrapper = shallow(<PageHeader />);
  return { props, wrapper };
};

describe('PageHeader Test Suite', () => {
  it('Should have a div', () => {
    const { wrapper } = setup();
    expect(wrapper.find('div').exists()).toBe(true);
  });
});

When i run the test i get the following error
$ jest FAIL  src/shared/components/PageHeader/PageHeader.test.js  ● Test suite failed to run
    Import error in:    /Users/raj.prem/Desktop/Random/AdminPortfolio    The import "sass/theme" could not be resolved. Searched paths:     - /Users/raj.prem/Desktop/Random/AdminPortfolio/sass/_theme.scss
     - /Users/raj.prem/Desktop/Random/AdminPortfolio/sass/theme.scss     - /Users/raj.prem/Desktop/Random/sass/_theme.scss
     - /Users/raj.prem/Desktop/Random/sass/theme.scss     - /Users/raj.prem/Desktop/Random/AdminPortfolio/src/shared/components/PageHe
ader/sass/_theme.scss     - /Users/raj.prem/Desktop/Random/AdminPortfolio/src/shared/components/PageHe
ader/sass/theme.scss     - /Users/raj.prem/Desktop/Random/AdminPortfolio/node_modules/sass-jest/sass/_theme.scss     - /Users/raj.prem/Desktop/Random/AdminPortfolio/node_modules/sass-jest/sass/
theme.scss

      at Importer.pathLookupError (node_modules/sass-thematic/lib/ast.js:256:12)
      at Importer.resolveSync (node_modules/sass-thematic/lib/ast.js:237:16)      at importFor (node_modules/sass-thematic/lib/ast.js:317:34)
      at File.parse (node_modules/sass-thematic/lib/ast.js:385:11)
      at Importer.runSync (node_modules/sass-thematic/lib/ast.js:155:17)      at Object.parseSync (node_modules/sass-thematic/lib/ast.js:407:31)      at Function.Thematic.parseASTSync (node_modules/sass-thematic/index.js:13:14)
      at Object.process (node_modules/sass-jest/transform-sass.js:226:25)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/Sc
riptTransformer.js:463:35)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform
/build/ScriptTransformer.js:568:40)

Test Suites: 1 failed, 1 totalTests:       0 totalSnapshots:   0 total
Time:        1.306 s
Ran all test suites.
error Command failed with exit code 1.

It seems like the alias used in the scss file cannot be resolved. Can somebody guide me in setting this up to work? The test works just find when i remove the styling from the div and remove the import statement of the style.scss
Thank you.
EDIT: Or is there a way to ignore the scss since im not testing any styles. The styles are just used in the components.

A: The way I've got to solve this problem importing sass|scss files was using "identity-obj-proxy", as mentioned in this question.
$ npm i -D identity-obj-proxy
// package.json
{
  (...)
  "scripts": {
    "test": "jest",
    "start": "styleguidist server"
  },
  "jest": {
    "moduleNameMapper": {
      "\\.(css|sass)$": "identity-obj-proxy"
    }
  },
 (...)
}


text:
Q: Map navigation - Titanium How can I implement navigation in map in my application? When I click on a navigation button, it should navigate to the destination when the user starts moving. I researched on google. I didn't get any solution. Please some one help me.

A: I think its better to open the device google map instead of ti.map
var directionUrl;
directionUrl = "comgooglemaps://?saddr=" + dirLatitude + "," + dirLongitude + "&daddr=" + latitude + "," + longitude;

This is working fine for me.


text:
Q: How to overwrite datetimepicker enabledHours after initial load? On page load I initialized datetimepicker to this:
$('#txtdate').datetimepicker({
    inline: true,
    sideBySide: true,
    maxDate: someDate,
    minDate: curentDate,
    enabledHours: HoursArray(CurrentDayOpenTime, CurrentDayCloseTime)
});

but on new date selection I want to update/overwrite enabledHours (because on new date enabledHours are different) using below function.
$(document).on('dp.change', manipulateTime);

//function////

function manipulateTime(td){
    if (!td.date.isSame(td.oldDate, "day")) {
        $('#txtdate').datetimepicker({
            inline: true,
            sideBySide: true,
            maxDate: SomeCloseDate,
            minDate: SelectedDayOpenTime,
            enabledHours: HoursArray(SelectedDayOpenTime, SelectedDayCloseTime)
        });
    }
}

I couldn't able to overwrite the previous enabledHours. It always shows enabled hours which is generated on page load.
Can someone help me on this?

A: You can try the below code to change enabledHours:
$(document).on('dp.change', manipulateTime);

function manipulateTime(td){
   //Your code....
   $('#txtdate').data('DateTimePicker').enabledHours([21,22,23]); //change the array of enabled hours here
}


text:
Q: jquery S.get sending data with trim() How to send triimed data using $.get() see code snippet below:
$("#txtSearch").keyup(function() {
  $.get("/controller/method/",
     { 'param1': $.trim($("#txtSearch").val()) !== "" ? $.trim($("#txtSearch").val()) : return false; },
     function(data) {
         $("#div").html(data);
  });
});

This results in syntax error whether or not i give semi colon(":") after return false. So i just want to ask should i use var & assign txtBox data to var & then serach if yes then how to use var after giving 1st parameter i.e url path in $.get as i am using it inside of keyup function so i have to trim data inside of $.get.

A: Call $.get after checking the value of the textbox.
$("#txtSearch").keyup(function() {
    var textVal = $.trim($("#txtSearch").val();
    if ( textVal !== "" )
    {
        // call your $.get function here.
    }
    else
    {
        return false;
    }
});

A: I use this small utility function:
jQuery.fn.trimAndSerialise = function ()
{
    this.find('input, textarea').each(function()
    {
        $(this).val(jQuery.trim($(this).val()));
    });
    return this.serialize();
}

Then use it like this:
var f = $('#aForm');
var data = f.trimAndSerialise();

P.S. I haven't tested this with $.get though (I normally use $.ajax...)

A: This seems the most sensible:
$("#txtSearch").keyup(function() {
    var strSearchVal = $.trim($("#txtSearch").val());
    if (strSearchVal !== "")
    {
      $.get("/controller/method/",
     { 'param1': strSearchVal},
     function(data) {
         $("#div").html(data);
  });
}
    else
    {
        return false;
    }
    });


text:
Q: Pig - expression is not a project expression: (Name: ScalarExpression) Type: null Uid: null) Here is my file data :
86246,205,7,707,1078778070,12564,3/2/2012,12,OZ,1,7.59
86246,205,63,6319,107654575,17876,3/2/2012,64,OZ,1,1.59
86246,205,97,9753,1022027929,0,3/2/2012,1,CT,1,5.99
86246,205,25,2509,107996777,31373,3/2/2012,16,OZ,1,1.99
86246,205,55,5555,107684070,32094,3/2/2012,16,OZ,2,10.38
12277270,95,11,1114,107027272,5613,5/25/2013,32,OZ,1,5.49
12277270,95,26,2622,102570020,20361,5/25/2013,30,CT,1,4.79
12277270,95,9,902,104400040,19783,5/25/2013,8.5,OZ,1,1.88
12277270,95,27,2704,103270030,7966,5/25/2013,25,CT,1,13.99
12277270,95,97,9753,10000,0,5/25/2013,1,CT,1,6.7

Following step I performed to get my data :
Step 1:
transaction = LOAD 'projectDemo2/part-m-00000' USING PigStorage(',') as(id:chararray,chain:chararray,dept:chararray,category:chararray,company:chararray,brand:chararray,date:chararray,productsize:float, productmeasure:chararray, purchasequantity:int,purchaseamount:float);

Step-2
chainGroupCust = GROUP transactions BY (chain,id);

Step-3
chainGroupCustSpedings1 = FOREACH chainGroupCust GENERATE group, SUM(transactions.purchaseamount)
as spendings;

Step-4
chainGroupCustSpendings2= FOREACH chainGroupCustSpedings1 generate group.chain as chain,group.id as
id, spendings;

step-5
chainGroupCustSpendings3= GROUP chainGroupCustSpendings2 BY chain;

Step-6
chainTop10Cust = FOREACH chainGroupCustSpendings3{
chainGroupCustSpedingsSort = ORDER chainGroupCustSpendings2 BY spendings DESC;
top10Cust = LIMIT chainGroupCustSpedingsSort 10;
GENERATE top10Cust;
}

While doing step-6 I am getting the following error:
expression is not a project expression: (Name: ScalarExpression) Type: null Uid: null)
Can anyone please help me with this.


text:
Q: Access props value in another props' validator I want to access a props value in another props' validator:
props: {
  type: {
    type: String,
    default: "standard"
  },
  size: {
    type: String,
    default: "normal",
    validator(value) {
      // below I want to access the props `type` from above.
      return (this.type !== "caution" || this.type !== "primary") && value !== "mega"
    }
  }
}

But I'm getting TypeError: Cannot read property 'type' of undefined.
Any idea?

A: The this variable in a prop's validator does not reference the Vue instance. And, unfortunately, there's no real way to reference another prop's value in a prop's validator function.

One thing you could do would be to set a watcher on the Vue instance's $props object, setting the immediate option to true so that the watcher fires when the component is created. That watcher could trigger the validation logic where this is a reference to the Vue instance.
Here's a simple example:

Vue.config.productionTip = false;
Vue.config.devtools = false;

Vue.component('child', {
  template: '

',
  props: {
    type: {
      type: String,
      default: "standard"
    },
    size: {
      type: String,
      default: "normal"
    }
  },
  methods: {
    validateProps() {
      if ((this.type === "caution" || this.type === "primary") && this.size === "mega") {
        console.error('Invalid props');
      }
    }
  },
  watch: {
    $props: {
      immediate: true,
      handler() {
        this.validateProps();
      }
    }
  }
});

new Vue({
  el: '#app'
});

  <child type="caution" size="mega"></child>

Another option would be to pass an object with a type and size property as a single prop. That way the validator of that prop would have a reference to both values.

Vue.config.productionTip = false;
Vue.config.devtools = false;

Vue.component('child', {
  template: '

',
  props: {
    config: {
      type: Object,
      default: () => ({ type: "standard", size: "normal" }),
      validator({ type, size }) {
        return !((type === "caution" || type === "primary") && size === "mega");
      }
    }
  }
});

new Vue({
  el: '#app'
});

  <child :config="{ type: 'caution', size: 'mega'}"></child>

(And just a note: your validation logic is probably incorrect. As it's written, the statement in parenthesis will always evaluate to true. I updated that logic in my examples to be what I think you meant.)

A: If you only need to validate once, do it simply in the mounted() handler. This fails the jest tests for us, and logs an error in the browser.
props: {
  type: {
    type: String,
    default: "standard"
  },
  size: {
    type: String,
    default: "normal"
  }
},
mounted() {
  if ((this.type === "caution" || this.type === "primary") && this.size === "mega") {
    console.error('Invalid props');
  }
}

A: It is not possible. There were few propositions in VUE project but all were rejected:
https://github.com/vuejs/vue/issues/3495
https://github.com/vuejs/vue/issues/6787
https://github.com/vuejs/vue/issues/9925
The trivial way for such case is to use a computed property or to validate properties on created hook. In this case, all properties are available.


text:
Q: Instagram Real time updates tag - getting empty data, why? Heloo,
I am working on one project and I need real time updates from Instagram for certain tag.
This is my code for Create a Subscription
<?php
    $client_id = 'MOJID';
    $client_secret = 'MOJIDSECRET';
    $redirect_uri = 'http://example.net/instagram/callback.php';
    $apiData = array(
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri' => $redirect_uri,
        'aspect' => "media",
        'object' => "tag",
        'object_id' => "winter",
        'callback_url' => $redirect_uri
    );

    $apiHost = 'https://api.instagram.com/v1/subscriptions/';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiHost);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $jsonData = curl_exec($ch);
    curl_close($ch);
    var_dump($jsonData);
?>

And output is:
 [meta] => stdClass Object
        (
            [code] => 200
        )

    [data] => stdClass Object
        (
            [object] => tag
            [object_id] => winter
            [aspect] => media
            [callback_url] => http://example.net/instagram/callback.php
            [type] => subscription
            [id] => 3932963
        )

)

This is code for callback.php:
<?php
    if (isset ($_GET['hub_challenge'])){
        echo $_GET['hub_challenge'];
    }
    else{
        $myString = file_get_contents('php://input');
        $ALL = $myString."\r\n";
        file_put_contents('activity.log', $ALL, FILE_APPEND | LOCK_EX);
    }
?>

And a line from activity.log is:
[{"changed_aspect": "media", "object": "tag", "object_id": "winter", "time": 1385411793, "subscription_id": 3932963, "data": {}}]
I am getting the right subscription_id but the data is empty.
Also Acces log looks like:
54.209.52.224 - - [25/Nov/2013:20:59:20 +0100] "POST /instagram/callback.php HTTP/1.0" 200 231 "-" "Python-httplib2/0.7.4 (gzip)"
And this is good, status code 200 but once again data is empty. Instagram is 'comming' to my callback file but the data is empty.
What am I doing wrong?

A: Instagram Realtime API subscription will only let you know when there has been an update to your subscribed object, not what the update is.  Once you receive a notification, it is up to you to make a call to the API (in your case probably https://api.instagram.com/v1/tags/winter/media/recent ) and to see what the new content is.
Depending on the volume of changes, you will probably want to batch these calls up at certain time intervals, but the below should be a good start.  You'll also probably only want to retrieve items you haven't already retrieved.
<?php
if (isset ($_GET['hub_challenge'])){
    echo $_GET['hub_challenge'];
}
else{
    $myString = file_get_contents('php://input');
    $sub_update = json_decode($myString);

    $access_token = '{ previously saved, get this from DB or flatfile }';

    foreach($sub_update as $k => $v) // can be multiple updates per call
    {
        $recent_data = file_get_contents('https://api.instagram.com/v1/tags/'.$sub_update->object_id.'/media/recent?access_token='.$access_token);
        file_put_contents('activity.log', serialize($recent_data->data), FILE_APPEND | LOCK_EX);
    }

}
?>

A: I get the $_POST to say there is an update from one of authenticated users, problem is there are 153 of them subscribed to the feed. The only way to get check if a user has an update is to get their latest.
I also can post a photo on IG myself.  The $_POST is received triggering the loop of users being polled but the newest item won't show up in the api at the same time as the $_POST trigger arrives from the real-time api.