text:
Q: Cant complete mysql-python installation in OSX I have tried to get this to work, but I have had no success. I'm trying to install mysql-python by running :
pip install mysql-python

but I always get this error
clang: error: invalid version number in '-mmacosx-version-min=10.11'
error: command 'clang' failed with exit status 1

I have used homebrew to update all libraries and I have already installed mysql. I also made sure to have the latest pip, xcode and xcode command line tools.
I have searched for hours but I have not found a way get this package to build.
Please, if anyone has run into a similar situation, I would greatly appreciate a little bit of guidance.
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: mysql-python
Running setup.py bdist_wheel for mysql-python ... error
Complete output from command /usr/local/opt/python/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/qh/38cj02sj1fb83lfnsd4x3jm40000gn/T/pip-build-lCuswO/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /var/folders/qh/38cj02sj1fb83lfnsd4x3jm40000gn/T/tmpFVHSn1pip-wheel- --python-tag cp27:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.11-x86_64-2.7
copying _mysql_exceptions.py -> build/lib.macosx-10.11-x86_64-2.7
creating build/lib.macosx-10.11-x86_64-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb
creating build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.11-x86_64-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.11-x86_64-2.7
clang -fno-strict-aliasing -fno-common -dynamic -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.7.12/include/mysql -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.11-x86_64-2.7/_mysql.o -fno-omit-frame-pointer
clang: error: invalid version number in '-mmacosx-version-min=10.11'
error: command 'clang' failed with exit status 1

A: This might be because x-code is not installed
xcode-select --install

A: You should install MySQL through Homebrew first, to get python-mysql work properly on OS X.
pip uninstall MySQL-python
brew install mysql
brew install mysql-connector-c
pip install MySQL-python

Original answer : MySQL-python on mac


text:
Q: Removing dashes from strings in Python I'm trying to write code that will remove dashes from a string if it's in the middle of a word and not between them.  If the dash comes before or after a line break, this will also remove the line break.  According to the rules of this assignment, a dash that needs to be removed will always border a line break, a space, or another dash.  If the character to the left of the dash is a letter and the character to the right is a letter, it should not be removed.
def remove_dashes(string):
    lst = list(string)
    for i in range(len(lst)-1):
        if lst[i] == '-' and lst[i+1] == (' ' or '-' or '\n') or lst[i-1] == (' ' or '-' or '\n'):
            lst[i] = ''
            if lst[i+1] == '\n':
                lst[i+1] = ''
            elif lst[i-1] == '\n':
                lst[i-1]
        elif lst[i] == '-' and i == len(lst)-1 and lst[i-1] == (' ' or '-' or '\n'):
            lst[i] = ''
            if lst[i-1] == '\n':
                lst[i-1] = ''
    return "".join(lst)

So in theory "rem-\nove the-\nse da\n-shes--" would return as "remove these dashes" without any line breaks.  But "not-these-dashes" would just return as "not-these-dashes".  However, my code is not working.  Can anyone help?

A: You can use re.sub:
import re
s = ["rem-\nove the-\nse da\n-shes--", "not-these-dashes"]
new_data = [re.sub("-\n|--|\n-", '', i) for i in s]

Output:
['remove these dashes', 'not-these-dashes']

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to store all the text files of its pickle file into its appropriate folder? There are a few pickle files, I exported their respective text files. I need to store these text files into a folder where the pickle file and its corresponding text files should exist.
For example:
There is a folder A, the pickle for this is A.pkl and the text files for this are A-1.txt, A-2.txt.
The folder A should contain A.pkl, A-1.txt and A-2.txt in it.
In the logic which I wrote, there is a folder being created for every text file.
from pathlib import Path
from shutil import move
path_to_files = Path(r"/home/abc/Desktop/qwerty/op")
for txt_path in path_to_files.glob("*.txt"):
    dir_path = path_to_files / txt_path.stem
    dir_path.mkdir()
    move(txt_path, dir_path / txt_path.name)

Could anyone please help me with this logic?


text:
Q: Inno Setup : how to launch an executable with parameters I have a custom Java runtime image for Windows called java.exe and I can simply execute java -jar HelloWorld.jar to run my HelloWorld application.
Using Inno Setup, I want to create an installer for my HelloWorld application. I can create an installer for java.exe, but obviously it would just run my custom Java image, whereas what I want is to run java -jar HelloWorld.jar.
Does anyone know how this can be achieved? Inno Setup does not seem to support application parameters.
I found a hack, which is to create a batch file that would execute my command. The problem is that it opens an extra CMD window. I was able to overcome this using a visual basic script that calls the batch file. It works, but I wonder if there is a better way.

A: Based on the Inno Setup design, the way to pass parameters to the executable (Java in this case) is via the parameters configuration of the [icon] section. And using "minimized" in the Flags of the [icon] would cause the application to launch without opening any CMD windows.
The only downside of using [icon] parameters is that they are visible and modifiable by right clicking on the application icon. An alternative approach is to create a .bat file, or better yet: a .exe file that calls the application with the required parameters. If using .exe, then a simple call to execv would do. There's no need to fork.


text:
Q: Как вывести имя директории в bat файле? Из контекстного меню проводника на папке запускаю команду *\2.bat "%1"
в bat файле:
echo %~dp1
получаю:
C:\Users/*\Desktop\Петли\
как я могу получить название директории в bat файле?
Команда %~n1 не работает.

A: Помогла данная команда:
for %%i in (%1) do set "folder_name=%%~nxi"

A: echo %cd%

Это Вы имели ввиду?
Оно выводит текущую директорию (не батника и не конкретно название директории)


text:
Q: Adding an overlaid line on video footage following the center of the frames via video processing/pattern recognition I have multiple 1-minute videos taken outside (a building, a sea cliff, etc). The camera is not fixed, it's taken by a drone very slowly going up a cliff for example.
What I need to do, if even possible, is use OpenCV or other video processing framework to automatically add a path to each of those video, a red line.
The red line would follow the location pointed by the centre of the video frame.
It means that on each frame, I must find the locations pointed at on the previous/next frames via some sort of pattern recognition and somehow  link them with an overlaid red line path.
Is there some sort of algorithm or tool that facilitate this process? How would you approach this problem?
Example:
From those frames:

*
*
*
*

To those frames:

(in the real, slow, footage, the consecutive frames would be much closer to each other)
Looks like for all frames, I must try to locate all the previous/next frames and link their centres as an rightly ordered line. Surely, that must have been done before?


text:
Q: Create Custom UIView From Subclass On Main Thread iOS I have the following code to a run method that returns a UIImage made from a UIView that's created in separate UIView class file. The FlagMarkerView is a separate subclass of UIView and is referenced here. The problem is the line FlagMarker *markerView... throws the following Main Thread Checker Error and crashes the app.

UIView.init(coder:) must be used from the main thread.

The code used to work as is, but no longer works as I've updated the project to target iOS 11.
I tried wrapping the FlagMarkerView call in a dispatch_async(dispatch_get_main_queue(), ^{}); but that doesn't work because it doesn't get picked up by the return UIImage in the method. I also tried to use a -(void) method instead of returning a UIImage, but that's hazard with the complexity of my project.
Is there a way I can create the newMarkerImage in - (void)updateMyFlagsWitAlert: and use dispatch_async(dispatch_get_main_queue(), ^{ for FlagMarkerView so newMarkerImage can be created in line from markerImage.
- (void)updateMyFlagsWitAlert:(BOOL)isAllowed{
    for (AGSGraphic *graphic in weakSelf.flagOverlay.graphics) {
        FlagModel *flagToUpdate = graphic.attributes[@"flag"];
           UIImage *newMarkerImage =
                    [weakSelf markerImageForFlag:flagToUpdate withDetail:detail];
    }
}

- (UIImage *)markerImageForFlag:(FlagModel *)flag withDetail:(BOOL)withDetail {

    // This line crashes app
    FlagMarkerView *markerView = [[[NSBundle mainBundle]  loadNibNamed:@"FlagMarkerView" owner:self options:nil] objectAtIndex:0];

    [markerView setFlag:flag];
    UIImage *markerImage = [markerView imageWithDetail:withDetail];
    [markerView layoutIfNeeded];
    return markerImage;
}

A: You should probably redesign your code to be async, but the quickest way I could think of is something like:
    __block FlagMarkerView *markerView;
    dispatch_sync(dispatch_get_main_queue(), ^{
        markerView = [[[NSBundle mainBundle] loadNibNamed:@"FlagMarkerView" owner:self options:nil] objectAtIndex:0];
        [markerView setFlag:flag];
        UIImage *markerImage = [markerView imageWithDetail:withDetail];
        [markerView layoutIfNeeded];
    });
    return markerImage;

This will make your code run in the main thread, and wait for it to finish.
It is not a good design, you should probably design your code better and not rely on a return value.
Instead, your code could use a block as a parameter that will receive the result after it was processed in the main thread, instead of waiting for it using a semaphore.
But sometimes, if you just need something to work - this solution could be helpful.

A: The following code-change solved my problem. I found the problem is not with markerImageForFlag at all even though the Main Thread Checker highlighted the markerView. I believe the weakSelf reference put the task on the background thread, which was ok for awhile, but doesn't work anymore. All I had to do is put the dispatch_sync, not dispatch_async, on the call, newMarkerImage. Thanks to @Rob and @Moshe! See below.
- (void)updateMyFlagsWitAlert:(BOOL)isAllowed{
    for (AGSGraphic *graphic in weakSelf.flagOverlay.graphics) {
        FlagModel *flagToUpdate = graphic.attributes[@"flag"];

        __block UIImage *newMarkerImage = nil;

        dispatch_sync(dispatch_get_main_queue(), ^{
        newMarkerImage = [weakSelf markerImageForFlag:flagToUpdate withDetail:(scale < markerThreshold)];
        });

    }

}


text:
Q: Not understanding navigation using Frames I am having design problems regarding navigation and views. I need different views for my app such as OverviewPage, DetailPage, HomePage, etc.
I tried doing this with Frames:
MainFrame.Navigate(typeof(OverviewPage));

Then, while on the OverviewPage the user might navigate to the DetailPage, possible passing parameters to the new Page.
At this point I lose control of the Frame in OverviewPage since the Frame inside that navigated to DetailPage. I am surely doing something wrong, nesting Frames like that - but how else can I do this?
My other idea is using a single Grid with Grids/Panels inside of that which I show and hide with Visibility.Collapsed and Visibility.Visible. Is this an appropriate way to show different views depending on user action and context?
Any ideas would be great, I am clearly missing something.

A: There are some ways to do this, but I wouldn't use visibility to handle navigation, because there's already a NavigationService to do the job. You can use a single Frame to hold the views that you want to navigate. Let's say that you have a MainWindow that has a Frame like this:
<Grid>
    <Frame Name="ContentFrame" Content="{Binding}" NavigationUIVisibility="Hidden" />
</Grid>

Now you should create a public class that has a static method that will return a NavigationService. Lets call it Navigator.cs:
using System.Windows.Navigation;

namespace YourNamespace
{
   public class Navigator
   {
       public static NavigationService NavigationService { get; set;}
   }
}

This class returns a NavigationService, which will contain the current frame, the previous frames and other things.
Now you should set the NavigationService to the NavigationService of the ContentFrame of the MainWindow:
Navigator.NavigationService = window.ContentFrame.NavigationService;

Finally, you can handle navigation really easy now.
Navigator.NavigationService.Navigate(SomeView);

A: I suppose you're not using MVVM. There's not need to create new frames, as the pages are hosted inside a rootframe. Every page has a Frame property to reference this root frame, just use that property to navigate.
private void TestClick(object sender, RoutedEventArgs e)
{
    Frame.Navigate(typeof (BlankPage1));
}

Going back is as simple as:
Frame.GoBack();

A NavigationService is often used with the MVVM pattern, but for a very simple app without MVVM the Frame.Navigate approach is working perfectly.


text:
Q: Autowired Repository is Null in Custom Constraint Validator I have a Spring based webapp. I am using several repository classes with annotations @Repository, @Transactional in my Controllers. That part works fine.
I created a Custom Constraint Validator which has to access the repository. Now I am not able to understand why the Repository is null. I tried annotating the validator with @Component annotation. My base package containing all these classes is in the  part of the xml. So what else should I do to ensure the repository dependency injection works. This is how my Constraint validator looks like.
public class DonorTypeExistsConstraintValidator implements
    ConstraintValidator<DonorTypeExists, DonorType> {

  @Autowired
  private DonorTypeRepository donorTypeRepository;

  @Override
  public void initialize(DonorTypeExists constraint) {

  }

  public boolean isValid(DonorType target, ConstraintValidatorContext context) {

   System.out.println("donorType: " + target);
   if (target == null)
     return true;

   try {
    if (donorTypeRepository.isDonorTypeValid(target.getDonorType()))
     return true;
   } catch (Exception e) {
    e.printStackTrace();
   }
   return false;
  }

  public void setDonorRepository(DonorTypeRepository donorTypeRepository) {
    this.donorTypeRepository = donorTypeRepository;
  }
}

Update
Package scan configuration:
<context:annotation-config />

<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />

<context:component-scan base-package="controller" />
<context:component-scan base-package="repository" />
<context:component-scan base-package="model" />
<context:component-scan base-package="viewmodel" />

This class is in the package model.donortype.
The repository is in the package repository.
Update
Something more puzzling, removing all preinsert listeners (in this case only BeanValidationEventListener) fixes the autowiring issue. This has complicated the matter even more.
I am not even inserting the BeanValidationEventListener as described in the answer below. This is infact contrary to the suggestion here:
JSR-303 dependency injection and Hibernate
  @Override
  public void integrate(Configuration configuration, SessionFactoryImplementor implementor,
                        SessionFactoryServiceRegistry registry) {
      logger.info("Registering event listeners");
      System.out.println("here");
      // you can add duplication strategory for duplicate registrations

      final EventListenerRegistry eventRegistry = registry.getService(EventListenerRegistry.class);
      // prepend to register before or append to register after
      // this example will register a persist event listener

      eventRegistry.prependListeners(EventType.PERSIST, EntitySaveListener.class);
      eventRegistry.appendListeners(EventType.MERGE, EntitySaveListener.class);
      Iterator<PreInsertEventListener> iter = eventRegistry.getEventListenerGroup(EventType.PRE_INSERT).listeners().iterator();
      while (iter.hasNext()) {
        PreInsertEventListener el = iter.next();
        System.out.println(el.getClass());
        BeanValidationEventListener listener = (BeanValidationEventListener) el;
        System.out.println(listener);
        iter.remove();
      }
  }

Update
I am using JPA. I have a backing form for the JPA entities. In the controller I use InitBinder to instantiate a custom validator binder.setValidator(new EntityBackingFormValidator(binder.getValidator()));.
Here is the code for this:
https://github.com/C4G/V2V/blob/87dc266043f6d623c101d947a88fa0b0ad536355/src/controller/CollectedSampleController.java
This custom validator invokes the validation on the default validator and leaves scope to do some custom validations.
https://github.com/C4G/V2V/blob/87dc266043f6d623c101d947a88fa0b0ad536355/src/model/collectedsample/CollectedSampleBackingFormValidator.java
I am using annotations within the entity to create constraints. Apart from the default constraints, I need to define constraints that check whether a entity at the other side of a many-to-one mapping exists or not.
Here is the custom constraint validator.
https://github.com/C4G/V2V/blob/87dc266043f6d623c101d947a88fa0b0ad536355/src/model/donor/DonorExistsConstraintValidator.java
Now the autowired repository in this custom constraint validator is null. I am trying to customize code in my CustomIntegrator which is present here
https://github.com/C4G/V2V/blob/87dc266043f6d623c101d947a88fa0b0ad536355/src/interceptor/CustomIntegrator.java
and the xml configuration file present here
https://github.com/C4G/V2V/blob/87dc266043f6d623c101d947a88fa0b0ad536355/war/WEB-INF/v2v-servlet.xml
Hopefully the actual code will help you to answer my question.
Thanks!

A: Do you pass the validator factory to be used by JPA when performing validation:
<bean
    id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaPropertyMap">
        <map>
            <entry
                key="javax.persistence.validation.factory"
                value-ref="validator"/>
            <!-- ... -->
        </map>
    </property>
    <!-- ... -->
</bean>

That's required since otherwise the default factory (as specified in validation.xml) would be used by JPA.

A: Which ValidatorFactory are you using. Or to put it another way, hot to you bootstrap Bean Validation? Per default Bean Validation (and Hibernate Validator as reference implentation) does not inject dependencies into ConstraintValidator instances. At least in Bean Validation 1.0.
To enable dependency injection you have to configure a custom ConstraintValidatorFactory. Spring offers SpringConstraintValidatorFactory which is the default when using LocalValidatorFactoryBean - see http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html
Also, are you using JPA? I assume so, in which case auto validation on life cycle events automatically. Instead of trying to remove event listeners you can just use the property javax.persistence.validation.mode and set it to NONE. I am wondering whether the right validator is used on life cycle based validation.
It would all depend on your overall Spring configuration and use.

A: Do you have an @Component annotation on the DonorTypeExistsConstraintValidator?
That has killed me in the past.

A: No luck with LocalValidatorFactoryBean. I have done some hack to solve this problem.
@Component
public class ServiceUtils
{
    private static ServiceUtils instance;

    @Autowired
    private ListableBeanFactory factory;

    @PostConstruct
    public void init()
    {
        instance = this;
    }

    public static ListableBeanFactory getFactory()
    {
        return instance.factory;
    }
}


text:
Q: Largest size of a file from inode Could someone explain me the answer to this. I got this in a quiz and couldn't answer it.
Assume that

*

*All blocks in a disk are of size 4KB (4096 bytes).

*The top level of an inode is stored in a disk block of size 4KB.

*All file attributes, except data block locations, take up a total of
128 bytes (out of the above 4KB).

*Each direct block address takes up 8 bytes of space and gives the
address of a disk block of size 4KB.

*Last three entries of the first level of the inode point to single,
double, and triple indirect blocks respectively.

Question: What is the largest size of a file that can be accessed through direct block entries of the inode?

A: The calculations are quite simple:
(( 4096 − 128 ) / 8 − 3) × 4096 = 2019328


text:
Q: How to install generic haskell after install hugs and then install ghc6 then install generic-haskell has the following message, How to do?
# make package
Creating generic-haskell package ...
ghc-pkg: cannot find package generic-haskell
Reading package info from "generic-haskell.cabal.pkg" ... done.
generic-haskell-1.80: missing id field
generic-haskell-1.80: dependency "base-4.2.0.0" doesn't exist (use --force to override)
generic-haskell-1.80: dependency "haskell98-1.0.1.1" doesn't exist (use --force to override)
generic-haskell-1.80: dependency "containers-0.3.0.0" doesn't exist (use --force to override)
make: *** [package] Error 1

in ubuntu i compile ghc-6.2.2 got the following error
/usr/bin/ghc -M -optdep-f -optdep.depend  -osuf o    -H16m -O HaskTags.hs

on the commandline:

    Warning: -optdep-f is deprecated: Use -dep-makefile instead
------------------------------------------------------------------------
==fptools== make boot - --no-print-directory -r;
 in /home/martin/ghc-6.2.2/ghc/utils/ghc-pkg
------------------------------------------------------------------------
/usr/bin/ghc -M -optdep-f -optdep.depend  -osuf o    -H16m -O -cpp -DPKG_TOOL -DWANT_PRETTY Main.hs Package.hs ParsePkgConfLite.hs Version.hs

on the commandline:
    Warning: -optdep-f is deprecated: Use -dep-makefile instead
make all
/usr/bin/ghc -H16m -O -cpp -DPKG_TOOL -DWANT_PRETTY    -c Main.hs -o Main.o  -ohi Main.hi

Main.hs:496:11:
    Ambiguous type variable `e' in the constraint:
      `Exception.Exception e'
        arising from a use of `Exception.throw' at Main.hs:496:11-25
    Possible cause: the monomorphism restriction applied to the following:
      my_catch :: forall a. IO a -> (e -> IO a) -> IO a
        (bound at Main.hs:499:0)
      my_throw :: forall a. e -> a (bound at Main.hs:496:0)
    Probable fix: give these definition(s) an explicit type signature
                  or use -XNoMonomorphismRestriction

Main.hs:498:13:
    Ambiguous type variable `e1' in the constraint:
      `Exception.Exception e1'
        arising from a use of `Exception.catch' at Main.hs:498:13-27
    Possible cause: the monomorphism restriction applied to the following:
      eval_catch :: forall a. a -> (e1 -> IO a) -> IO a
        (bound at Main.hs:498:0)
    Probable fix: give these definition(s) an explicit type signature
                  or use -XNoMonomorphismRestriction
make[4]: *** [Main.o] Error 1
make[3]: *** [boot] Error 2
make[2]: *** [boot] Error 1
make[1]: *** [boot] Error 1

Any one have installed old version of GHC and generic haskell in ubuntu 10?
There are many pairs of version , i tried ghc-6.2.2 got above error, will i need to uninstall ubuntu 10 to install older version ubuntu to get it work? which version of ubuntu for which version of ghc work?
http://www.cs.uu.nl/research/projects/generic-haskell/compiler.html

A: Apparently, the generic-haskell package depends on an old version of base.
The Haskell Platform specifies base-4.3.1.0, while generic-haskell needs an older version. Please contact  the maintainers, or possibly, install an older version of GHC.

A: I tried installing generic-haskell myself from the source, I managed, and am able to describe how I fixed it. My installation platform is the Haskell Platform 2011.2.0.1-x86_64, but the following instruction are somewhat more general.
I met three problems, including the first one you describe (no. 3 below). For other users, I also describe the first two ones, which you probably solved as well.
1) Other users have first to fix an error depending on Data.Map.lookup type having changed, for containers >= 0.2.0.0: it used to return Monad m => m b (in containers-1.0.0.0), now it returns just Maybe b.
I added calls to Data.Maybe.maybeToList to fix a few call-sites needing to use a list type; I bet you fixed the same error in some way. You can find this fix at:
http://hpaste.org/47624.
2) Another error I had, with GHC 7, is that the configure script does not realize that it is newer than GHC 6.8, so it needs to also depend on containers. configure output included this line:

checking whether base package is split (GHC 6.8 or newer)... no

To fix this, you need to replace
if test $ghc_ma -ge 6 -a $ghc_mi -ge 8; then

with
if test $ghc_ma -eq 6 -a $ghc_mi -ge 8 -o $ghc_ma -ge 7; then

3) To fix your problem, you need to edit build/generic-haskell.cabal.pkg (assuming you are not doing an in-place installation with make in-place). You need to add an id: line and fix the depends line to use package-ids of packages present on your systems instead of package names. You can find out the ids using the following commands (output on my system included):
$ ghc-pkg field base id
id: base-4.3.1.0-f5c465200a37a65ca26c5c6c600f6c76
$ ghc-pkg field haskell98 id
id: haskell98-1.1.0.1-150131ea75216886448a7146c9e0526b
$ ghc-pkg field containers id
id: containers-0.4.0.0-b4885363abca642443ccd842502a3b7e

The change to build/generic-haskell.cabal.pkg would then be:
-depends:        base-4.3.1.0
-                haskell98-1.1.0.1
-                containers-0.4.0.0
+depends:        base-4.3.1.0-f5c465200a37a65ca26c5c6c600f6c76
+                haskell98-1.1.0.1-150131ea75216886448a7146c9e0526b
+                containers-0.4.0.0-b4885363abca642443ccd842502a3b7e

Furthermore, you need to add an id line to the same file - any id will do, as long as you change it if/when you reinstall the library. Here I've used:
id:             generic-haskell-1.80-lib-md5sum-2a7ae9d60440627618ad0b0139ef090b

I've also aligned all fields with spaces, as in the existing files. The syntax reference for this file can be found in:
http://www.haskell.org/ghc/docs/6.12.2/html/users_guide/packages.html#installed-pkg-info


text:
Q: Dominant term in time complexity If an algorithm has time complexity O(n+m), and we know that m >= n (e.g., we're traversing a connected graph with n nodes and m edges). Then I think the following is true:

*

*O(n+m) = O(m)

*O(n log n + m) cannot by simplified

Is this correct?

A: Yes. To eliminate one of those terms you'd have to know more about n / m.


text:
Q: Angular-translate: Set custom loader option from controller Today, I have an config for the translateProvider looking like this:
App.config(['$translateProvider', function ($translateProvider) {
  $translateProvider.preferredLanguage('en-US');
  $translateProvider.useLoader('TranslationLoader', { versionIdentifier : 127} );
  $translateProvider.useMissingTranslationHandler('MissingTranslationHandler');
}]);

The problem is that I don't know the value of the formIdentifier-option at configuration time. I get this value after resolving the first state in ui-route. I've tried to set the translationProvides loader in the state's controller, but realized that that's not possible :)
Any ideas?

A: angular-translate allows you to use any service as a loader as long as it meets a desired interface. But it doesn't restrict you in ways of how you pass additional parameters to the loader. So, you may pass them just like you want.
For example, you can set additional parameters directly to the loader. Just implement setters for them on top of your loader:
module.factory('Loader', [
'$q',
function($q) {

    var myParam;

    var loader = function(options) {
        var allParams = angular.extend({}, { myParam: myParam }, options);
        var deferred = $q.defer();

        // load stuff

        return deferred.promise;
    };

    loader.setMyParam = function(param) {
        myParam = param;
    };

    return loader;
}])

Also, you may try to set these parameters with some helper service (either sync or async:
module.factory('SyncLoader', [
'$q', '$injector',
function($q, $injector) {

    var loader = function(options) {
        var helper = $injector.get(options.helper);

        var myParam = helper.getMyParam();

        var deferred = $q.defer();

        // load stuff

        return deferred.promise;
    };

    return loader;
}]);

or
module.factory('AsyncLoader', [
'$q', '$injector',
function($q, $injector) {

    var loader = function(options) {
        var helper = $injector.get(options.helper);

        var deferred = $q.defer();

        helper.getMyParam()
            .then(function success(myParam) {
                // load stuff
            }, function error() {
                // fail, probably
            });

        return deferred.promise;
    };

    return loader;
}]);

Also, it might be possible to use events somehow. Or, maybe, there are some other ways possible. It depends on a specific architecture.


text:
Q: The Cantor Space and open, but not closed sets. consider the space $\{0,1\}^{\mathbb{N}}$ of all infinite binary sequences, called the Cantor-Space. This space is metrizable with metric
$$
 d(u,v) = 2^{-(r-1)} \qquad \textrm{ where } r = \operatorname{min}\{n : u_n \ne v_n\}.
$$
Therefore we have a topology. Let $X = \{0,1\}$. The open sets are sets of the form $W \cdot X^{\mathbb{N}}$ with $W \subseteq X^{*}$. The clopen sets are sets of the form $W \cdot X^{\mathbb{N}}$ with $W \subset X^{*}$ and $W$ finite. Now I conjecture:
If $E = W\cdot X^{\mathbb{N}}$ with $W$ infinite, then there exists a $w$ such that $w \in \overline{W}$ (i.e. there exists a sequence $w_i$ with $w_i \to w$) and $w \notin E$ (because then $w$ is open but not closed). For some examples I could construct such a sequence, but I am unable to find such a sequence for an arbitrary set of this form? Is it possible to construct such a sequence?

A: I came back to your question and it seems I got it this time (otherwise I still may try to take a look at it near 2021. :-)).
I'll assume that $X^*$ is a set of finite words over $X$ and for each word $w\in X^*$ the set $w\cdot X^{\Bbb N}$ consists of all elements of $X^{\Bbb N}$ which starts from $w$.
Let $E = W\cdot X^{\mathbb{N}}$ with $W$ infinite. Consider a reduced set  $$W^r=\{w\in W: w\mbox{ has no proper prefix in }W\}.$$ Then $W\cdot X^{\mathbb{N}}=W^r\cdot X^{\mathbb{N}},$ and we wish to exclude a case when the set $W^r$ is finite.
The by induction we can define a sequence $\{v_n:n\ge 0\}$ of words over $X$ such that $v_0=\varnothing$ and for each $n\ge 1$
(i) A word $v_n$ has length $n$,
(ii) a word $v_{n-1}$ is a prefix of $v_n$,
(iii) a set $W_n=\{w\in W_r: v_n\mbox{ is a prefix of }w \}$ is infinite.
Conditions i and ii implies that there exists an infinite word $w=\lim _{n\to\infty} v_n\in X^{\Bbb N}$.  Conditions i and iii imply that $w\in\overline{W^r\cdot X^{\Bbb N}}$. Asssume that $w\in W^r\cdot X^{\Bbb N}$. Then $w$ has a prefix $w_n\in W^r$ of length $n$ for some $n$. Then $w_n=v_n$ and it is a prefix for each word from the set $W_{n+1}\subset W^r$, which contradicts the irreducibility of the set $W^r$.


text:
Q: Scrape text with playwright is slow on part of the code (using page.locator) I have made a script in playwright, to scrape some text.
This is the part i have problems, here i scrape a series name, using locator:
# Series
global nfo_series
try:
  nfo_series = page.locator("#Series > span:nth-child(1)")
  nfo_series = nfo_series.inner_text()
  logger_scraper.info('nfo_series is now:%s', nfo_series)
except:
  logger_scraper.info('This book as no series.')

and it works, when the series are not present is skipped, but it takes 30 seconds to the code move on, the log is below, what is the problem, can i improve it?
19:28:31 nfo_author is now:Thomas Fincham
19:29:01 This book as no series.

i think its because of the try statement, but why? as i have the same code, for per example, author and it is fast.
i know it is not good to use playwright, best are other modules.

A: Playwright's default timer is 30 seconds.
So in the try part, it tries for 30 seconds to get the series, but there is none, so after 30 seconds only, it goes to the exception.
You can set a custom timout when calling inner_text().
See: https://playwright.dev/python/docs/api/class-locator#locator-inner-text


text:
Q: gdb core debug - how to display .so name in backtrace I'm trying to debug a core dump of a large project with gdb.
The problem is that the application is a set of quite a lot of shared objects. Also each component is encrypted.
Now it is quite a lot of work to prepare whole environment locally (might take even couple of days). So I was hoping that when I try to debug the coredump I will at least get .so names in backtrace, so I can fetch only the files which I really need.
Unfortunately when doing this I just get empty results like this:
Thread 3 (LWP 4582):
#0  0x00007f11956d6d50 in ?? ()
#1  0x00007f112a810a68 in ?? ()
#2  0x000000002a810ab8 in ?? ()
#3  0x00007f1134001b00 in ?? ()
#4  0x00007f112a810a90 in ?? ()
#5  0x00007f112a810a68 in ?? ()
#6  0x00007f1169d3ba5b in ?? ()
#7  0x000000000163ccd8 in ?? ()
#8  0x0000000000000000 in ?? ()

Is it correct that coredump doesn't even know the name of executable nor shared object which caused an error?
Is there any way to get this information?
Thank you

A: The most likely cause of this:

(gdb) info shared No shared libraries loaded at this time

is that you are analyzing a core from a remote machine, and are not doing it correctly.
In particular, GDB knows which shared libraries were loaded in the process at crash time by examining contents of _r_debug variable in the loader (this isn't exactly correct, but is close enough).
GDB finds the address of _r_debug by looking at local ld-linux, and it finds the value by looking up that address in the core.
If the ld-linux present on the machine at crash point is different from ld-linux present on the analysis machine, then GDB will effectively look at a random address, and will not be able to locate any shared libraries.
To set this up correctly, use this answer. At a minimum, you must provide the right ld-linux.so. While you are at it, also copy libc.so.6 and libpthread.so.0 -- these are required to get a correct stack trace if the program was terminated by a signal.


text:
Q: microsoft wedge mobile keyboard I have a "Microsoft wedge mobile keyboard".  It changes the Function key to play, mute, search, share, etc...  I cannot find any driver or programs for this keyboard.
Can I change it back to normal function key instead?

A: http://www.autohotkey.com/
With this script, work for me!
Media_Play_Pause::F1
Volume_Mute::F2
Volume_Down::F3
Volume_Up::F4
<+#F21::F5
<!<#F21::F6
<^<#F21::F7
<#F21::F8
PrintScreen::F9
Home::F10
End::F11
PgUp::F12
F1::Media_Play_Pause
F2::Volume_Mute
F3::Volume_Down
F4::Volume_Up
F5::<+#F21
F6::<!<#F21
F7::<^<#F21
F8::<#F21
F9::PrintScreen
F10::Home
F11::End
F12::PgUp

A: Reply from MVP, they said it is hardware function, which means it cannot be changed.  It is not for a programmer to use it.  :(


text:
Q: Rails views helper don't seems to work with render_to_string I try to convert rails views into pdf with the gem wicked_pdf.
But when I do a render_to_string like this
ActionController::Base.new.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')

Methods like user_path don't work and return undefined method error... (note that the page work properly if I render it in html)
If someone can help me !

A: You can include helpers by using the following method
ac = ActionController::Base.new
ac.view_context_class.include(ActionView::Helpers, ApplicationHelper)
ac.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')

A: Unfortunately, using render_to_string will not give you access to Rails URL helpers. One workaround is to include them directly in the locals that you pass into the PDF template using something like url: Rails.application.routes.url_helpers:
ActionController::Base.new.render_to_string(
  template: "templates/pdf_meteo.html.erb",
  locals: {url: Rails.application.routes.url_helpers, communaute_meteo_id: id}
  layout: 'pdf'
)

And then inside of your PDF template you would call them with:
url.user_path

Keep in mind that by default the _path URL helpers will be relative, and not absolute paths. You can instead use the _url version of the helpers and set the host for them in a few different ways. You can configure them globally for your entire app:
# config/environments/development.rb
Rails.application.routes.default_url_options[:host] = 'www.mysite.com'

or set them individually on each helper inside of your PDF template:
url.user_url(host: 'www.mysite.com')

Hope that gets you what you need!

A: Simplest way is to use regular rails rendering flow - with view file your_action_name.pdf.erb, trick is in overriding formats for partials:
<%= render partial:"some_partial", formats:[:html] %>

Also you can run render_to_string in context of your controller to have helpers (because ActionController::Base knows nothing about your app)


text:
Q: Sample Application - Amazon S3 / Indy / Delphi I am looking for an example application to store objects to Amazon S3 using INDY components.
Any help much appreciated.
Phillip

A: Here's a demo with Synapse, it should be easy to use Indy instead:
http://www.itwriting.com/s3example_21dec06.zip


text:
Q: How to condition Check In\Out file Is there a code by which method should I check the status of the Check Out\In?
SPCheckOutStatus not correct method? Or am I not correctly calling?

var list;
var item;
var file;
  function fileCheckIn() {
   var clientContext = SP.ClientContext.get_current();
   if (clientContext != undefined && clientContext != null) {
   var webSite = clientContext.get_web();
   this.list = webSite.get_lists().getByTitle("DEPLOY");
   this.item = list.getItemById(2);
   this.file = this.item.get_file();
if (this.file.CheckOutStatus != this.SPCheckOutStatus.None)
{
    //file was checked out
     alert('Ok');
}
    }
}

A: You need to use get_checkOutType() property and SP.CheckOutType enum to check the status.
Modify the code as below:
var clientContext = SP.ClientContext.get_current();
if (clientContext != undefined && clientContext != null) {
    var web = clientContext.get_web();
    var list = web.get_lists().getByTitle("DEPLOY");
        var item = list.getItemById(2);
        var file = item.get_file();
        clientContext.load(file);
        clientContext.executeQueryAsync(function(){
          if(file.get_checkOutType() == SP.CheckOutType.none)
                console.log(file.get_name()+ " is not checked out.");
          else if(file.get_checkOutType() == SP.CheckOutType.online)
                console.log(file.get_name()+ " is checked out for editing on server.");
          else
                console.log(file.get_name()+ " is checked out for editing on local computer.");

    },function(sender,args){
            console.log('Error: ' + args.get_message() + '\n' + args.get_stackTrace() );
    });
}

Reference - SP.CheckOutType enum
SP.File.checkOutType property

A: We can also use Rest API like below to check if a file is checked out:
$.ajax({url: window.location.href.toLowerCase().split('pages')[0] + "_api/web/getFileByServerRelativeUrl('" + window.location.pathname  + "')/checkOutType",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function(data) {

                  if(data.d.CheckOutType === 0) {
                    console.log('The file is checked out');
              } else {
                    console.log('The file is not checked out');
              }

              console.log(data.d.CheckOutType, 'data.d.CheckOutType');
            }
    });

Checking if a SharePoint 2013 Page is Checked Out or Published with JavaScript and REST


text:
Q: I'm having issues pushing a commit to bitbucket using SourceTree git -c diff.mnemonicprefix=false
    -c core.quotepath=false
    push -v --tags --set-upstream origin Front-end:Web-Pages
fatal: unable to access

'https://example@bitbucket.org/example/example.git/':
  Unknown SSL protocol error in connection to bitbucket.org:443

Pushing to https://example@bitbucket.org/example/example.git

Completed with errors, see above.

Please, how do i go about this?

A: Few options:

*

*A temporary reply when they have service issues:
https://answers.atlassian.com/questions/25142498/unknown-ssl-protocol-error-in-connection-to-bitbucket.org503

*You are beyond a proxy

*Quota limit as suggested in one of the above links. even due i never encored this one my self even when i passed the quota.

What else can you do?
Verify that you are using the correct SSL configuration:
It should be set to Open SSH unless you using putty.

A: I already found the solution to this problem.
$ git config --global http.proxy 127.0.0.1:8080

setting the proxy host and port number in git.


text:
Q: I want to make function button that puts text and number in the input to the variables in the code I'm learning html, css and Javascript receltly, Since first day of this month.
I patched those codes
So I'm trying to make some kind of map that I can mark place with name.
I got data from KAKAO MAP API.(Common map app in KR.)
There's multiple input that I can choose how many list I want to submit placename and address(lat,lng).
So I want to make function working on 'find' button when I click it
put name and address into
title: HERE,
latlng: new kakao.maps.LatLng( AND HERE)
so they marked on the map.
Can anyone help me with this? or just let me know how I solve this any ways.
Thanks for reading.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Marker</title>

    <link rel="stylesheet" href="MMMAP.css">

          <form id="form1">
            Number:
            <input type="text" id="inputs" value="25" name="inputs"/>
            <input type="button" id="button1" value="create" />

            <input type="button" id ="button2" value="find" />
          </form>


text:
Q: Reference for table of Schur polynomials Can anyone guide me to a reference where I can find a table of some Schur polynomials?  Schur polynomials of degree $m$ are indexed by partitions of $m$ and form a basis of symmetric polynomials of degree $m$. If I could find a table with even some Schur polynomials corresponding to partitions of 3,4 and perhaps 5, that would be great.
Thanks!

A: There's a table on page 315 (Figure 7-4) of Stanley's Enumerative Combinatorics Vol. II expressing the first few in terms of the monomial symmetric functions:


text:
Q: How to pass useState value to getServerSideProps in Nextjs? Hi guys so I have been on this for 4 hrs trying to filter a product.
I have setState upon onClick event.
I can think of or find info on changing the query. THis is my code:
export async function getServerSideProps() {
    await db.connect();
    const products = await Product.find({}).lean();
    const categories = await Category.find({}).lean();
    await db.disconnect();
    return {
        props: {
            products: products.map(db.convertDocToObj),
            categories: categories.map(db.convertDocToObj),
        },
    };
}

I have passing the state value but nothing. I think it is to provide an variable for the state and slap it in where 'meat' is, but should i dont know if i am to make serverside request that way
const products = await Product.find({ category: 'meat' }).lean();

A: Your getServerSideProps usage is correct. I would bet there is something incorrect with your data fetching.
Make sure products and categories are what you think they are before returning them in props here. I am unfamiliar with convertDocToObj method but if that returns a promise you will have to resolve that before returning from getServerSideProps.
Once products and categories are valid they will be available as props in your component:
function Page({ products, categories }) {
  // Render data...
}


text:
Q: exp() math.c i c not working if in a loop I'm currently working on a pid regulator for at school project.
Since the corona is has shut down the school we can't get any hardware to test it with.
So i want to simulate the PID regulator on a microprocessor (PSoC5LP).
So i'm implementing a function that returns a step respons of the chosen dc motor.
When i'm finding the output of the transferfunction "(-3.47*exp(-6.36*s)+3.47))" i get the right result if i define the value of "s" manually in the code.
But when i set s to be incremented in the code "undefined reference to "exp".
The problem seems to be that i can't run exp in a loop while incrementing it.
tried it in another project, where the only thing that happens is that a loop goes 10 times and prints out the exp() with the nr of times the loop have run (does not work)
float step_respons(){
    double s = 0.1;
        snprintf(outpurBuffer, sizeof(outpurBuffer), "%f \r\n", (-3.47*exp(-6.36*s)+3.47));
        pc_uart_PutString(outpurBuffer);
        snprintf(outpurBuffer, sizeof(outpurBuffer), "%f \r\n", (-3.47*exp(-6.36*1)+3.47));
        pc_uart_PutString(outpurBuffer);
    //These works just fine

    pc_uart_PutString("Loop:\r\n");

    for(s = 0.1; s < 2; s++){
        snprintf(outpurBuffer, sizeof(outpurBuffer), "%f %f \r\n", s,(-3.47*exp(-6.36*s)+3.47));
        pc_uart_PutString(outpurBuffer);
        //this does not work (if "s" is changed with a number it works fine.)

    };

    return 0;
};

So it works if i choose S manually in the loop, but if it gets incremented it stops.
I've tried to use another variable and increment that on and it still does not work
    for(s = 0.1; s < 2; s++){
        snprintf(outpurBuffer, sizeof(outpurBuffer), "%f %f \r\n", s,(-3.47*exp(-6.36*s)+3.47));
        pc_uart_PutString(outpurBuffer);

    };

does not work
    for(s = 0.1; s < 2; s++){
        snprintf(outpurBuffer, sizeof(outpurBuffer), "%f %f \r\n", s,(-3.47*exp(-6.36*1)+3.47));
        pc_uart_PutString(outpurBuffer);

    };

does work but no incrementation of the result is done
As you can se the only changes done in the loop is the "s" have been defined a value
double temp = 0.5;

    for(s = 0.1; s < 2; s++){
        snprintf(outpurBuffer, sizeof(outpurBuffer), "%f %f \r\n", s,(-3.47*exp(-6.36*temp)+3.47));
        pc_uart_PutString(outpurBuffer);

    };

this works
double temp = 0.5;

for(s = 0.1; s < 2; s++){
        snprintf(outpurBuffer, sizeof(outpurBuffer), "%f %f \r\n", s,(-3.47*exp(-6.36*temp)+3.47));
        pc_uart_PutString(outpurBuffer);
        temp += 0.5;
    };

does not
This is the error: Build error: undefined reference to 'exp'
The log from the compiler output
--------------- Build Started: 04/28/2020 01:34:42 Project: Plotterkode, Configuration: ARM GCC 5.4-2016-q2-update Debug ---------------
The code generation step is up to date.
The compile step is up to date, no work needs to be done.
arm-none-eabi-ar.exe -rs .\CortexM3\ARM_GCC_541\Debug\Plotterkode.a .\CortexM3\ARM_GCC_541\Debug\cy_em_eeprom.o .\CortexM3\ARM_GCC_541\Debug\CyDmac.o .\CortexM3\ARM_GCC_541\Debug\CyFlash.o .\CortexM3\ARM_GCC_541\Debug\CyLib.o .\CortexM3\ARM_GCC_541\Debug\cyPm.o .\CortexM3\ARM_GCC_541\Debug\CySpc.o .\CortexM3\ARM_GCC_541\Debug\cyutils.o .\CortexM3\ARM_GCC_541\Debug\pc_uart.o .\CortexM3\ARM_GCC_541\Debug\pc_uart_PM.o .\CortexM3\ARM_GCC_541\Debug\pc_uart_INT.o .\CortexM3\ARM_GCC_541\Debug\pc_uart_BOOT.o .\CortexM3\ARM_GCC_541\Debug\pc_uart_IntClock.o .\CortexM3\ARM_GCC_541\Debug\isr_pc_uart.o .\CortexM3\ARM_GCC_541\Debug\Pin_adc_input.o .\CortexM3\ARM_GCC_541\Debug\MISO.o .\CortexM3\ARM_GCC_541\Debug\MOSI.o .\CortexM3\ARM_GCC_541\Debug\SCLK.o .\CortexM3\ARM_GCC_541\Debug\pot_adc_sar.o .\CortexM3\ARM_GCC_541\Debug\pot_adc_sar_INT.o .\CortexM3\ARM_GCC_541\Debug\pot_adc_sar_PM.o .\CortexM3\ARM_GCC_541\Debug\ui_spi.o .\CortexM3\ARM_GCC_541\Debug\ui_spi_PM.o .\CortexM3\ARM_GCC_541\Debug\ui_spi_INT.o .\CortexM3\ARM_GCC_541\Debug\pot_adc_sar_IRQ.o .\CortexM3\ARM_GCC_541\Debug\pot_adc_sar_theACLK.o .\CortexM3\ARM_GCC_541\Debug\ui_spi_IntClock.o .\CortexM3\ARM_GCC_541\Debug\motor_pwm.o .\CortexM3\ARM_GCC_541\Debug\motor_pwm_PM.o .\CortexM3\ARM_GCC_541\Debug\Clock.o .\CortexM3\ARM_GCC_541\Debug\pin_pwm_x.o .\CortexM3\ARM_GCC_541\Debug\pin_pwm_y.o .\CortexM3\ARM_GCC_541\Debug\pin_enable.o .\CortexM3\ARM_GCC_541\Debug\pin_border.o .\CortexM3\ARM_GCC_541\Debug\isr_border.o .\CortexM3\ARM_GCC_541\Debug\pin_led.o .\CortexM3\ARM_GCC_541\Debug\isr_goal_left.o .\CortexM3\ARM_GCC_541\Debug\pin_goal_right.o .\CortexM3\ARM_GCC_541\Debug\pin_goal_left.o .\CortexM3\ARM_GCC_541\Debug\isr_goal_right.o .\CortexM3\ARM_GCC_541\Debug\isr_ui_spi.o .\CortexM3\ARM_GCC_541\Debug\AMux.o .\CortexM3\ARM_GCC_541\Debug\CyBootAsmGnu.o
arm-none-eabi-ar.exe: creating .\CortexM3\ARM_GCC_541\Debug\Plotterkode.a
arm-none-eabi-gcc.exe -Wl,--start-group -o C:\Users\Vikto\Desktop\plottercode\Plotterkode.cydsn\CortexM3\ARM_GCC_541\Debug\Plotterkode.elf .\CortexM3\ARM_GCC_541\Debug\main.o .\CortexM3\ARM_GCC_541\Debug\cyfitter_cfg.o .\CortexM3\ARM_GCC_541\Debug\cymetadata.o .\CortexM3\ARM_GCC_541\Debug\Cm3Start.o .\CortexM3\ARM_GCC_541\Debug\Plotterkode.a "C:\Program Files (x86)\Cypress\PSoC Creator\4.2\PSoC Creator\psoc\content\cycomponentlibrary\CyComponentLibrary.cylib\CortexM3\ARM_GCC_541\Debug\CyComponentLibrary.a" -mcpu=cortex-m3 -mthumb -L Generated_Source\PSoC5 -Wl,-Map,.\CortexM3\ARM_GCC_541\Debug/Plotterkode.map -T Generated_Source\PSoC5\cm3gcc.ld -specs=nano.specs -u _printf_float -Wl,--gc-sections -u_printf_float -g -ffunction-sections -Og -ffat-lto-objects -Wl,--end-group
.\CortexM3\ARM_GCC_541\Debug\main.o: In function step_respons':
C:\Users\Vikto\Desktop\plottercode\Plotterkode.cydsn/./plotter_position.h:125: undefined reference toexp'
collect2.exe: error: ld returned 1 exit status
The command 'arm-none-eabi-gcc.exe' failed with exit code '1'.
--------------- Build Failed: 04/28/2020 01:34:42 ---------------

A: You are likely not linking the library that includes the exp() function.
It works in the case where you're passing it a literal (or a value the compiler can deduce) because the compiler is computing the value and putting that in the code.
https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
I believe exp() is included in 'libm', so adding -Wl,-lm (or however else you specify libm in your build system) should fix it.
And if it is already there, try putting it at the end of the list.


text:
Q: Flyway doesn't work with SQL Server 2000? Someone know how to use Flyway with SQL Server 2000?

A: Yes, I did. When I use SQL Server 2008 works fine, but using SQL Server 2000 i get this error:

jul 14, 2016 6:31:09 PM
  org.flywaydb.core.internal.util.logging.apachecommons.ApacheCommonsLog
  info INFORMAÇÕES: Database:
  jdbc:jtds:sqlserver://10.211.55.7:1433/hemovida (Microsoft SQL Server
  8.0) Error: Unable to retrieve the current schema for the connection

My code is:
    Flyway flyway = new Flyway();
    flyway.setDataSource("jdbc:jtds:sqlserver://10.211.55.7:1433/dataTest", "sa", "123");
    flyway.setInitOnMigrate(true);
    flyway.setValidateOnMigrate(false);
    try {
        flyway.migrate();
    } catch (Exception ex) {
        System.out.println("Error: " + ex.getMessage());
    }

My migration file is:
CREATE TABLE test_table(
   name varchar(10) NOT NULL
);

I dont know why!


text:
Q: Dash Active_cell and page_current conflict I am trying to link a data table with multiple pages and a graph that displays all the pages of the data table. When I click on the data table, the relevant vertex in the graph is highlighted. When I hover over a vertex, the page_current value in the data table is updated and the active_cell is changed.
The issue I am having is when I update page_current and active_cell in a callback, active_cell updates, then page_current_updates, which clears the active cell. This results in the active_cell only highlighting if the vertex on the graph is in the same page as the data table. If it isn't, the active_cell blinks and the page_current changes, with no cell highlighted. If you unhover then hover over the same point, the active cell will highlight.
I created a workaround by creating a chained callback (which is commented out below) named placeholder. With the chained callback, page_current is updated on the data table and the active cell is passed to the placeholder, which then updates the active cell in the data table. This works, but throws the errors below
:rescue_worker_helmet:
Circular Dependencies
10:31:41 AM
Error: Dependency Cycle Found: data_table.page_current → placeholder.active_cell → data_table.active_cell → placeholder.active_cell
:rescue_worker_helmet:
Invalid prop for this component
10:31:41 AM
Property "active_cell" was used with component ID:
"placeholder"
in one of the Input items of a callback.
This ID is assigned to a dash_html_components.Div component
in the layout, which does not support this property.
This ID was used in the callback(s) for Output(s):
data_table.active_cell
:rescue_worker_helmet:
Invalid prop for this component
10:31:41 AM
Property "active_cell" was used with component ID:
"placeholder"
in one of the Output items of a callback.
This ID is assigned to a dash_html_components.Div component
in the layout, which does not support this property.
This ID was used in the callback(s) for Output(s):
data_table.data, graph.figure, graph-tooltip.show, graph-tooltip.bbox, graph-tooltip.children, placeholder.active_cell, data_table.selected_cells, data_table.page_current, tbl_out.children
Is there a way to link a graph and data table with multiple pages without throwing errors by updating the page_current before the active_cell in a single call back or using a method like the chained callbacks I commented out?
from dash import Dash, dcc, html, Input, Output, no_update, dash_table, State, callback_context
from dash.exceptions import PreventUpdate
import plotly.express as px
import pandas as pd
import dash_bootstrap_components as dbc
import json
from datetime import datetime as dt, timedelta
import plotly.graph_objects as go
import os, sys
import datetime
import re
import time
import numpy as np
from collections import defaultdict

app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
dict_list = [{'fid': 'a1', 'tail': 'test1', 'x': 1, 'y': 1}, {'fid': 'b2', 'tail': 'test2', 'x': 2, 'y': 2},
             {'fid': 'c3', 'tail': 'test3', 'x': 3, 'y': 1}, {'fid': 'd4', 'tail': 'test1', 'x': 2, 'y': 2}, {'fid': 'e5', 'tail': 'test2', 'x': 4, 'y': 4},
             {'fid': 'f6', 'tail': 'test3', 'x': 6, 'y': 4}, {'fid': 'g7', 'tail': 'test1', 'x': 3, 'y': 3}, {'fid': 'h8', 'tail': 'test2', 'x': 6, 'y': 6},
             {'fid': 'i9', 'tail': 'test3', 'x':12, 'y': 10}]
df = pd.DataFrame(dict_list)

app.layout = html.Div(
    dbc.Container([dbc.Row(
                dash_table.DataTable(id='data_table',
                columns=[{"name": i, "id": i} for i in ['fid', 'tail', 'x', 'y']],
                page_current=0,
                page_size=5,
                page_action='custom',
                filter_action='custom',
                filter_query='',
                sort_action='custom',
                sort_mode='multi',
                sort_by=[],
                style_filter_conditional=[{
                'if': {'column_id': 'date_processed'},
                'pointer-events': 'None'}]),
            style={'height': 750, 'overflowY': 'scroll'},
            className='six columns'),
        dbc.Row([dcc.Graph(id="graph",clear_on_unhover=True),
                dcc.Tooltip(id="graph-tooltip",background_color="lightgrey",border_color="blue")]),
        dbc.Row([dbc.Alert(id='tbl_out'), html.Div(id='placeholder')])

]))

operators = [['ge ', '>='],
             ['le ', '<='],
             ['lt ', '<'],
             ['gt ', '>'],
             ['ne ', '!='],
             ['eq ', '='],
             ['contains '],
             ['datestartswith ']]

def split_filter_part(filter_part):
    for operator_type in operators:
        for operator in operator_type:
            if operator in filter_part:
                name_part, value_part = filter_part.split(operator, 1)
                name = name_part[name_part.find('{') + 1: name_part.rfind('}')]

                value_part = value_part.strip()
                v0 = value_part[0]
                if (v0 == value_part[-1] and v0 in ("'", '"', '`')):
                    value = value_part[1: -1].replace('\\' + v0, v0)
                else:
                    try:
                        value = float(value_part)
                    except ValueError:
                        value = value_part

                # word operators need spaces after them in the filter string,
                # but we don't want these later
                return name, operator_type[0].strip(), value

    return [None] * 3

@app.callback(
    Output('data_table', "data"),
    Output('graph', "figure"),
    Output("graph-tooltip", "show"),
    Output("graph-tooltip", "bbox"),
    Output("graph-tooltip", "children"),
    #Output("placeholder", "active_cell"),
    Output("data_table", "active_cell"),
    Output("data_table", "selected_cells"),
    Output('data_table', 'page_current'),
    Output('tbl_out', 'children'),
    Input('data_table', "page_current"),
    Input('data_table', "sort_by"),
    Input('data_table', "filter_query"),
    Input("graph", "hoverData"),
    Input("graph", "figure"),
    Input('data_table', 'active_cell'),
    State('data_table', 'data'),
    State('data_table', "page_size"))

def update_table(page_current, sort_by, filter,  hoverData, dict_fig, active_cell, data_table, page_size):
    dff = get_table(df, page_size, page_current, sort_by, filter)
    triggered_id = callback_context.triggered[0]['prop_id']
    if 'data_table.active_cell' == triggered_id:
        try:
            active_cell, selected_cells, fig = update_graphs(active_cell, data_table, dict_fig)
            return no_update, fig, False, no_update, no_update, active_cell, selected_cells, no_update, F"{callback_context.triggered}-----{callback_context.triggered_prop_ids}---{callback_context.triggered_id}"
        except Exception as e:
            return no_update, no_update,  no_update, no_update, no_update, no_update, no_update, no_update, str(e)

    elif 'graph.hoverData' == triggered_id:
        try:
            #show, bbox, children, active_cell, selected_cells, geojson3, idx, error = update_tooltip_content(hoverData, flights_geojson, flight_data, dff, page_size)
            try:
                show, bbox, children, active_cell, selected_cells, idx, error = update_tooltip_content(hoverData, data_table, dff, page_size)
                hover_rec = hoverData['points'][0]['customdata'][0]
            except:
                hover_rec = None
            if hover_rec is not None:
                fig = go.Figure(dict_fig)
                fig.for_each_trace(lambda trace: trace.update(visible=False) if trace.name == "highlight" else())
                page_current = int((idx)/page_size)
#
                return dff.iloc[
            page_current*page_size: (page_current + 1)*page_size
        ].to_dict('records'), fig, show, bbox, children,active_cell, selected_cells, page_current, page_current
            else:
                return no_update, no_update,  False, bbox, no_update,no_update, no_update, no_update,no_update#F"{idx}:{active_cell}"
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            return no_update, no_update,  no_update, no_update, no_update, no_update, no_update, no_update,F"{exc_type}, {fname}, {exc_tb.tb_lineno}"

    else:
        fig = px.line(dff.sort_values('x').reset_index(drop=True)[['tail', 'fid', 'x', 'y']], x="x", y="y",color="tail",hover_data=[dff.fid])

        fig.update_traces(
            hoverinfo="none",
            hovertemplate=None
        )
        fig.add_scatter(y=[0], x=[0], mode="markers", visible = False, name = 'highlight', hoverinfo='skip', showlegend=False, marker=dict(size=12))

        return dff.iloc[
            page_current*page_size: (page_current + 1)*page_size
        ].to_dict('records'), fig, no_update, no_update, no_update,no_update, no_update, page_current, no_update

#@app.callback(
#    Output("data_table", "active_cell"),
#    Input("placeholder", "active_cell"))
def update_highlight(active_cell):
    return active_cell
def get_table(dff, page_size, page_current, sort_by, filter):
    if filter is not None:
        filtering_expressions = filter.split(' && ')

        for filter_part in filtering_expressions:
            col_name, operator, filter_value = split_filter_part(filter_part)
            if operator in ('eq', 'ne', 'lt', 'le', 'gt', 'ge'):
                # these operators match pandas series operator method names
                dff = dff.loc[getattr(dff[col_name], operator)(filter_value)]
            elif operator == 'contains':
                dff = dff.loc[dff[col_name].str.contains(filter_value)]
            elif operator == 'datestartswith':
                # this is a simplification of the front-end filtering logic,
                # only works with complete fields in standard format
                dff = dff.loc[dff[col_name].str.startswith(filter_value)]

    if len(sort_by):
        dff = dff.sort_values(
            [col['column_id'] for col in sort_by],
            ascending=[
                col['direction'] == 'asc'
                for col in sort_by
            ],
            inplace=False
        )
    return dff.reset_index(drop=True)

def find_xy(fid, json_dict):
    for tail_obj in json_dict:
        i = 0
        for obj in tail_obj['customdata']:
            if obj[0] == fid:
                return tail_obj['x'][i], tail_obj['y'][i]
            i +=1
    return None, None
def find_table_idx(fid, flight_data):
    i = 0
    for row_obj in flight_data:
        if fid == row_obj['fid']:
            return i
        i += 1
    return None

def update_tooltip_content(hoverData, flight_data, dff, page_size):
    try:
        if hoverData is None:
            return no_update, no_update, no_update, no_update, no_update, None, None

        pt = hoverData["points"][0]
        bbox = pt["bbox"]
        fid = hoverData['points'][0]['customdata'][0]
        try:
            idx = dff.index[dff['fid'] == fid][0]
            activecell, selectedcells = [{'column':0, 'row':idx-int(idx/page_size)*page_size, 'column_id': 'noupdate'}, [{'column':0, 'row':idx-int(idx/page_size)*page_size}]]
        except:
            idx = 0
            activecell, selectedcells = [None, []]
        children = [
            html.P(f"Date: {pt['x']}, ASP: {pt['y']}, fid: {fid}")
        ]
        return True, bbox, children, activecell, selectedcells, idx, F"{idx}:{fid}:{dff.index[dff['fid'] == fid][0]}-----{dff.to_json(orient='records')}"
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        return no_update, no_update, no_update, no_update, no_update, 0, F"{dff.to_json(orient='records')}----{idx}:{fid}----{exc_type}, {fname}, {exc_tb.tb_lineno}"

def update_graphs(active_cell, flight_data, dict_fig):
    if active_cell:
        fig = go.Figure(dict_fig)
        fig.for_each_trace(
            lambda trace: trace.update(visible=False) if trace.name == "highlight" else (),
        )
        if active_cell['column_id'] =='fid':
            fid = flight_data[active_cell['row']]['fid']
            x, y = find_xy(fid, dict_fig['data'])

            if x is not None and y is not None:
                fig.for_each_trace(
                    lambda trace: trace.update(visible=True, x=[x], y=[y]) if trace.name == "highlight" else (),
                )
            return active_cell, [active_cell], fig
        elif active_cell['column_id'] =='noupdate':
            return active_cell, [active_cell], no_update
        else:
            return None, [], fig
    else:
        return None, [], no_update
if __name__ == '__main__':
    app.run_server(debug=True) # Running the application```


text:
Q: css bootsrap , align buttons in the div container so here's the problem
i want to align my buttons , in the div
here the result
my view
i've tried some css but it dont work
now i am not using any custom css for this div
here's my blade file

                            <form method="POST" action="{{ route('users.destroy',$user->id) }}">
                              {{ csrf_field() }}
                              {{ method_field('delete') }}

                                  {{-- <!––  //With the  tag you are sending a get request.
                                  that's why we changed it like that because the destroy method require a DELETE request
                                  thank you stackoverflow you saved me  ––> --}}
                              <button type="submit"   class="btn btn-danger" >
                              </button>
                            </form>
                           id) }}"><button  type="button" class="btn btn-primary"></button>
                            id) }}"> <button  type="button" class="btn btn-warning"></button>

A: Add text-nowrap class to the form, and they will be in one line.


text:
Q: Rails building predesigned database I'm a beginner in Rails and I have a complete database designed with a database design tool. (For a startup so quite confidential)
Can I write all the tables and their columns straigth into the migration file and then migrate or should I run the >> rails generate model ...    for every table in my database?
And what about the join tables? Do I need to create them to or do they get created when I write the table classes for association?
I have some experience in MySQL from school so things are a litle strange switching to Rails.
Thanks!

A: I think you need to read more about migrations, specially for join-table, association-tables.
For your question to create all databases, and all tables in one migration file, I think that is valid, but that is bad, you can write code as the following:
class CreateTables < ActiveRecord::Migration
  def change
    create :table_1 do |t1|
      t1.string :name
    end
    create :table_2 do |t2|
      t2.string :name
    end
    # this for join table
    create_join_table :table_1, :table_2
    # this for associations
     add_reference :table_1, :table_2, index: true
  end
end

But this tables will create in your database that is called database.yml file, and you can see your tables using mysql, but if you want to use active-record functions as(new, create, update, save, validations, ...), so you'll need to create model for these tables

A: rails generate model is just a template generator to create

*

*a migration file under db/migrate

*a model file under app/models with some template

*some related test files

All of these can be done manually.
In your case, you can create your migration file (for building the tables) and model file separately, no need to stick with generate function.

A: (1)Can I write all the tables and their columns straight into the migration file and then migrate?
Yes, you can, but I would not recommend it. Because at first you need to create migration files in the db/migrate directory and definition migration class by yourself, I think it is very boring. If Rails can help you do this , you doesn't need to do it yourself, but you should understand how migration works. Secondly, create you needed tables at present unless just a test or small rails application, because customer(maybe yourself) needs and expectations are changing. Perhaps the end you doesn't use some tables at all or change tables frequently.
(2)should I run the >> rails generate model ... for every table in my database?
You are a beginner in Rails, so am I. I suggest you use the rails generate command to create tables, models, controllers..., this is the foundation of Rails learning, and it is very convenience.
(3)And what about the join tables? Do I need to create them to or do they get created when I write the table classes for association?
You can create it by yourself, can also use rails generate command.
Rails guide can provide you with direction and help.


text:
Q: Not able to execute/run vbs file from java on server I have a VBS file xxx.vbs that i'm able to execute it on my local machine using the below code:
 String cmd = "wscript filePath\\xxx.vbs";
 Process p = Runtime.getRuntime().exec(cmd);

But when i create a war file of the project and deploy it on the server, I'm not able to execute the vbs file.
I can however execute the VBS file manually on the server. So there is nothing wrong with the VBS file.
Any idea on what may be the reason for the above?

A: Try adding the below snippet to determine whats happening in the background.
String line="";
          try
            {
            InputStreamReader isr = process.getInputStream();
            BufferedReader br = new BufferedReader(isr,4094);
            while ( (line = br.readLine()) != null)
                System.out.println(line);
            } catch (IOException ioe)
              {
                ioe.printStackTrace();
              }

          try
            {
             isr = process.getErrorStream();
             br = new BufferedReader(isr,4094);
             while ( (line = br.readLine()) != null)
                System.out.println(line);
            } catch (IOException ioe)
              {
                ioe.printStackTrace();
              }

P.S. The above snippet is just for informational purpose.
Runtime.getRuntime().exec() will simply begin the execution, and exits..
Trying the above will eventually show you the exceptions, if any, and the output of the script file you are trying to run.
However, the better way is to create a seperate runnable which can accept the input stream and display its content instead of writing the code I specified above.


text:
Q: Can action force be more than reaction force? It is weird to ask but i want to know if there is any case where the action force can be more than the reaction force.
This question came into my mind when I thought that if a person sits on chair which is weak it breaks. So is it that, that the reaction force applied by chair was less than the action force or the weight of person??

A: The event of breaking of the chair is purely attributed to the material characteristics, and does not violate Newton's Third Law. The material of the chair may have been pre-stressed or may have suffered fatigue loading conditions. Whatever the situation might be, AS LONG AS THE CHAIR IS IN CONTACT WITH THE PERSON, it exerts the same reaction force as exerted by the person. It is just that the material of the chair cannot withstand the applied load. Thus, the chair breaks, breaking off contact between the chair and the person, and essentially releasing the stress.

A: Essentially there are three forces acting on the chair which combined together compress the material of the chair.
If the compressive stress is too large the material deforms catastrophically and breaks.
The three forces and their Newton's third law (equal magnitude and opposite direction) pair (+) are:

*

*The downward force on the chair due to the gravitational attraction
of the Earth + the upward force on the Earth due to the gravitational
attraction of the chair.

*The downward force on the chair due to the person sitting on the chair + the upward force on the person sitting on the chair due to the chair.

*The upward force on the chair due to ground + the downward force on the ground due to the chair.

When the chair breaks it starts to move down and force that the chair exerts on the person sitting on it is reduced.
You know this to be true because then the person who was sitting still on the chair starts to move downwards.
However at the same time the force that the person sitting on the chair exerts on the chair is also reduced by exactly the same amount so Newton's third law still holds true.

A:
can there be any case where action force can be more than reaction force

Newton's 3rd law says that "for every action there is an equal and opposite reaction". So, no, as long as Newton's laws apply this explicitly cannot happen.

As this question came into my mind when i thought that if a person sits on chair which is weak it breaks so is it that, that the reaction force applied by chair was less then the action force or the weight of person??

Here you are mis-analyzing the pairs of forces. The weight is a gravitational force between the earth and the person, it does not involve the chair at all.
The interaction between the chair and the person is a contact force. By Newton's third law the upwards contact force from the chair on the butt is equal and opposite the downwards contact force from the butt on the chair.
Because the chair is weak that upwards contact force on the person is less than the downwards force of the weight, and so by Newton's 2nd law the person accelerates downwards.


text:
Q: How do I bring app to foreground into activity that I left Say someone is using my app, and they get to a critical state, ex they are entering some data. Say at that same time the phone rings so they answer the phone, forcing my app into the background. After the phone call ends, if they click on the icon of my app, I want it to bring them back into the activity they left. How do I do that?
Edit
One thing I forgot to clarify (apologies) is that the activity the user left is not the main activity. I need to re-open the app in an activity that is normally not the main entry point.

A: To keep the system from launching another instance of your activity, you should add launchMode="singleTop" to your activity.
AndroidManifest.xml
<activity
    ....
    ....
    android:launchMode="singleTop" />

What  this will do:
When the user tries to launch your app (after the phone call, for instance), system will check if your launcher activity is already running && at the top of the stack. If it is, a new instance will not be created, and your activity will be resumed. Top of the stack condition is important. Depending on your requirements, you may want to opt for singleTask   launch mode.
More info here: Link


text:
Q: Code to color dupes in row 1 colors only one cell of dupe I want to check for dupes in Row One
The Code below works fine for column ranges like:
 myrng = Range("C2:C" & Range("C65536").End(xlUp).Row)

 and

 If WorksheetFunction.CountIf(Range("C2:C" & cel.Row), cel) = 1 Then

But if I change to Row 1 the code only highlights one cell of the duplicates
Thanks
First Row
Sub HilightDupsRow1()
Dim ws As Worksheet
Dim cel As Variant
Dim myrng As Range
Dim clr As Long, LC As Long, cnt1 As Long, cnt2 As Long

    Set ws = ThisWorkbook.Sheets("Nodes")
    With ws
         LC = .Cells(1, .Columns.Count).End(xlToLeft).Column
         Set myrng = .Range(.Cells(1, 1), .Cells(1, LC))

      myrng.Interior.ColorIndex = xlNone
      clr = 3
      For Each cel In myrng
          If Application.WorksheetFunction.CountIf(myrng, cel) > 1 Then
              If WorksheetFunction.CountIf(.Range(.Cells(1, 1), .Cells(1, cel.Column)) cel) > 1 Then
                  cel.Interior.ColorIndex = clr
                  clr = clr + 1
              Else
                  cel.Interior.ColorIndex = myrng.Cells(WorksheetFunction.Match(cel.Value, myrng, False), 1).Interior.ColorIndex
              End If
          End If
      Next cel
   End With

End Sub

A: Use Collections to get the unique values, then loop through the collections to highlight the duplicates.
Sub UsingCollection()
    Dim cUnique As Collection
    Dim Rng As Range
    Dim Cell As Range
    Dim sh As Worksheet
    Dim vNum As Variant
    Dim LstCol As Long
    Dim c As Long, clr As Long, x, r As Range

    Set sh = ThisWorkbook.Sheets("Nodes")
    With sh

        LstCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        Set Rng = .Range(.Cells(1, 1), .Cells(1, LstCol))
        Set cUnique = New Collection
        Rng.Interior.ColorIndex = xlNone
        clr = 3

        On Error Resume Next
        For Each Cell In Rng.Cells
            cUnique.Add Cell.Value, CStr(Cell.Value)
        Next Cell
        On Error GoTo 0

        For Each vNum In cUnique
            For c = 1 To LstCol
                Set r = .Cells(1, c)
                x = Application.WorksheetFunction.CountIf(.Range(.Cells(1, 1), .Cells(1, c)), r)
                If r = vNum Then
                    If x > 1 Then
                        r.Interior.ColorIndex = clr
                    End If
                End If
            Next c
            clr = clr + 1
        Next vNum

    End With

End Sub


text:
Q: Changing date of GregorianCalendar not saving I have a class that takes a calendar object and prints out the current date. After printing the current date it gives an option to print the previous or next date, however the previous and next aren't working properly.
public void viewDate(Calendar greg) {
//greg is a GregorianCalendar passed in from classA
    Calendar cal = new GregorianCalendar();
    Scanner in = new Scanner(System.in());
    cal = greg.getInstance();
    //print current date

System.out.println("P or N");
    char request = input.nextLine().charAt(0);
    if(request == 'P') {
        cal.add(Calendar.DATE, -1);
        System.out.println(cal.get(Calendar.DAY_OF_MONTH));
        viewDate(cal);
    {//else next...

After changing current date -1 and printing I could see that the date has changed back one day, but when I pass cal back into the method it doesn't save that change. Why?


text:
Q: EJb, direct ServerSocket or any other implementation I am working on a Chatting Website project which will provide similar features as was  like yahoo messenger with chat rooms...
Where multiple clients will connect to the central server and chatting(communication) and file sharing(if possible) will take place.
Now i did a bit of research and i came out with the following choices:
For the client i will use either Winforms or WPF with c#
And for server I am confused between,
Direct Servesocket based application to be deployed on a VPN or a dedicated server,
or EJB based something,
Or any other technology as you may suggest to be suitable for this.
kindly keep somethings in mind:
1. It should be scalable enough to be able to sustain 100 - 1000 to 1,00,000 clients
2. Server should also serve android app as client end.
3. Deployment details also requested


text:
Q: GAE JPA Embedded Annotation Issue Ok so I have an Entity School.
@Entity
public class School implements Serializable
{
private static final long serialVersionUID = -854333301529125138L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long ID;
private String Type;
private String Name;
private String City;
private String Country;

@OneToOne(cascade = CascadeType.PERSIST,fetch=FetchType.LAZY)
private Info information;

@OneToMany(cascade = CascadeType.PERSIST, mappedBy="school",fetch=FetchType.LAZY)
private List<Contact> Contacts;

@OneToMany(cascade = CascadeType.PERSIST, mappedBy="school",fetch=FetchType.LAZY)
private List<Student> students= new ArrayList<Student>();
// more fields and getters and setters.

The Student Class contains lots of student information, and the student transcripts and is as follows
@Entity
public class Student implements Serializable
{

private static final long serialVersionUID = 5426530769458891752L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key ID;
@ManyToOne
private School school;
private long SID;
private final long TSTAMP;
private String FName;
private String LName;
private String Email;
private String SchoolName;

@OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private StudentInfo studentInf = new StudentInfo ();
@OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private Transcript transcript;
 // more fields and getters and setters.

the Transcript Class in the Student Class is as follows
@Entity
public class Transcript
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key ID;
@OneToOne(cascade = CascadeType.ALL, mappedBy="transcript",fetch=FetchType.LAZY)
private Student student;
@Embedded
private Course1 c1;
@Embedded
private Course2 c2;
@Embedded
private Course3 c3;
//... ect
public Transcript()
{
    this.c1= new Course1();
    this.c2= new Course2();
    this.c3= new Course3();
    // ... ect
}

// more fields and getters and setters.

and finally here is a sample course class
@Embeddable
public class Course1 implements Serializable
{
/**
 *
 */
private static final long serialVersionUID = -7643055124732162110L;

private final String CourseTitle = "Course 1 Title";
private boolean MileStone1 = false;
private boolean MileStone2 = false;
// ... ect ... getters and setters
}

All the classes Enhance without a problem and the server runs, but as soon as a Student Instance is created, it results in a total catastrophe in GAE dev server and I have tried alot of possible options with the same error message:
"java.lang.IllegalArgumentException: org.datanucleus.exceptions.NucleusUserException: You have a field db.Entity.student.Student.transcript that has type db.Entity.Courses.Transcript but this type has no known metadata. Your mapping is incorrect"

I would very very much appreciate an explanation on why this is happening and how to fix it while keeping the logical relations


text:
Q: Redireccionar mediante los DNS una carpeta sin afectar su estructura Ya se han visto varias soluciones para no le vemos factible a alguna de ellas, la idea es la siguiente:
tengo midominio.com/ecuador en el cual deseo que al entrar en esa carpeta me busque informacion desde otro servidor pero sin afectar la estructura url
Debido a que midominio.com/ecuador es un sitio en produccion la idea es no tocar nada importante que afecte a las demas estructuras de la pagina web
Probamos con añadir un subdominio ecuador.midominio.com y apuntar los DNS hacia el otro dominio y desde ese servidor poner lo necesario y es factible, pero no queremos perder lo principal que es escribir midominio.com/ecuador
Se probo enmascarar la direcicon url, es decir, desde midominio.com/ecuador crear un archivo que me muestre el otro servidor, pero no es factible ya que tambien la idea de esto es quitarle un peso de encima al servidor


text:
Q: JSDoc: reference @param of method in another @param I am new to using JSDocs and couldn't find an answer to this question.
Suppose I wanted to write this simple function:
function hasQ(array, item) {return array.includes(item);}

which with JSDoc's I would mark-up like:
/**
* Another way to call array.includes(item);
* @param {Array} array
* @param {*} item to test if contained in array
* @returns
*/

Is there a way for me to markup the word array in the second @param statement such that it references the first @param?
This is just a toy example, but I hope it makes the concept clear.

A: Cross-Reference Parameters
Regarding @param as far as I know, there's no way to cross-reference parameters. As suggested here you can use plain English.
As a partial solution, you can use markdown's backticks to highlight the param name (as described here), for example:
/**
 * @param {*} item to test if contained in `array`
 */

Sidenote: Reference External
There's a concept of inline @link to external resources in JSDoc that I guess would be useful here. You can make it clear in your description that for example your talking about the function includes of Array:
/**
* Another way to call [Array's includes function]{@link external:Array#includes}
* @param {Array} array
* @param {*} item to test if contained in array
* @returns
*/
function hasQ(array, item) {
    return array.includes(item);
}

Or if you prefer a link without a text, just remove the part inside [] in the first line:
/**
 * Another way to call {@link external:Array#includes}
 */

Read More
In case you're interested to read more:

*

*@external tag

*inline @link tag

*@see tag

A: There is no way to do that. Source: https://github.com/jsdoc/jsdoc/issues/1145

A: I did not see the possibility of writing related parameters (but see parameters with properties). But you can write description ;)
/**
 * @method
 * @param {Array} array - description for this param
 * @param {*} item - description for this param
 * @description Please write your description for Method
 * @returns {*|boolean}
 */
const hasQ = (array, item) => array.includes(item);


text:
Q: change color of image pixel by pixel I an trying to change color of a png image so that transparent area still remain transparent and give rest of the image a color this is what i tried
<?php

$im = imagecreatefrompng('2.png');
$w = imagesx($im);
$h = imagesy($im);

$om = imagecreatetruecolor($w,$h);

for ($x = 0; $x < $w; $x++) {
    for ($y = 0; $y < $h; $y++) {
        $rgb = imagecolorat($im, $x, $y);
        $colors = imagecolorsforindex($im,  $rgb);

        $orgb = imagecolorallocate($om,$colors['alpha'],$colors['alpha'],$colors['alpha']);
        imagesetpixel($om,$x,$y,$orgb);
    }
}

header('Content-Type: image/png');
imagepng($om);

imagedestroy($om);
imagedestroy($im);

?>

It produce image like:
Before

After

i am still not getting an exact idea how can i get highlighted area of png image and give them a color such as yellow or pink without loosing transparency so that only non-transparent area will get remain transparent

A: You should be able to work with the palette instead of going through every pixel in that case:
<?PHP
    $myRed = 255;
    $myGreen = 0;
    $myBlue = 0;

    $im = imagecreatefrompng('http://s25.postimg.org/ll0dzblan/image.png');
    imageAlphaBlending($im, true);
    imageSaveAlpha($im, true);

    if (imageistruecolor($im))
    {
        $sx = imagesx($im);
        $sy = imagesy($im);
        for ($x = 0; $x < $sx; $x++)
        {
            for ($y = 0; $y < $sy; $y++)
            {
                $c = imagecolorat($im, $x, $y);
                $a = $c & 0xFF000000;
                $newColor = $a | $myRed << 16 | $myGreen << 8 | $myBlue;
                imagesetpixel($im, $x, $y, $newColor );
            }
        }
    } else {
        $numColors = imagecolorstotal($im);
        $transparent = imagecolortransparent($im);

        for ($i=0; $i < $numColors; $i++)
        {
            if ($i != $transparent)
                imagecolorset($im, $i, $myRed, $myGreen, $myBlue, $myAlpha);

        }
    }

    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
?>


text:
Q: Custom prefix for components Angular and WebStorm I initially started a few months ago a project in Angular using Visual Studio Code editor.
Today I made the switch to WebStorm and I also upgraded my project to Angular 4.0.
While my project is running nice without any errors, I receive the following error in WebStorm:

TSLint: The selector of the component "ConnectionStatusComponent"
  should have prefix "app" (
  https://angular.io/docs/ts/latest/guide/style-guide.html#!#02-07) (component-selector)

Following that link I realized that is a good practice to add a custom prefix to component selector to prevent name collisions with components in other apps and with native HTML elements
I understand that. My question is why am I forced to use the app prefix and not other prefix? If I put other prefix then app, WebStorm will mark the line as error.
According to the style guide from that link:

Do use a custom prefix for a component selector. For example, the
  prefix toh represents from Tour of Heroes and the prefix admin
  represents an admin feature area.

I can use whatever prefix I want. Is there a rule on the prefix name?

A: As far as I know, there are no strict rules on prefix name.   If you are using the CLI, you can edit the prefix node under apps in the angular-cli.json.   This will make the cli create new components with whatever prefix you decide.  For tslint.json you can set both component and directive rules:
"directive-selector": [true, "attribute", "app", "camelCase"],
"component-selector": [true, "element", "app", "kebab-case"],

Hope this helps.
EDIT
If you want to use more than one prefix, you can specify them in an array like this(example from here):
//RULES: [ENABLED, "attribute" | "element", "selectorPrefix" | ["listOfPrefixes"], "camelCase" | "kebab-case"]
  "directive-selector": [true, "attribute", ["dir-prefix1", "dir-prefix2"], "camelCase"],
  "component-selector": [true, "element", ["cmp-prefix1", "cmp-prefix2"], "kebab-case"],

*

*In the array, the first argument is a boolean for whether it is
enabled or not.

*The second argument is a union type with choices attribute or
element.

*The third argument is either a string for a single prefix or an array
for a list of prefixes.

*And the fourth argument is a union type of either kebab-case or
camelCase.


text:
Q: Greenplum date/time field out of range: "10/10/2020" I'm testing Greenplum (which is based of Postegres) with a table of this form:
CREATE TABLE whiteglove (bigint BIGINT,varbinary bytea,boolean BOOLEAN,date DATE,decimal DECIMAL,double float,real REAL,integer INTEGER,smallint SMALLINT,timestamp TIMESTAMP,tinyint smallint,varchar VARCHAR)

Then I trying to insert this row using Postegres JDBC driver
INSERT INTO whiteglove VALUES (100000,'68656c6c6f',TRUE,'10/10/2020',0.5,1.234567,1.234,10,2,'4/14/2015 7:32:33PM',2,'hello')

which fails with the following error
org.postgresql.util.PSQLException: ERROR: date/time field value out of range: "10/10/2020"
  Hint: Perhaps you need a different "datestyle" setting.
  Position: 57
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2532)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2267)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:312)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:448)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:369)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:310)
    at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:296)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:273)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:268)

If I take that same query and execute it from terminal using psql it passes without problems
dev=# select * from whiteglove ;
 bigint | varbinary | boolean | date | decimal | double | real | integer | smallint | timestamp | tinyint | varchar
--------+-----------+---------+------+---------+--------+------+---------+----------+-----------+---------+---------
(0 rows)

dev=# INSERT INTO whiteglove VALUES (100000,'68656c6c6f',TRUE,'10/10/2020',0.5,1.234567,1.234,10,2,'4/14/2015 7:32:33PM',2,'hello');
INSERT 0 1
dev=# select * from whiteglove ;
 bigint | varbinary  | boolean |    date    | decimal |  double  | real  | integer | smallint |      timestamp      | tinyint | varchar
--------+------------+---------+------------+---------+----------+-------+---------+----------+---------------------+---------+---------
 100000 | 68656c6c6f | t       | 2020-10-10 |     0.5 | 1.234567 | 1.234 |      10 |        2 | 2015-04-14 19:32:33 |       2 | hello
(1 row)

Any pointers on why I'm getting this out of range error??


text:
Q: Autofilling info from Google Forms to Sheets I'm a lawyer who is completely out of his element here. I've been researching and running tests on Google Script, however, I keep running into issues.
The goal:
Step 1 - Someone completes a Google Form (info includes name, number, etc.);
Step 2 - A NEW template spreadsheet is automatically generated in Google Drive;
Step 3 - The info from the Form is automatically populated within the new template spreadsheet.
Can anyone be a life saver and help me out? Or at least put me out of my misery haha.
Thanks so much in advance!
Update #1:
Based on a comment, here's where I'm at. Good news is that it accomplishes Step 1 and Step 2. Bad news is that I'm still figuring out Step 3, which is probably because I'm so new to this.
Anyways, here's what I have for Step 1 and 2:
function autoFillCaseInfofromIntake(e) {
  var Timestamp = e.values[0];
  var Source = e.values[1];
  var FullName = e.values[2];

  var templatefile = DriveApp.getFileById("I inserted ID here");

  var templatepopulatedfolder = DriveApp.getFolderById("I inserted ID here");

  var copy = templatefile.makeCopy(FullName, templatepopulatedfolder);

  var sheet = DocumentApp.openById(copy.getId());

  sheet.saveAndClose();

Again, sorry for the ignorance!
Update #2:
Big thanks to @arul selvan and @Iamblichus for helping to get me to where I needed to go!
Just in case someone needs the answer in the future:
function autoFillCaseInfofromIntake(e) {
  var Timestamp = e.values[0];
  var Source = e.values[1];
  var FullName = e.values[2];

  var templatefile = DriveApp.getFileById("I inserted ID here");

  var templatepopulatedfolder = DriveApp.getFolderById("I inserted ID here");

  var copy = templatefile.makeCopy(FullName, templatepopulatedfolder);

  var newsheet = SpreasheetApp.openById(copy.getId());
  var sht1 = newsheet.getSheetByName("Sheet1");//open the default sheet 1 or if you want you can rename the sheet or create a new sheet
  sht1.getRange("A1").setValue(Source); //populate any cell with value captured by the form
  sht1.getRange("B1").setValue(FullName);

}

A: You cracked the difficult steps 1 and 2. The Step 3 is easy.
function autoFillCaseInfofromIntake(e) {
  var Timestamp = e.values[0];
  var Source = e.values[1];
  var FullName = e.values[2];

  var templatefile = DriveApp.getFileById("I inserted ID here");

  var templatepopulatedfolder = DriveApp.getFolderById("I inserted ID here");

  var copy = templatefile.makeCopy(FullName, templatepopulatedfolder);

  var newsheet = SpreadsheetApp.openById(copy.getId());
  var sht1 = newsheet.getSheetByName("Sheet1");//open the default sheet 1 or if you want you can rename the sheet or create a new sheet
  sht1.getRange("A1").setValue(Source); //populate any cell with value captured by the form
  sht1.getRange("B1").setValue(FullName);

}

Explanation:

*

*Get the desired sheet with getSheetByName(name).

*Get the cells you want to change with getRange.

*Set the values of the cells with setValue(value).

I'm sure you figured out how to run the above script "On formSubmit"


text:
Q: Flexslider pushing down content when it loads My home page has different sections with anchor tags on them. One of the sections contains a full width 'flexslider' slider. When I link to any anchor on the home page that is below the slider, from another page, the viewport initally goes to the right place. But when flexslider loads it pushes everything down.
I fixed this by defining a fixed width and height for the flexslider container, but that's not a valid solution because my site is responsive.
Any solution would be very much appreciated, I've been at this all day.
EDIT: Markup:

CSS:
/* FlexSlider Necessary Styles
*********************************/
.flexslider {margin: 0; padding: 0;}
.flexslider .slides > li {display: none; -webkit-backface-visibility: hidden;} /* Hide      the slides before the JS is loaded. Avoids image jumping */
.flexslider .slides img {width: 100%; display: block;}
.flex-pauseplay span {text-transform: capitalize;}

When I set a fixed height to the .flexslider class, the page doesn't offset when the slider loads, but that's obv not responsive. I tried using max-height instead, but that didn't "reserve" the space for the slider.

A: In your code, replace all instances of height and width with max-height and max-width. Even on a responsive site, this should not push stuff out of the max boundaries.
If you need more specific help, please post edit your current code into your question.

A: you can reserve the space by adding just two additional CSS lines to the "slides" element.
First, you must get the aspect ratio of your slider by diving the height trough the width of your images, e.g. your images are 2048x820px, the ratio is 820/2048 ~ 0.4.
Then the additional css lines are:
.flexslider .slides {
height: 0;
padding-bottom: 40%; /* if it doesn't fit exactly, try a minimal higher value, eg. 40.05%;  maybe you need to add !important too, to overwrite some previous values */
background: red; /* just for testing purposes, this line can be removed afterwards */
}

A: Instead of using fixed height and width, use max-height and max-width.
Hope this helps you